use strict;
use warnings;

use lib "/home/Perl/";
use lib "/home/SuperDAILY/module";

use Cwd;
use Net::SMTP;
use MIME::Base64;
use MIME::Lite;
use Thread qw(:DEFAULT async yield);

use Term::ANSIColor;
use Term::ANSIColor qw(:constants);

use build;

$Term::ANSIColor::AUTORESET = 1;

my $cmd             = '';
my $line            = '';
my $isFail          = 0;
############################################################
# Global Var                                               #
############################################################
my $P4USER      = 'NINJA';
my $P4CLIENT    = 'ninja_NINJA_DAILY_dfb_ut';
my $P4PASSWD    = '6pTqFrJH';
my $P4PORT      = 'p4_svr_dz:1667';

my $P4GCMD      = "p4 -c $P4CLIENT -p $P4PORT -P $P4PASSWD -u $P4USER";

############################################################
# Main                                                     #
############################################################
print UNDERLINE "\nDFB Daily Check\n";

my $parasoft_compilerFamily = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.compiler.family.linux.x86=';
my $parasoft_compilerOption = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.compiler.options.linux.x86=';
my $parasoft_compilerCommand_C = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.compiler.command.c.linux.x86=';
my $parasoft_compilerCommand_CPP = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.compiler.command.cpp.linux.x86=';
my $parasoft_linkerOption = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.linker.options.linux.x86=';
my $parasoft_linkerCommand = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.linker.command.linux.x86=';
my $org_parasoft_compilerFamily = $parasoft_compilerFamily.'.*';
my $org_parasoft_linkOption = $parasoft_linkerOption.'.*';
my $org_parasoft_compilerOption = $parasoft_compilerOption.'.*';
my $org_parasoft_compilerCommand_C = $parasoft_compilerCommand_C.'.*';
my $org_parasoft_compilerCommand_CPP = $parasoft_compilerCommand_CPP.'.*';
my $org_parasoft_linkCommand = $parasoft_linkerCommand.'.*';

#my $parasoft_compilerOption = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.compiler.options.linux.x86=';
#my $parasoft_linkerOption = '\/UT_DFBProject\/\/com.parasoft.xtest.checkers.api.cpp.options.linker.options.linux.x86=';
#my $org_parasoft_linkOption = $parasoft_linkerOption.'.*';
#my $org_parasoft_compilerOption = $parasoft_compilerOption.'.*';
 my $root_workspace = "/home/SuperDAILY";


###############          °ѼƳ]©w          ######################


 my $projectLocation = "$root_workspace/daily_dfb_ut";
 my $project_workspace = "$root_workspace/daily_dfb_ut_workspace";

 my $project_name = "UT_DFBProject";
 my $bdf_location = "$projectLocation/THEALE/RedLion/Lunar/directfb/1.4.2/cpptestscan.bdf";
 my $localsetting_name = "$root_workspace/localsetting/daily_localsetting_dfb.properities";
 my $localsetting_name_no_mail = "$root_workspace/localsetting/daily_localsetting_dfb_no_mail.properities";
# my $projectSetting_name = "$root_workspace/localsetting/MM_UnitTest.parasoft";
# my $Daily_Check_Configuration = "team://MStar-MM-Daily-Static";
 my $Daily_UT_Build_Executable_Configuration = "team://MStar-DFB-Daily-Build-Executable";
 my $Daily_UT_Read_Log_Configuration = "team://MStar-DFB-Daily-Load-Results";
 my $report_location = "./report/MStar-DFB-Daily-Static.xml";
 my $unitTestCaseLocation = "$projectLocation/THEALE/RedLion/Lunar/directfb/1.4.2/unittest";
 my $new_parasoft_linkOption =  $parasoft_linkerOption.'\${cpptest\\\:original_options} -L${workspace_loc}\/..\/cpptest9.0_3\/engine\/lib -m32';
 my $new_parasoft_compilerOption = $parasoft_compilerOption.'\${cpptest\\\:original_options} -DPARASOFT_CPPTEST -m32';

 my $new_parasoft_compilerFamily = $parasoft_compilerFamily.'gcc_4_4';
 my $new_parasoft_compilerCommand_C = $parasoft_compilerCommand_C.'gcc';
 my $new_parasoft_compilerCommand_CPP = $parasoft_compilerCommand_CPP.'g++';
 my $new_parasoft_linkCommand =  $parasoft_linkerCommand.'g++';


 my @sync_path = ('//DAILEO/Supernova/...', '//THEALE/RedLion/Lunar/directfb/1.4.2/...', '//THEALE/RedLion/2.6.32.15/...');
 
 my $sync_flag = 1;
 my $build_flag = 1;
###############            End            ######################


my $clnoFile = "$projectLocation/daily_build_clno.txt";

