#!/usr/bin/env perl

use strict;
use warnings;

my %progparams = ();
while(@ARGV > 3) {
  my $p = shift @ARGV;
  $progparams{$p} = 1;
}

my $verbose = $progparams{"-v"};

my ($fromdir, $renamefile, $todir) = @ARGV;

sub usage {
  my $msg = shift;
  if($msg) { $msg="\n$msg\n" } else {$msg=''}
  die "usage: $0 {options} [fromdir] [renamefile] [todir]\n
  takes files from [fromdir], renames according to the json-map in
  [renamefile] and writes the files to [todir].
  old filenames are used as keys; new filenames as value.

  Options:
    -v verbose output
$msg";
}

usage("missing parameters: fromdir renamefile todir needed") unless $fromdir and $renamefile and $todir;
usage("fromdir is not a directory") unless -d $fromdir;
usage("renamefile is not given") unless -f $renamefile;


#mkdir $todir;
system("mkdir", '-p', $todir);

my %did = ();
my %params = ();

my @errNex = ();

my $fh = undef;
open($fh, '<', $renamefile) or die "Cannot read '$renamefile', because: $!";
my $cont = join '', <$fh>;
close $fh;
if($cont!~m#^\s*\{(.*)\}\s*$#s) { die "'$renamefile' not in an expected format; it should be an json-object" }
my $core = $1;

my %toRename = ();

while($core=~s#^\s*,?\s*"(/?[^"/]+)"\s*:\s*"([^"]+)"##) {
  my ($to, $from) = ($1, $2);
  if ($to =~ m#^/#) {
    $params{$to} = $from;
  } else {
    $toRename{$to} = $from;
  }
}

my $defaultExtension = $params{"/defaultExtension"};
my $license = $params{"/license"};
$license =~ s#\\n#\n#g if defined $license;

for my $to (keys %toRename) {
  my $from = $toRename{$to};
  die "Cannot rename into subdirectories" if $to =~ m#/#;
  my $pfrom = "$fromdir/$from";
  my $pto = "$todir/$to";
  if (defined $defaultExtension and $from !~ m#\.#) {
    $_ .= ".$defaultExtension" for $pfrom, $pto;
  }
  if(-e $pfrom) {
    print "Renaming '$pfrom' to '$pto'\n" if $verbose;
    system("cp", $pfrom, $pto);
    $did{$from} = 1;
    if (defined $license) {
      my $fh = undef;
      open ($fh, '>', "$pto.license") or die "Could not write $pto.license because: $!";
      print $fh $license
    }
  } else {
    push @errNex, $from
  }
}

for(@errNex) {
  warn "Could not rename non-existent file: $_\n" if $verbose;
}

die "Syntax error in [renamefile], could not process everything!" if $core!~m#^[\s*,]*$#;

my $dh = undef;
opendir($dh, $fromdir) or die "Could not read dir '$fromdir', because: $!";
while(my $filename = readdir($dh)) {
  next if $filename=~m#^\.\.?$#;
  warn "Did not touch not mentioned file '$filename'\n" unless $did{$filename} or not $verbose;
}


