#!/usr/bin/perl

## make sure we can run this from bims via sudo from pubmed
use lib qw(/home/ernad/ernad/perl /home/ernad/usr/share/perl /home/ernad/lib/perl);

use strict;
use warnings;

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

use Ernad::Args;
use Ernad::Adverts;
use Ernad::Bremse;
use Ernad::Constant;
use Ernad::Common;
use Ernad::Dates;
use Ernad::Erimp;
# use Ernad::Issues;
use Ernad::Namf;
use Ernad::Notify;
use Ernad::Presort::Seeds;
use Ernad::Presort::Dates;
use Ernad::Presort;
use Krichel::File;

my %options;
&getopts('lBbpabItfx:r:v:m', \%options);

## last issue, rather that issue file
my $do_last=$options{'l'} // '';
## for the brown period
my $do_brown=$options{'b'} // '';
## for just testing the bremse
my $do_only_activity=$options{'a'} // '';
## do only one repcode
my $only_do_repcode=$options{'r'} // '';
## ignore bremse
my $no_bremse=$options{'B'} // '';
my $do_batch=$options{'b'} // '';
## are we invoked by batch?
my $invoked_by_batch=$options{'I'};
my $exclude_repcode=$options{'x'} // '';
my $do_testing=$options{'t'};
# # don't check for mupliple instances
my $allow_multi=$options{'m'} // '';
my $dont_truncate=$options{'f'};
## disable counting of texts in rif at the start, this takes
## a lot of time
my $do_verbose=$options{'v'} // 2;
# # 2021-07-03 make default
my $python_presort=$options{'p'} // '1';

#if(not $allow_multi) {
#  use Sys::RunAlone;
#}

our ($impna, $e, $repcode, $in_file);

if($do_brown) {
  &Ernad::Args::parse();
  $e=Ernad::Erimp->new({'impna'=> $impna, 'verbose'=>3});
  ## addition for brown period
  my $brown_dir=$e->{'conf'}->{'brown_dir'};
  if(not $brown_dir) {
    print("Your brown_dir is not set\n");
    exit;
  }
  if(not -d $brown_dir) {
    print("Your brown_dir $brown_dir does not exists.");
    exit;
  }
  my $today=&Ernad::Dates::today();
  if($brown_dir) {
    my $brown_fufi="$brown_dir/$today.amf.xml.gz";
    my $issue_fufi=$e->{'dir'}->{'issues'}.'/'.$e->{'f'}->by_date($today);
    $in_file.="$issue_fufi.gz";
    if(not -f $brown_fufi) {
      print("I don't see your $brown_fufi\n");
      exit;
    }
    my $s="/bin/cp -a $brown_fufi $in_file";
    print("$s\n");
    system($s);
  }
}
else {
  ## overwrite files that exist?
  $in_file=$ARGV[0];
  if(not $in_file) {
    if(not $do_last) {
      print("With no issue file, I need -l\n");
      exit;
    }
  }
  if(not $do_last) {
    if(not -f $in_file) {
      print "I can't open the naf $in_file.\n";
      if(not -f "$in_file.gz") {
        print "I can't open the naf $in_file.gz.\n";
        exit;
      }
      $in_file="$in_file.gz";
    }
  }
  &Ernad::Args::parse();
  $e=Ernad::Erimp->new({'impna'=> $impna, 'verbose'=>3});
}

if($do_last) {
  my $issues_dir=$e->{'dir'}->{'issues'};
  $in_file=$e->{'d'}->last_rif($issues_dir);
}

my $b=Ernad::Bremse->new($repcode);
my $batch_fh;
my $batch_tmp_fufi;
if($do_batch) {
  $batch_tmp_fufi="/tmp/release_$impna";
  $batch_fh = IO::File->new("> $batch_tmp_fufi");
  print $batch_fh "#!/bin/bash\n\n";
}

## to keep old variable naming
my $naf=$in_file;
## this could take time in batch mode
if(not $invoked_by_batch) {
  if(not $e->{'x'}->count_texts($naf)) {
    print "I don't see any texts in your naf $naf\n";
    exit;
  }
}



my $namf=$Ernad::Constant::c->{'namf_dir'}
   or confess "You have not defined a namf_dir name.";
my $allport_repcode = $e->get_allport_repcode() // '';

## check for a holiday
my $today=&Ernad::Dates::today();
my $holiday_regex=$e->{'conf'}->{'holidays'} // '';
if($holiday_regex and $today=~m|$holiday_regex| and not $do_testing) {
  $e->echo(__LINE__,"Today, $today, is a holiday. I relax.");
  exit;
}

## I always test on the test machine
if($e->{'testing'}) {
  $do_testing=1;
}

## fixme:: to go in 2019
our $issuedate=&Ernad::Presort::Dates::set_issuedate($naf,$do_testing);
$e->{'file'}->{'namf'}=$naf;

