#..
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
#
# Module name   : JAVA
# Module type   : Makefile system
# Compiler(s)   : None
# Environment(s): All
#
# Description:
#       This file provides Toolset initialisation and plugin functions
#       to makelib.pl2
#
# Contents:     Basic (very basic) Java support
#
#............................................................................#

#   Local varables
#
my  $postProcessUnitTest = 0;

##############################################################################
#   ToolsetInit()
#       Runtime initialisation
#
##############################################################################

ToolsetInit();

sub ToolsetInit
{
    my( @args ) = @ScmToolsetArgs;             # Toolset arguments
    my( $version, $product, @defines, @dirs, @flags );

    #
    #   If the user doesn't specify a version, then force a known version
    #   1.4 may not be the current flavor, but it was when this was done!
    #
    $version = 1.4;

#.. Parse arguments
#
    Debug( "JAVA(@args)\n" );

    foreach $_ ( @args ) {
        if (/^--Version=(.*)/) {                # Compiler version
            $version = "$1";
        } else {
            Message( "JAVA: unknown toolset argument $_ -- ignored\n" );
        }
    }

#.. Parse Platform Arguments
#
    @args = @ScmPlatformArgs;                   # Platform arguments
    foreach $_ ( @args ) {
        if (/^--product=(.*)/) {                # GBE product
            $product = $1;

        } elsif (/^--Version=(.*)/) {
            $version = $1;
            
        } else {
            Message( "JAVA: unknown platform argument $_ -- ignored\n" );
        }
    }

#.. Toolset configuration
#
    $::ScmToolsetVersion = "1.0.0";                 # our version
    $::ScmToolsetGenerate = 0;                      # generate optional
    $::ScmToolsetProperties{'AutoUnitTests'} = 1;   # Supports AutoUnit Tests in MakeProject
    $::ScmToolsetProperties{'UnitTests'} = 1;       # Supports Manual Unit Tests in MakeProject

#.. Standard.rul requirements
#
    $s =   'java';          # Assembler source file
    $o =   '';              # Object file
    $a =   'class';         # Library file
    $so =  '';              # Shared library
    $exe = '.jar';          # Linked binary images

#.. Pass version information in
#
    Error ("Java Version has not been set") unless $version;
    my $nice_ver = $version;
    $nice_ver =~ s~\.~_~g;

    ToolsetDefine ( "\n#..    Specify the version of JAVA to use and the EnvVar that specifies it" );
    ToolsetDefine ( "#" );
    ToolsetDefine ( "JAVA_VER = $version" );
    ToolsetDefine ( "JAVA_HOME_VAR = JAVA_HOME_$nice_ver" );
    ToolsetDefine ( "" );

#
#   Examine the dependent packages looking for a package that provides
#   'ant' toolset information. If found the provided ANT will be used
#   in place of the default ant
#  
    if (testToolInfo('ant'))
    {
        my $antTool = getToolInfo('ant', 'JAVA_VERSION');
        my $antHome = catdir($antTool->{PKGBASE}, $antTool->{TOOLROOT});
        my $antVersion = $antTool->{PKGENTRY}->getVersion();

        # 
        # Validate the required version of Java for the tool
        #   Assume JAVA_VERSION is of the form JAVA_HOME_1_6 and
        #   that we can do a crude string comparison
        # 
        my $javaVersion = $antTool->{JAVA_VERSION};
        if (("JAVA_HOME_$nice_ver" cmp $javaVersion) < 0 )
        {
            Error ("The version of Java required by the ant package is not suitable",
                   "The ant plugin requires: $javaVersion",
                   "This package is building for: JAVA_HOME_$nice_ver"
                   );
        }
        $ENV{JAVA_HOME}=$ENV{$javaVersion};

        ToolsetDefine ( '#..    Specify the ANT_HOME provided by the package' );
        ToolsetDefine ( '#' );
        ToolsetDefine ( "ANT_HOME = $antHome" );
        ToolsetDefine ( "ANT_TITLE=, Ant $antVersion" );
        ToolsetDefine ( '' );
    }

#.. Toolset specific definitions
#
    Init( "java_sdk" );
    ToolsetDefines( 'JAVA.DEF' );
    
}

########################################################################
#
#   Generate a project from the provided build.xml
#   This is aimed at Java
#
#   Arguments   : $name             - Base name of the project
#                 $buildxml         - Path to the build.xml file
#                 $pArgs            - Project specific options
#                 $auto_test        - Unit Test Target (optional)
#                 $unit_test        - Unit Test Target (optional)
#                 $pGenerated       - Ref to an array of Generated Files (optional)
#
########################################################################

