#!/usr/bin/env perl
use warnings;
use strict;
use Getopt::Long;
use FindBin qw($Bin $Script);
use File::Basename qw(basename dirname);
use Cwd qw(abs_path);
my %opts;
GetOptions(\%opts,"c=s","s=s","h");
if(!defined($opts{c}) || !defined($opts{s}) ||defined($opts{h})){
	print <<"	Usage End.";
Description:
              Version:v2.1.7

Usage:
    -c        cfg file         <infile>     must be given
    -s        run step         <int>        must be given
              step number:
              0:                  run all step
              1:                  run fastq2BcUmiSC
              2:                  run cellranger count
              3:                  run cluster
              4:                  run web report

	-h        Help document
	
	Example：
              BSCMatrix -c config.txt -s 0
              BSCMatrix -c config.txt -s 1,2,3,4
	
	
	Usage End.
	exit;
}

################检查软件是否存在
die "The seqkit dose not exists, please check the environment variables are configured properly!" if !`which seqkit`;
my $barcode;
if(!`which cellranger`){
    die "The Cell Ranger dose not exists, please check the environment variables are configured properly!\n";
}else{
    ##版本判断
    my $version = `cellranger --version`;
    chomp $version;
    $version = (split /-/,$version)[1];
    my @allowed_versions = ('7.0.0', '7.1.0', '7.2.0', '8.0.0', '8.0.1','9.0.0');
    if(!grep { $version eq $_ } @allowed_versions){
        die "cellranger must be one of " . join(", ", @allowed_versions) . "\n";
    }
    ##定义barcode类型
    if($version eq '9.0.0'){
        $barcode = "$Bin/ref_file_SC/version2.txt.gz";
    }else{
        $barcode = "$Bin/ref_file_SC/version1.txt.gz";
    }
}

###############Time
my $Time_Start;
$Time_Start = sub_format_datetime(localtime(time()));
&show_log("Start Time :[$Time_Start]");
################
$| = 1 ;
## get parameters
my $cfgfile = abs_path($opts{c});
my $step = $opts{s} ;

## reading cfg file
my %hcfg = ();
&reading_cfg_file($cfgfile, \%hcfg);

## run process
&run_process($step, \%hcfg);

###############Time
my $Time_End;
$Time_End = sub_format_datetime(localtime(time()));
&show_log("End Time :[$Time_End]");

#################################log
sub reading_cfg_file()
{
    my ($cfgfile, $ahcfg) = @_ ;

    open (IN, $cfgfile) || die "$cfgfile, $!\n" ;
    while(<IN>){
        chomp ;
        next if (m/^\#|^\s*$/);
        my ($key, $value) = split /\s+/ ;
        $ahcfg->{$key} = $value ;
    }
    close(IN);
    ###检查配置文件是否齐全，如果不全，退出并告诉程序执行者补充完整
    die "The FQ1 dose not exists, please check $cfgfile\n" if(!exists $ahcfg->{FQ1});
    die "The FQ2 dose not exists, please check $cfgfile\n" if(!exists $ahcfg->{FQ2});
    die "The FA dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{FA});
    die "The GTF dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{GTF});
    die "The OUTDIR dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{OUTDIR});
    die "The PREFIX dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{PREFIX});
    die "The EC dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{EC});
    die "The Threads dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{Threads});
    die "The RAM dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{RAM});
    die "The Nobam does not exists,please check $cfgfile\n" if (!exists $ahcfg->{Nobam});
    return ;
}


sub run_process()
{
    my ($step, $ahcfg) = @_ ;

    my @numbers = split /\,/, $step ;
    @numbers = sort {$a<=>$b} @numbers ;
    if ($numbers[0] == 0){
        @numbers = (1,2,3,4);
    }
    my $result_dir = $ahcfg->{OUTDIR};
    mkdir $result_dir if (!-d $result_dir) ;
    $result_dir = abs_path($result_dir);
    my $prefix = $ahcfg->{PREFIX} ;
    for my $num (@numbers){
        if ($num == 1){
            my $outdir = "$result_dir/01.fastq2BcUmiSC" ;
            mkdir $outdir if (!-d $outdir) ;
            my $cmd = "perl $Bin/tools/fastq2BcUmiSC -i1 $ahcfg->{FQ1} -i2 $ahcfg->{FQ2} -d $outdir -p $prefix -t $ahcfg->{Threads}" ;
            if (defined $ahcfg->{KmerFile}){
                $cmd .= " -k $ahcfg->{KmerFile}" ;
            }
            &run_or_die($cmd) ;
        }
        elsif ($num == 2){
            my $outdir = "$result_dir/02.cellranger" ;
            mkdir $outdir if (!-d $outdir) ;
            my $prefix = $ahcfg->{PREFIX};
            my $bc_umi  = "$result_dir/01.fastq2BcUmiSC/$prefix.umi" ;
            my $cmd = "cd $outdir && perl $Bin/tools/From_bmk_to_10x_v2.2.pl -b $barcode -s $bc_umi -c $cfgfile \n";
            &run_or_die($cmd) ;
        }
        elsif ($num == 3){
            my $outdir = "$result_dir/03.cluster" ;
            mkdir $outdir if (!-d $outdir) ;
            my $matrix = "$result_dir/02.cellranger/$prefix/outs/filtered_feature_bc_matrix";
            my $R_env = "";
            $R_env = "export PATH=".$ahcfg->{Rscript}.":\$PATH && " if defined $ahcfg->{Rscript};
            my $cmd = "$R_env Rscript $Bin/tools/cluster.R -i $matrix -o $outdir --MinCell 5 --MinFeatures 100\n";
            &run_or_die($cmd) ;
        }
        elsif ($num == 4){
            my $outdir = "$result_dir/04.WebReport" ;
            mkdir $outdir if (!-d $outdir) ;
            my $cmd = "perl $Bin/web_report/create_report.pl -i $outdir -c $cfgfile\n";
            &run_or_die($cmd) ;
        }
    }

    return ;
}

##########################################################
sub sub_format_datetime {#Time calculation subroutine
    my($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst) = @_;
        $wday = $yday = $isdst = 0;
    sprintf("%4d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $day, $hour, $min, $sec);
}

sub show_log()
{
        my ($txt) = @_ ;
        my $time = time();
        my $Time = &sub_format_datetime(localtime($time));
        print "$Time:\t$txt\n" ;
        return ($time) ;
}

sub run_or_die()
{
        my ($cmd) = @_ ;
        my $start_time = &show_log($cmd);
        my $flag = system($cmd) ;
        if ($flag != 0){
                my $end_time = &show_log("Error: command fail: $cmd");
                &show_log("Elaseped time: ".($end_time - $start_time)."s\n");
                exit(1);
        }
        my $end_time = &show_log("done.");
        &show_log("Elaseped time: ".($end_time - $start_time)."s\n");
        return ;
}