## build cache for the selection screen
my $cache_selection_screen= sub {
  ## this is handed by the caller
  my $repcode=shift;
  ## reset key
  $e->{'repcode'}='';
  $e->{'issuedate'}='';
  $e->{'namf'}='';
  my $rerc=$e->{'report'}->{$repcode};
  if($only_do_repcode and $only_do_repcode ne $repcode) {
    $e->echo(__LINE__,"I skip $repcode.",10);
    return 0;
  }
  $e->{'repcode'}=$repcode;
  ## global variable
  $e->{'issuedate'}=$issuedate;
  my $namf=shift;
  my $cache_dir=$e->{'report'}->{$repcode}->{'dir'}->{'cache'} //
    confess "I need the cache_dir defined here.";
  my $cc_dir=$cache_dir.'/'.$e->{'const'}->{'created_dir'};
  my $cache_file=$cc_dir."/$issuedate.html";
  &Krichel::File::prepare($cache_file);
  ## fixme:: add some checks of it being newer that the namf file
  ## fixme ... I just made this up
  my $params= {'back_from' => "'source'",
               'stage' => "'created'",
               'Report' => "'$repcode'",
               'repcode' => "'$repcode'"};
  ## case before unisource
  my $ps_dir=$rerc->{'dir'}->{'presorted'};
  my $source_dir=$rerc->{'dir'}->{'source'};
  if($e->{'d'}->has_it_file($source_dir)) {
    $ps_dir=$source_dir;
  }
  ## ps_file file first
  #my $ps_file=$ps_dir.'/'.&Ernad::Common::get_most_recent_rif($ps_dir,'lax',$issuedate);
  my $ps_bana=$e->{'d'}->most_recent_rif($ps_dir,'lax',$issuedate);
  if(not $ps_bana) {
    $e->echo(__LINE__,"I can not cache the selection screen for $repcode.");
    return 0;
  }
  my $ps_file=$ps_dir.'/'.$ps_bana;
  ## if this does not exist,
  if(not -f $ps_file) {
    $ps_file=$e->{'d'}->most_recent_rif($ps_dir,'lax',$issuedate);
  }
  if(not -f $ps_file) {
    $e->echo(__LINE__,"I don't see your ps_file $ps_file");
  }
  if(not $e->{'d'}->most_recent_rif($ps_dir,'lax',$issuedate)) {
    $e->echo(__LINE__,"I have no rif in $ps_dir and issuedate $issuedate");
    return 0;
  }
  #if(not $e->{'d'}->most_recent_rif($ps_dir,'lax',$issuedate)) {
  #  $e->echo(__LINE__,"I have no rif in $ps_dir and issuedate $issuedate");
  #}
  if($ps_file) {
    if(not &Ernad::Files::does_file_need_renewal($cache_file,$ps_file)) {
      $e->echo(__LINE__,"$cache_file needs no renewing over $ps_file.");
      return 0;
    }
    if(-d $ps_file) {
      return 0;
    }
    if(not $ps_file=~m|$issuedate|) {
      $e->echo(__LINE__,"I found '$ps_file'. It does not match my issuedate '$issuedate'.");
      return 0;
    }
    $e->echo(__LINE__,"I found $ps_file. I start to transform papers_screen...");
    my $doc=$e->{'t'}->transform_file($ps_file,'papers_screen',$params);
    $doc->toFile($cache_file);
    $e->echo(__LINE__,"I'm wrote $cache_file.");
    return 1;
  }
  $e->echo(__LINE__,"I should not be here.");
};