our $ToolsetPROJECT_type = 'ant';
sub ToolsetPROJECT
{
    my( $name, $buildxml ,$pArgs, $auto_test, $unit_test, $pGenerated ) = @_;
    my $cmd = '$(ANT) $(ANT_VERBOSE)';
    my $io = ToolsetPrinter::New();

    #
    #   Generate the recipe to create the project
    #   Add names of co-generated targets.
    #
    $io->Label( "Build project", $name );
    $io->Entry( "Project_$name",": $buildxml\n", " \\\n", "" , @{$pGenerated} );
    $io->PrtLn( "\t\$(XX_PRE)grep \'includeAntRuntime[ \t]*=[ \t]*\"off\"\' $buildxml || (echo ANT 'build file MUST specify includeAntRuntime=\"off\" with each javac command'; exit 1)" );
    $io->PrtLn( "\t\$(XX_PRE)\$(call ProjectDefine_$name,)" );
    $io->Newline();

    #
    #   Generate the recipe to clean the project
    #
    $io->Label( "Clean project", $name );
    $io->PrtLn( "ProjectClean_$name: $buildxml" );
    $io->PrtLn( "\t\$(XX_PRE)\$(call ProjectDefine_$name,clean)" );
    $io->Newline();

    #
    #   Generate the recipe to run unit tests on the project
    #   This is optional
    #
    if ( $auto_test )
    {
        #   Flag that we need to post process the test results
        #   Under Java the UTF tests MUST be Post processed
        $postProcessUnitTest = 1;

        $io->Label( "Auto Test project", $name );
        $io->PrtLn( "ProjectATest_$name: $buildxml" );
        $io->PrtLn( "\t\$(XX_PRE)\$(call ProjectDefine_$name,$auto_test)" );
        $io->Newline();
    }

    if ( $unit_test )
    {
        $io->Label( "Unit Test project", $name );
        $io->PrtLn( "ProjectUTest_$name: $buildxml" );
        $io->PrtLn( "\t\$(XX_PRE)\$(call ProjectDefine_$name,$unit_test)" );
        $io->Newline();
    }

    #
    #   Generate macro to contain the project invocation
    #   The first argument will be a 'build target' argument
    #
    $io->Label( "Macro to invoke project", $name );
    $io->PrtLn( "define ProjectDefine_$name" );
    $io->PrtLn( "\t$cmd -f $buildxml -DINTERFACEDIR=\$(abspath \$(INTERFACEDIR)) -DGBE_TYPE=\$(GBE_TYPE) @{$pArgs} \$1" );
    $io->PrtLn( "endef");
    $io->Newline();
}

#-------------------------------------------------------------------------------
# Function        : ToolsetPostprocess 
#
# Description     : Last chance by the toolset to perform processing
#                   All Directives have been processed
#
#                   If the Java Project has indicated that it has an automated unit test
#                   then we need to post process the results
#
# Inputs          : None
#
# Returns         : 
#

sub ToolsetPostprocess
{
    if ($postProcessUnitTest)
    {
        MakeHeader ("Automated tests Post Processing");

        #   Extend the list of Post Unit Tests recipes that are run
        my $recipeName = 'post_utf_processing';
        ToolsetAddUnitTestPostProcess($recipeName);

        #
        #   Create the Post Unit Test Recipe
        #
        my $me = MakeEntry::New (*MAKEFILE, $recipeName, '--Phony' );

        #   Insert test EnvVars
        #       In the Java toolset these are not as useful in a Jats RunTest
        $me->AddDefn('export GBE_UTFNAME', 'junit4Test');
        $me->AddDefn('export GBE_UTFUID', '$(MAKEFILEUID)' . '_' . '1');
        $me->AddDefn('export GBE_UTFFILE','$(UTFDIR_PKG)/$(GBE_PLATFORM)-$(GBE_TYPE)-$(GBE_UTFUID)' . '.xml');
        $me->AddDefn('export GBE_UTFTEST','TEST-$(GBE_UTFNAME)-$(GBE_TYPE)-$(GBE_UTFUID)' );

        $me->SectionIfDef ('UTF_POSTPROCESS');
        $me->AddRecipe  ( [
                           '$(GBE_PERL) -Mjats_runutf -e processUtf -- ',
                           '$(VERBOSE_OPT)',
                           '-filter=junit',
                           '-arg=pattern=TEST-*.xml',
                           '-root=$(GBE_ROOT_ABS)',
                           '-target=$(GBE_PLATFORM)', 
                           '-pkgdir=$(PKGDIR)',
                           '-local=$(LOCALDIR)',
                           '-interface=$(INTERFACEDIR)' 
                          ]);
        $me->Print();

        #   Clean up files that look like Junit output files
        ToolsetGenerate( 'TEST-*.xml' );
    }
}

1;

