#!/usr/bin/perl

use strict;
use warnings;
use File::Slurp;

use Ernad::Dates;

print("This script is obsolete\n");
quit()

my $repcode=shift // '';
if(not $repcode) {
  print("I need a repcode\n");
  exit;
}

## staff code
my $stafk=shift // '';

my $impna=$ENV{'IMPNA'};
if($ENV{'impna'}) {
  my $len_impna=length($impna);
  if(substr($repcode,0,$len_impna) ne $impna) {
    $repcode="$impna-$repcode";
  }
}

my $staff_name='selectors';
if($impna ne 'bims') {
  print("I can only do bims.\n");
  exit;
}

if(not length($repcode) == 11) {
  print("Your repcode is not 11 chars long.\n");
  exit;
}

my $home_dir=$ENV{'HOME'};
my $skel_file;
my $skaf_file;
if($stafk) {
  $skel_file="$home_dir/etc/skel_report.amf.xml";
  $skaf_file="$home_dir/etc/skel_staff.amf.xml";
}
else {
  $skel_file="$home_dir/etc/skel.amf.xml";
}
my $conf_file="$home_dir/ernad/etc/$impna/reports/available/$repcode.amf.xml";
my $staff_file="$home_dir/ernad/etc/$impna/$staff_name/$stafk.amf.xml";
my $seed_file="$home_dir/ernad/etc/$impna/seed/$repcode.txt";
if(not $stafk) {
  if(-f $conf_file) {
    system("emacs $seed_file $conf_file");
    system("enable_report $repcode");
    print("I did not run seeds again\n");
    exit;
  }
}
elsif (-f $conf_file and -f $staff_file) {
  system("enable_report $repcode");
  print("I did not run seeds again\n");
  exit;
}

if(not -f $skel_file) {
  print "I don't see the skeleton file $skel_file\n";
  exit;
}

if($stafk and not -f $skaf_file) {
  print "I don't see the skeleton file $skel_file\n";
  exit;
}

if(! -f $conf_file) {
  my $conf=read_file($skel_file);
  $conf=~s|http://biomed\.news/$impna-"|http://biomed.news/$repcode"|;
  $conf=~s|<e:repcode></e:repcode>|<e:repcode>$repcode</e:repcode>|;
  my $today=&Ernad::Dates::today;
  $conf=~s|<e:start></e:start>|<e:start>$today</e:start>|;
  $conf=~s|<person ref=""/>|<person ref="$stafk"/>|;
  write_file($conf_file,$conf);
}

if($stafk) {
  if(not -f $staff_file) {
    my $conf=read_file($skaf_file);
    $conf=~s|http://biomed\.news/$impna-"|http://biomed.news/$stafk"|;
    write_file($staff_file,$conf);
  }
  system("/home/ernad/ernad/bin/append_editorship $stafk $repcode");
  print("emacs $seed_file $staff_file $conf_file\n");
  system("emacs $seed_file $staff_file $conf_file");
}
else {
  system("emacs $seed_file $conf_file");
}

system("/home/ernad/ernad/bin/enable_report $repcode");
system("/home/ernad/ernad/bin/sidat $repcode");
system("/home/ernad/ernad/bin/start $repcode");
system("/home/ernad/ernad/bin/train $repcode");