#if ($ARGV[1] ne "UT_Result") {
if ($ARGV[1] ne "UT_Result" && $ARGV[1] ne "RunUT") {
    ####################
    # Change folder    #
    ####################
  if ($sync_flag)
  {
    system 'rm daily_dfb_ut -rf' if((-e 'daily_dfb'));
    system 'mkdir daily_dfb_ut';
  }
    chdir "daily_dfb_ut" or die $!;

    ############
    # P4 Login #
    ############
    print UNDERLINE "\nP4 Login\n";

    $cmd = "
        echo $P4PASSWD >tmp;
        $P4GCMD login -a <tmp;
        rm tmp;
    ";
    print $cmd."\n";
    system $cmd;

    #########################################################
    # P4 find head revision and force sync to head revision #
    #########################################################
    print UNDERLINE "\nP4 find head revision and force sync to head revision\n";
    $cmd = "
        $P4GCMD changes -m 1 $sync_path[0] >lastchangelist.txt;
    ";
    print $cmd."\n";
    system $cmd;

    open FH, "lastchangelist.txt" or die $!;
    $line = <FH>;
    my @parts = split(' ', $line);
    my $changelist_num = $parts[1];
    print "    changelist $changelist_num\n";
    system "echo $changelist_num > $clnoFile";
    close FH;

    $cmd = '';
    foreach my $tmp(@sync_path)
    {
    	#if ($tmp =~ /\/\/DAILEO\/Supernova\/.../) { $cmd = $cmd."cp -rf /home/SuperDAILY/daily_Supernova_codebase_ut/* $projectLocation/;" ; next;}
    	
        $cmd = $cmd."
        $P4GCMD sync $tmp#none >>/dev/null;
        $P4GCMD sync -f $tmp >>/dev/null;";
    }
    $cmd = $cmd."
        chmod 777 ./ -R";
    print $cmd."\n";
  if ($sync_flag)
  {
    system $cmd;
  }

    #######################
    # Compile and Gen BDF #
    #######################
    print UNDERLINE "\nCompile and Gen BDF\n";

    $cmd = "
        chmod 777 -R ./DAILEO;
        chmod 777 -R ./THEALE;

        cd ./DAILEO/Supernova/projects/;
        ./buildsettings/build_A5_129E_IPC.sh;
        sed -i 's/4.5.1/4.4.5/g' sw_cfg/tool_config.mk;
        source ./env.cfg;
        make rebuild_all;
        make image_all;

        cd ../../../THEALE/RedLion/Lunar/directfb/1.4.2/;

        sed -i 's/#THEALE\_PATH=.*/THEALE\_PATH=\"\\\/home\\\/SuperDAILY\\\/daily_dfb_ut\\\/THEALE\"/g' mstconfigure_x86_ut.sh;
        sed -i 's/#PHOTOSPHERE\_ROOT=.*/PHOTOSPHERE\_ROOT=\"\\\/home\\\/SuperDAILY\\\/daily_dfb_ut\\\/DAILEO\\\/Supernova\"/g' mstconfigure_x86_ut.sh;
        sed -i 's/KERNEL\_PATH=.*/KERNEL\_PATH=\"\$THEALE\_PATH\\\/RedLion\\\/2.6.32.15\\\/kernel\"/g' mstconfigure_x86_ut.sh;
        sed -i 's/CHIP=.*/CHIP=a5/g' mstconfigure_x86_ut.sh;
        ./mstconfigure_x86_ut.sh;

        sed -i 's/echo/ECHO/g' libtool;
        sed -i 's/\"ECHO\"/\"echo\"/g' libtool;
        sed -i 's/`ECHO/`echo/g' libtool;
				make all;
				
				cd gfxdrivers/mstar_g2/;
				rm *.bdf;
				make clean;
				make;
				
				cd ../../interfaces/IDirectFBImageProvider/;
				sed -i 's/-lapiGOP//' Makefile; 
				sed -i 's/-ldrvVE//' Makefile;
				rm *.bdf;
				make clean;
				make;
				
				cd ../IDirectFBVideoProvider/;
				sed -i 's/-lapiGOP//' Makefile; 
				sed -i 's/-ldrvVE//' Makefile; 
				rm *.bdf;
				make clean;
				make;
				
				cd ../../;
        ./genBdf.sh > /home/SuperDAILY/log/$0_build_log.txt;
    ";

	if ($build_flag)
	{
    print $cmd."\n";
    system $cmd;
  }


    ######################################################
    # Parasoft - Remove Old Project      #
    ######################################################
    print UNDERLINE "\nParasoft - Remove Project Workspace\n";


    $cmd = " rm -rf $project_workspace;     ";
    print $cmd."\n";
    system $cmd;


    $cmd = " mkdir -p $project_workspace/$project_name;     ";
    print $cmd."\n";
    system $cmd;

    if(!(-e $bdf_location))
    {
        $isFail = 1;
        print "==================================================================\n";
        print " No $bdf_location!!!\n";
        print "==================================================================\n";
        system "echo $isFail >./borg_error_condition.txt";
        exit 0;
    }

    ##########################
    # Create Project         #
    ##########################
    print UNDERLINE "\nParasoft - Coding Standard * Bug Detective\n";

    $cmd = "
    source ~/.bashrc;
    CLNO=$changelist_num;
        cpptestcli -J-Xms1024m -J-Xmx2048m -J-XX:MaxPermSize=512m -data \"$project_workspace\" -bdf \"$bdf_location\" -config \"util/CreateProjectOnly\" -localsettings $localsetting_name_no_mail >static.txt;
        cat static.txt;
    ";
    print $cmd."\n";
    system $cmd;

    local($/) = ""; # Read entire file at once
    open FH, "static.txt" or die $!;
    $line = '';
    while(<FH>){$line = $line.$_};
    close FH;
    local($/) = "\n";

    if($line =~ /No valid license/)
    {
        $isFail = 1;
        print "==================================================================\n";
        print " ERROR: Error: No valid license\n";
        print "==================================================================\n";
        system "echo $isFail >./borg_error_condition.txt";
        exit 0;
    }

    system "echo $isFail >./borg_error_condition.txt";



    ######################################################
    # Parasoft - Build Test Executable file [Utopia_TestExecuttion.exe]         #
    ######################################################
    print UNDERLINE "\nParasoft - Build Test Executable file [CI_Supernova_TestExecuttion.exe]\n";

#    $cmd = "
#
#        cp $projectSetting_name $project_workspace/$project_name/.parasoft;
#        cp -rf $unitTestCaseLocation/*  $project_workspace/$project_name/;
#
#
#        source ~/.bashrc;
#        CLNO=$changelist_num;
#        cpptestcli -data \"$project_workspace\" -resource \"$project_name\" -config $Daily_UT_Build_Executable_Configuration -report $report_location  -localsettings $localsetting_name_no_mail;
#    ";
        $cmd = "
        
        sed -i 's/$org_parasoft_compilerFamily/$new_parasoft_compilerFamily/g' $project_workspace/$project_name/.parasoft;
        sed -i 's/$org_parasoft_compilerCommand_C/$new_parasoft_compilerCommand_C/g' $project_workspace/$project_name/.parasoft;
        sed -i 's/$org_parasoft_compilerCommand_CPP/$new_parasoft_compilerCommand_CPP/g' $project_workspace/$project_name/.parasoft;
        sed -i 's/$org_parasoft_linkCommand/$new_parasoft_linkCommand/g' $project_workspace/$project_name/.parasoft;
      

        sed -i 's/$org_parasoft_compilerOption/$new_parasoft_compilerOption/g' $project_workspace/$project_name/.parasoft;
        sed -i 's/$org_parasoft_linkOption/$new_parasoft_linkOption/g' $project_workspace/$project_name/.parasoft;

        cp -rf $unitTestCaseLocation/*  $project_workspace/$project_name/;

        source ~/.bashrc;
        CLNO=$changelist_num;
        cpptestcli -data \"$project_workspace\" -resource \"$project_name\" -config $Daily_UT_Build_Executable_Configuration -report $report_location  -localsettings $localsetting_name_no_mail -appconsole stdout > /home/SuperDAILY/log/$0_build_parasoft_exe.txt;
    ";

    print $cmd."\n";
    system $cmd;
    
} elsif ($ARGV[1] eq "RunUT") {
    ######################################################
    # Parasoft - Execute Unit Test Log                   #
    ######################################################
    print UNDERLINE "\nParasoft - Execute RunUT step \n";

    #$cmd = "export LD_LIBRARY_PATH=LD_LIBRARY_PATH:/THEALE/3d_drv/Mali/driver/latest/linux/build/gcc-internal-indirect-debug-unittest-mali400-r1p1-rgb_is_xrgb-linux-directfb-ump/lib/libMali.so";

    $cmd = "export LD_LIBRARY_PATH=LD_LIBRARY_PATH:/home/SuperDAILY/cpptest9.0_3/engine/lib;
            cd $project_workspace/$project_name/;
            ./UT_DFBProjectTest.exe;";
    print $cmd."\n";
    system $cmd;

} else {

 ######################################################
    # Parasoft - Read Unit Test Log        #
    ######################################################
    print UNDERLINE "\nParasoft - Read Unit Test Log\n";
    my $FHin;
    my $daily_build_clno;
    open(FHin, "$clnoFile") or die "can't open xxxx file\n";
    $daily_build_clno = <FHin>;
    $daily_build_clno =~ s/\n//g;

#    $cmd = "
#        source ~/.bashrc;
#        CLNO=$daily_build_clno;
#        cpptestcli -data \"$project_workspace\" -resource \"$project_name\" -config $Daily_UT_Read_Log_Configuration -report $report_location -publish -localsettings $localsetting_name;
#    ";

    $cmd = "
        source ~/.bashrc;
        CLNO=$daily_build_clno;
        cpptestcli -data \"$project_workspace\"  -config $Daily_UT_Read_Log_Configuration -report $report_location -publish -localsettings $localsetting_name -appconsole stdout  > /home/SuperDAILY/log/$0_load_result.txt;
    ";
    print $cmd."\n";
    system $cmd;

}
