#!/usr/bin/env perl 

use strict; 
use warnings; 
use Getopt::Long; 

BEGIN { 
	use Cwd qw/getcwd abs_path/ ; 
	use File::Basename;
	my $script = $0 ; 
	my $script_path = dirname(abs_path($script)); 
	unshift(@INC, $script_path);
}


# load the Verify module
eval "require Tools::Verify";
if($@){
    warn "Unable to load package Tools::Verify: " . $@ . "\n"; 
    exit ;
}

my $verify = Tools::Verify->new(); 
$verify->init(dirname(abs_path($0))); 


# obey the user
my %options ; 
commandParse(); 

if($options{'path'}){ $verify->setSearchPath($options{'path'}) }

if($options{'toolinfo'}){
        $verify->setToolinfo($options{'toolinfo'}) ;
        $verify->parseToolInfo();

        # set up library PATHS specified in the toolinfo file
        my %toolinfo_values = $verify->getToolInfoValues();

        $ENV{'PERL5LIB'} = "/usr/lib/perl5:/usr/lib64/perl5" ;
        if(defined($toolinfo_values{'VCFTOOLS_PERLLIB'})){
                $ENV{'PERL5LIB'} .= ":" . $toolinfo_values{'VCFTOOLS_PERLLIB'} ;
        }
        
	if(defined($toolinfo_values{'PDFAPI2_PM_PATH'})){
                $ENV{'PERL5LIB'} .= ":" . $toolinfo_values{'PDFAPI2_PM_PATH'} ;
        }
       
	if(defined($toolinfo_values{'HTSEQ_LIB_PATH'})){
		$ENV{'PYTHONPATH'} .= ":" . $toolinfo_values{'HTSEQ_LIB_PATH'};
	}

	#print "PYTHONPATH: " . $ENV{'PYTHONPATH'} . "\n"; 
	#print "PERL5LIB: " . $ENV{'PERL5LIB'} . "\n"; 


}

if($options{'prefix'}){ print "PREFIX: " . $options{'prefix'} . "\n"; $verify->setPrefix($options{'prefix'}) }

if($options{'debug'}){ $verify->setDebug($options{'debug'}) }

if($options{'download'}){ $verify->enableDownload(); }

if($options{'install'}){ $verify->enableInstall(); }

if($options{help}){ help(); exit 1; }

if($options{list}){
	$verify->listModules();
	exit 1;
}



# check modules by default
if($verify->checkModules()){ exit 0 ; } else { exit 1 ; }


sub commandParse { 

	my $result = GetOptions (
		"list" => \$options{list},
		"path=s" => \$options{path},
		"toolinfo=s" => \$options{toolinfo},
		"prefix=s" => \$options{prefix},
		"download" => \$options{download},
		"install" => \$options{install},
		"debug=i" => \$options{debug},
		"help" => \$options{help},
		); 
}

sub help { 
	print "$0:\n"; 
	print "\t-list displays a list of prerequisites\n"; 
	print "\t-path <search:path:for:binaries>\n"; 
	print "\t-toolinfo </path/to/toolinfo.txt>\n"; 
	print "\t-prefix </path/to/install/directory>\n"; 
	print "\t-download retrieve any available binaries from listed sources.\n"; 
	print "\t-install build and install binaries (implies -download)\n";
	print "\t-debug <level>\n"; 
	print "\t-help\n"; 
	print "\n"; 
}

