#!/usr/bin/perl
use warnings;
use strict;

use POSIX qw(strftime);
use Time::Local;
use autodie;

open(my $find, '-|', 'find queue -type f');
while(<$find>) {
	chomp;
	my @p = split(/\//, $_);
	my $old = $_;
	my $new = $old;
	if ( $#p == 2 ) {
		if ( $p[2] =~ m/^(\d+)\.(.+)/ ) {
			my ( $t, $rest ) = ( $1, $2 );
			my ($date,$time) = split(/ /,strftime("%Y-%m-%d %H:%M:%S", localtime($t)));

			my $new = "$p[0]/$p[1]/$date";
			mkdir $new if ! -d $new;
			$new .= "/$time.$t.$rest";
			rename($old, $new);
		} else {
			warn "OK $old\n";
		}
	} elsif ( $#p == 3 && $p[3] =~ m/(\d\d):(\d\d):(\d\d)\.((up|down|sent).+)/ ) {
			my ( $h, $m, $s, $rest ) = ( $1, $2, $3, $4 );
			my ( $yyyy, $mm, $dd ) = split(/-/,$p[2]);
			my $t = timelocal( $s, $m, $h, $dd, $mm, $yyyy );
			my $new = "$p[0]/$p[1]/$p[2]/$h:$m:$s.$t.$rest";
			rename($old, $new);
	} else {
		warn "OK $old\n";
	}

}
