#!/usr/bin/perl

use utf8;
use Config::Simple;
use Data::Dumper::Concise;

my $exps = qq/.log .log.zip .command.log .b25.log .mencoder.log .x264.log .mp4box.log .ts.b25 .ts.tsmix .ts .mp4 .264 .mp3 .aac .wav .m2v/;
$exps =~ s/ /|/g;
$exps =~ s/\./\\./g;

my $cfg = new Config::Simple;
$cfg->read('/etc/rec10.conf');

my $recording = $cfg->param('path.recpath');
opendir(DIR, $recording);
my @files = readdir(DIR);
closedir(DIR);

my @failed;
my %files;

foreach (@files) {
	next if ($_ eq '.' || $_ eq '..' || -d "$recording/$_");
	my ($file, $exp) = $_ =~ /(.+?)($exps)\Z/;
	if ($file eq '' || $file =~ /\.\w+\Z/) {
		push(@failed, $_);
	}
	$files{$file}->{$exp} = '';
}

if (@failed) {
	die "Unknown exps: @failed";
}

foreach (keys %files) {
	my @existing_exps = keys %{$files{$_}};
	my @existing_exps_with_log    = grep( /log/, @existing_exps);
	my @existing_exps_without_log = grep(!/log/, @existing_exps);
	if ( @existing_exps_with_log == @existing_exps ) {
		print "$_ @existing_exps\n";
		foreach my $exp (@existing_exps) {
			system "mv '$recording/$_$exp' '$recording/log/$_$exp'\n";
		}
	}
	elsif ( @existing_exps_without_log == 1 and $existing_exps_without_log[0] eq '.mp4' ) {
		print "only mp4 remaining: $_\n";
		foreach my $exp (@existing_exps_with_log) {
			system "mv '$recording/$_$exp' '$recording/log/$_$exp'\n";
		}
	}
}

