#!/usr/bin/perl -w
use strict;
use POSIX qw(strftime);

my ($list_file,$oldrel,$newrel);

if(!$ARGV[2]){ die "# usage: $0 <list species> <old release> <new release>\n" }
else{ 
    ($list_file,$oldrel,$newrel) = @ARGV;
}

# copy current list of supported organisms
my $now = strftime("%Y%m%d", localtime());
system("cp data/supported_organisms.tab data/supported_organisms.tab.$now"); 

open(LIST,"<",$list_file) || die "# cannot read $list_file\n";
while(<LIST>){
    next if(/^#/);
    my $species = (split)[0];
    my $updated_species = $species;
    $updated_species =~ s/.$oldrel$/.$newrel/;

    print "$species -> $updated_species\n";

    # update data folders
    my $lcspecies = lc((split(/\./,$species))[0]);
    system("make -f makefiles/ensemblgenomes_FTP_client.mk GROUP=Plants ".
       "RELEASE=$oldrel NEXTRELEASE=$newrel SPECIES=$lcspecies upgrade_one_species\n");

    system("make -f makefiles/ensemblgenomes_FTP_client.mk GROUP=Plants ".
       "RELEASE=$newrel SPECIES=$lcspecies prepare_gtf_install\n");

    # update list of supported organisms, note that some fields remain unchanged
    system("perl -i -pe 's/$species/$updated_species/g;' data/supported_organisms.tab");
}
close(LIST);

