#!/usr/bin/perl

use strict;
use warnings;

use Ernad::Dates;
use Date::Format;
use File::Copy;
use File::Basename;
use File::Path;
use File::Spec;

my $file = $ARGV[0] // die "I need a file";
## save the original value
my $in_file=$file;
if(not -f $file) {
  die "I can't seen the file $file";
}


# File::Spec->rel2abs():

my $fufi=File::Spec->rel2abs($file);
my $date=&Ernad::Dates::mdate($fufi);
my $target=$fufi;
$target=~s|/home/ernad/ernad/|/home/ernad/ernad/obsolete/|;
$target=~s|/home/ernad/nitpo/|/home/ernad/nitpo/obsolete/|;
my $obs_dir=dirname($target);
my $bana=basename($target);

# target bana to take acount of ending ~
$bana=~s|~$||;

my $copy;
if($bana=~m|(.+)\.(xslt\.xml)$|) {
  my $name=$1;
  my $ext=$2;
  $copy=$obs_dir.'/'.$name.'_'.$date.".$ext";
}
elsif($bana=~m|(.+)\.([^.]+)$|) {
  my $name=$1;
  my $ext=$2;
  $copy=$obs_dir.'/'.$name.'_'.$date.".$ext";
}
else {
  $copy=$obs_dir.'/'.$bana.'_'.$date;
}

if(-f $copy and not -z $copy) {
    print "I found the copy $copy. I will leave it as it is.\n";
    exit;
}

print "I save '$file' as '$copy'.\n";
if(not -f $file) {
  die "I don't see $file";
}
copy($file,$copy);
if(-z $copy) {
  die "The copy of $file is empty!"
}
system("/usr/bin/touch -r $in_file $copy");
