#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);
use Data::Dumper;
use File::Path;
#use Getopt::Std;

use Ernad::Args;
use Ernad::Erimp;
use Ernad::Presort::Seeds;

our ($impna, $e, $repcode);
&Ernad::Args::parse();
$e=Ernad::Erimp->new({'impna'=> $impna,
                      'repcode'=>$repcode,
                      'verbose'=>3});
if(not $repcode) {
  print "I don't see your repcode.\n";
  exit;
}

my $admin_user=$e->{'conf'}->{'admin_user'};
if(not $admin_user) {
  die "I can't run this script without a configured 'admin_user'";
}

my $rerc=$e->{'report'}->{$repcode} // confess "I don't see your report $repcode.";

## FixMe: there should be more standards-compatible way
my $repdir=$e->{'dir'}->{'reports'}.'/'.$repcode;

## FixMe: should be in erimp
my $archive_dir=$e->{'dir'}->{'var'}.'/archive/reports';
my $archrep_dir=$archive_dir.'/'.$repcode;
if(not -d $archrep_dir) {
  mkpath($archrep_dir);
}

my $s="rsync -va --exclude opt $repdir/ $archrep_dir";

# print "$s\n";
system($s);
if(-d "$archrep_dir/notify") {
  $s="rm -rf $archrep_dir/notify";
  print "$s\n";
}

## unzip all the contents
$s="find $archrep_dir -name '*.gz' -exec gunzip {} \\;";
print "$s\n";
system($s);

my $seed_conf_orig_file=$e->{'dir'}->{'seed_conf'}."/$repcode.txt";
print "$seed_conf_orig_file\n";
my $seed_conf_dest_file="$archrep_dir/seed.txt";
if(-f $seed_conf_orig_file) {
  if(not -f $seed_conf_dest_file) {
    $s="cp $seed_conf_orig_file $seed_conf_dest_file";
    print "$s\n";
    system($s);
  }
  if(-f $seed_conf_orig_file and -f $seed_conf_dest_file) {
    $s="sudo -u $admin_user rm $seed_conf_orig_file";
    print "$s\n";
    system($s);
  }
  if(not -f $seed_conf_orig_file and not -f $seed_conf_dest_file) {
    die "I have neither $seed_conf_orig_file nor $seed_conf_dest_file.";
  }
}

my $reports_file=$e->{'file'}->{'reports'};
$s="cp $reports_file $archrep_dir/.";
print "$s\n";

$s="cd $archive_dir ; /bin/tar -czf $archive_dir/$repcode.tar.gz $repcode";
print "$s\n";
system($s);

my $var_dir=$e->{'dir'}->{'var'};
foreach my $dir (`find $var_dir/ -type d -name $repcode`) {
  chomp $dir;
  if($dir=~m|archive|) {
    next;
  }
  $s="rm -rf $dir";
  print "$s\n";
  system($s);
}

print "Now edit ~/ernad/var/bims/blatt/sborn/reports.html.\n";
print "Now edit the reports file as bims\n";


__END__;
