#!/usr/bin/perl

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

use Ernad::Dates;

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

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

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

my $home_dir=$ENV{'HOME'};
my $skel_file="$home_dir/etc/skel.amf.xml";
my $conf_file="$home_dir/ernad/etc/$impna/reports/available/$repcode.amf.xml";
my $seed_file="$home_dir/ernad/etc/$impna/seed/$repcode.txt";
if(-f $conf_file) {
  system("emacs $seed_file $conf_file");
  system("enable_report $repcode");
  exit;
}

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

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>|;
write_file($conf_file,$conf);
system("emacs $seed_file $conf_file");
system("enable_report $repcode");
