#!/usr/bin/perl
#This script will set up STARS for first use for species supported by.
#pubmlst.org. Template databases for these MLST schemes are automatically
#downloaded and set up for the user.
#
#Version 0.2 Beta
#Written by Keith Jolley, January 2004
#(c) Copyright 2004, University of Oxford

use warnings;
use strict;

use LWP::Simple;
use Getopt::Std;

###Local configuration values#########################################
my $configfile='templates.cfg';
my $webroot='http://pubmlst.org/software/bio-linux/stars/templates/';
######################################################################

#Check arguments
#s            - setup:  creates required directories
#c <dbase>    - create: creates new database

my %opts;
getopts('sc:', \%opts);
if (!$opts{'s'} and !$opts{'c'}){
    print "Usage: stars_setup.pl [-s] [-c <dbase>]\n";
    exit(1);
}
my $homedir = $ENV{HOME};

#Create STARS working directories
if ($opts{'s'}){
    print "Setting up directories:\n";
    my @dirs=('failed','my_lists','new_data','renamed_traces','session');

    if (!(-d "$homedir/staden")){
	if (mkdir "$homedir/staden"){
	    print "$homedir/staden directory created.\n";
	} else {
	    print "Could not create $homedir/staden directory!\n";
	}
    }
    foreach my $dir (@dirs){
	my $dir = "$homedir/staden/$dir";
	print "$dir ... ";
	if (-d $dir){
	    print "already exists.\n";
	} else {
	    if (mkdir $dir){
		print "created.\n";
	    } else {
		print "creation failed!\n";
	    }
	}
    }
    print "\n";
}

#Create new database
if ($opts{'c'}){
    if (-d "$homedir/PROJECTROOT/$opts{'c'}"){
	print "Database already exists, will not overwrite.\n";
	exit(1);
    }
    if (my $cfg=get ($webroot.$configfile)){
	print "Template list downloaded from pubmlst.org.\n";
	my %templates;
	my @data=split /\n/,$cfg;
	foreach my $template (@data){
	    my ($name,$desc)=split /:/,$template;
	    $templates{$name}=$desc;
	}
	print "The following database templates are available to set up:\n";
	my $i=1;
	my %options;
	$options{'q'}=1;
	$options{'Q'}=1;
	foreach my $template (sort keys %templates){
	    print "$i) $template - $templates{$template}\n";
	    $options{$i}=$template;
	    $i++;
	}
	print "q) Quit\n\n";
	my $response=0;
	while (!$options{$response}){
	    print "Enter template choice: ";
	    chomp ($response=<STDIN>);
	}
	if ($response eq 'q' or $response eq 'Q'){
	    exit;
	}
	my $arcfile="$options{$response}.tar.gz";
	my $dbase=$options{$response};
	print "\nDownloading template $dbase ... ";
	if (system('wget','-q','-r','-nc','-nd',"-P$homedir/tmp/stars_setup","$webroot$arcfile")){
	    print "failed!\n";
	    exit(1);
	} else {
	    print "done\n";
	}
	print "\nCreating new database '$opts{'c'} from template':\n";	
	my $newdb = "$homedir/PROJECTROOT/$opts{'c'}";
	if (-d $newdb){
	    print "$newdb already exists!\n";
	    print "Exiting.\n";
	    exit(1);
	}
	print "Extracting $homedir/tmp/stars_setup/$arcfile ... ";
	if (system('tar','-xzf',"$homedir/tmp/stars_setup/$arcfile",'-C',"$homedir/tmp/stars_setup")){
	    print "failed!\n";
	    exit(1);
	} else {
	    print "done\n";
	}
	if (!(-d "$homedir/PROJECTROOT")){
	    print "Creating $homedir/PROJECTROOT directory ... ";
	    if (mkdir "$homedir/PROJECTROOT"){
		print "done\n";
	    } else {
		print "failed!\n";
		exit(1);
	    }
	}
	print "Modifying template for your setup ... ";
	my $escaped_newdb=$newdb;
	$escaped_newdb=~s/\//\\\//g;
	my $escaped_batch1=$escaped_newdb."\\\/alleles\\\/pregap-db";
	system("sed 's/catch.*pregap-db.*/catch {load_db $escaped_batch1}/g' $homedir/tmp/stars_setup/$dbase/data/batch1.config > $homedir/tmp/stars_setup/batch1.config");
	system('cp','-fr',"$homedir/tmp/stars_setup/batch1.config","$homedir/tmp/stars_setup/$dbase/data/batch1.config");
	my $escaped_vecpath=$escaped_newdb."\\\/alleles";
	system("sed 's/PATH/$escaped_vecpath/g' $homedir/tmp/stars_setup/$dbase/alleles/pregap-db > $homedir/tmp/stars_setup/pregap-db");
	system('cp','-fr',"$homedir/tmp/stars_setup/pregap-db","$homedir/tmp/stars_setup/$dbase/alleles/pregap-db");
	print "done\n";
	print "Copying template to $newdb ... ";
	if (system('cp','-fr',"$homedir/tmp/stars_setup/$dbase",$newdb)){
	    print "failed!\n";
	    exit(1);
	} else {
	    print "done\n";
	}
	print "\nSetting as default database in your start-up script (.zshrc):\n";
	if (system('grep','-q','MLST_DEF_PROJECT',"$homedir/.zshrc")){
	    print "MLST_DEF_PROJECT not defined in .zshrc\n";
	    print "Adding definition to .zshrc ... ";
	    open (ZSHRC,">>$homedir/.zshrc") or die "can't open .zshrc.\n";
	    print ZSHRC "\nexport MLST_DEF_PROJECT=$newdb";
	    close ZSHRC;
	    print "done\n";
	} else {
	    print "MLST_DEF_PROJECT already defined in .zshrc\n";
	    print "Changing default project in .zshrc ... ";
	    #Remove line defining MLST_DEF_PROJECT and send to temp file
	    system("sed 's/.*MLST_DEF_PROJECT.*//g' $homedir/.zshrc > $homedir/tmp/stars_setup/zshrc");
	    open (ZSHRC,">>$homedir/tmp/stars_setup/zshrc") or die "can't open temporary file.\n";
	    print ZSHRC "export MLST_DEF_PROJECT=$newdb";
	    close ZSHRC;
	    system ('cp','-fr',"$homedir/tmp/stars_setup/zshrc","$homedir/.zshrc");
	    print "done\n";
	}
	print "\nType 'source .zshrc' from your home directory for the default database to be set immediately, otherwise it will be set the next time you start a new shell.\n"; 
	print "\nCleaning up temporary files ... ";
	if (system('rm','-fr',"$homedir/tmp/stars_setup")){
	    print "failed!\n";
	} else {
	    print "done\n";
	}
    } else {
	print "Cannot download template list!\n";
	print "Exiting.\n";
	exit(1);
    }
}