my $releaser = sub {
  ## this is handed by the caller
  my $repcode=shift;
  my $bremsed=0;
  if($only_do_repcode and $only_do_repcode ne $repcode) {
    $e->echo(__LINE__,"I skip $repcode.",10);
    return 0;
  }
  ## the bremse should be in a seperate loop
  if(not $no_bremse) {
    if($e->{'conf'}->{'bremse'} and (not $invoked_by_batch or $do_only_activity)) {
      $b->report($repcode);
      $bremsed=$b->is_bremsed($repcode);
      if($bremsed) {
        print("$repcode is bremsed\n");
        my $doc=$b->doc($repcode);
        $b->notify($doc, $repcode);
        return;
      }
      if($do_only_activity) {
        print("$repcode is bremsed, I tested that.\n");
        return;
      }
    }
  }
  ## in batch mode, just write the file
  my $log_dir=$e->{'dir'}->{'log'};
  my $log_file="$log_dir/release/$issuedate"."_$repcode";
  my $log_part="> $log_file.out 2> $log_file.err";
  if($do_batch) {
    if($python_presort) {
      my $do=$e->{'dir'}->{'bin'} . "/class -c $repcode $issuedate";
      my $log_part="> $log_file.class.out 2> $log_file.class.err";
      $do.=" $log_part\n";
      print $batch_fh $do;
    }
    ## -I says: I have been invoked in the batch made
    ## -m says: allow for multiple instances running
    my $do=$e->{'dir'}->{'bin'} . "/release -I -m -r $repcode $in_file";
    $do.=" $log_part\n";
    print $batch_fh $do;
    return;
  }
  ## reset key
  $e->{'repcode'}='';
  $e->{'issuedate'}='';
  $e->{'namf'}='';
  ## maybe put ahead
  if($dont_truncate) {
    $e->{'conf'}->{'truncate'}=0;
  }
  $e->{'repcode'}=$repcode;
  $e->{'issuedate'}=$issuedate;
  my $rerc=$e->{'report'}->{$repcode};
  if(not $e->{'report'}->{$repcode}) {
    ## this is temporary for non-Osborne
    if($e->{'r'}) {
      $e->{'r'}->load($repcode);
    }
  }
  my $namf=shift;
  $e->echo(__LINE__,"I'm looking at $repcode for work to do.");
  $e->echo(__LINE__,"I have to do $repcode $issuedate $naf.");
  ## up there is the wrong issuedate
  # die $issuedate;
  ## saves to report in the next module
  $e->{'repcode'}=$repcode;
  $e->{'issuedate'}=$issuedate;
  $e->{'namf'}=$namf;
  $e->echo(__LINE__,"I presort for $repcode.",1);
  my $ps_rif;
  if($python_presort) {
    $e->echo(__LINE__,"I use python presort for $repcode.",1);
    my $python_out_fufi=$rerc->{'dir'}->{'mocla'}.'/'.$issuedate.'.amf.xml.gz';
    if(not -f $python_out_fufi) {
      my $do=$e->{'dir'}->{'bin'} . "/class $repcode $issuedate";
      my $log_part="> $log_file.class.out 2> $log_file.class.err";
      $do.=" $log_part\n";
      system($do);
      if(not -f $python_out_fufi) {
        $e->echo(__LINE__,"After python call, '$do' no $python_out_fufi.",1);
        warn("no $python_out_fufi, continue with perl");
        ###
        exit;
        ###
        $ps_rif=&Ernad::Presort::presort($repcode,$issuedate,$namf);
      }
    }
    my $source_dir=$rerc->{'dir'}->{'source'} or die;
    $ps_rif=$source_dir.'/'.$e->{'f'}->by_date($issuedate);
    system("/bin/zcat $python_out_fufi > $ps_rif");
  }
  else {
    $ps_rif=&Ernad::Presort::presort($repcode,$issuedate,$namf);
  }
  if(not $ps_rif) {
    return 0;
  }
  &Ernad::Adverts::inject_adverts_into_rif($ps_rif,$e);
  $e->echo(__LINE__,"I placed adverts into $ps_rif.");
  #&Ernad::Notify::notify($e,$ps_rif);
  if(! $e->{'testing'}) {
    &Ernad::Notify::notify($ps_rif);
  }
  my $transit_style_fufi = $e->{'dir'}->{'style'} . '/transit.xslt.xml';
  ## avoid a system call for bims
  if( -f $transit_style_fufi) {
    my $transit_bin_fufi = $e->{'dir'}->{'bin'} . '/transit';
    system("$transit_bin_fufi $ps_rif");
  }
  ## add cache here
  &$cache_selection_screen($repcode, $naf);
};


## main call
#$e->call_on_all_reports($releaser,$naf,$only_do_repcode);
#$e->call_on_all_reports($cache_selection_screen,$naf);
$e->{'o'}->call_by_lafise($releaser,$naf,$only_do_repcode);
if($do_batch) {
  $batch_fh->close();
  system("/bin/chmod 755 $batch_tmp_fufi");
  system($batch_tmp_fufi);
}
elsif(not $do_only_activity) {
  $e->{'o'}->call_on_all_reports($cache_selection_screen,$naf);
}

exit;


sub delete_already_there {
  my $us_ps=shift;
  my $repcode=shift;
  my $issuedate=shift;
  ## except the file, to delete all others after creation
  my $except=shift // '';
  if(($us_ps ne 'unsorted') and ($us_ps ne 'presorted')) {
    die 'us_ps has to be unsorted or presorted.';
  }
  $e->echo(__LINE__,"I delete $repcode $issuedate $us_ps except $except",1);
  my $rerc=$e->{'report'}->{$repcode};
  if(not $e->{'report'}->{$repcode}) {
    ## this is temporary for non-Osborne
    if($e->{'r'}) {
      $e->{'r'}->load($repcode);
    }
  }
  my $dir=$rerc->{'dir'}->{$us_ps} or confess "I need this here.";
  my @already_there_files=glob("$dir/$issuedate*");
  foreach my $file (@already_there_files) {
    if($except and $file eq $except) {
      $e->echo(__LINE__,"I keep except $file",3);
      next;
    }
    $e->echo(__LINE__,"I remove $file",3);
    unlink $file;
  }
}


__END__

1;
