#! perl
########################################################################
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
#
# Module name   : MakePackage.pl
# Module type   : Makefile system
# Compiler(s)   : n/a
# Environment(s): jats
#
# Description   : This script is invoked by the builder to:
#                   1) Perform sanity tests
#                   2) Package up jats
#                 This script is really used to 'release' JATS.
#
#                 This script must be executed within a JATS environment
#                 JATS required JATS to build itself.
#
# Usage:
#
#......................................................................#

use strict;
use warnings;
use Cwd;
use Getopt::Long;
use Pod::Usage;

use JatsError;
use JatsSystem;
use FileUtils;
use JatsCopy;

#
#   Set the perl library search path so that this script will use the tools
#   being released by this vesrion of JATS and not the one under which it
#   is being built.
#
use FindBin;                                    # Determine the current directory
use lib "$FindBin::Bin/../TOOLS/LIB";           # Build under this version

my $VERSION = "1.0.0";
my $opt_help = 0;
my $opt_manual = 0;
my $opt_buildname;
my $opt_buildversion;
my $opt_package;
my $opt_root;
my $opt_interface;
my $opt_verbose = $ENV{'GBE_VERBOSE'};
my $opt_vargs;

#
#   Parse the user options
#
my $result = GetOptions (
                "help+"             => \$opt_help,
                "manual"            => \$opt_manual,

                "BuildName=s"       => \$opt_buildname,
                "BuildVersion=s"    => \$opt_buildversion,
                "PackageDir=s"      => \$opt_package,
                "BuildRoot=s"       => \$opt_root,
                "InterfaceDir=s"    => \$opt_interface,
                "Verbose:s"         => \$opt_vargs,

                );

#
#   Process help and manual options
#
pod2usage(-verbose => 0, -message => "Version: $VERSION")  if ($opt_help == 1  || ! $result);
pod2usage(-verbose => 1)  if ($opt_help == 2 );
pod2usage(-verbose => 2)  if ($opt_manual || $opt_help > 2);

#
#   Init the error and message subsystem
#
$opt_verbose += 2 unless ( $opt_vargs eq '@' );
ErrorConfig( 'name'    => 'RELEASE_JATS',
             'verbose' => $opt_verbose );

SystemConfig ('ExitOnError' => 1 );
InitFileUtils();

#
#   Sanity Test arguments
#
Error ("Not expecting any command line arguments" )
    if ( $#ARGV >= 0);

#
#   Diagnostics
#
Verbose ( "BuildName: ", $opt_buildname );
Verbose ( "BuildVersion: ", $opt_buildversion );
Verbose ( "PackageDir: ", $opt_package );
Verbose ( "BuildRoot: ", $opt_root );
Verbose ( "Interface: ", $opt_interface );


#
#   Ensure we have all required parameters
#
Error ("No build name provided" ) unless ( $opt_buildname );
Error ("No build version provided" ) unless ( $opt_buildversion );
Error ("No package directory provided" ) unless ( $opt_package );
Error ("No build root provided" ) unless ( $opt_root );
Error ("Build root is not a directory " ) unless ( -d $opt_root );
Error ("No interface directory provided" ) unless ( $opt_interface );
Error ("Interface directory is not a directory" ) unless ( -d $opt_interface );

#
#   Import Environment Variables
#
my $GBE_PERL = $ENV{GBE_PERL} || Error ("Environment variable GBE_PERL not set");
my $GBE_CORE = $ENV{GBE_CORE} || Error ("Environment variable GBE_CORE not set");

#
#   Setup logging options for the copy functions
#
SetCopyDirDefaults ('Log' => 0 );

#
#   Remove any existing package directory
#

Message "Create package image: $opt_package";
CreateDir ($opt_package, 'DeleteFirst' => 1 );


Message "Copy in: BIN dirs";
CopyDir ( $opt_root, $opt_package, 'MatchDirs' => ['BIN.*'], 'SkipTLF' => 1 );

for my $dir (qw(CFG TEMPLATES TOOLS HTML))
{
    Message "Copy in: $dir";
    CopyDir ( "$opt_root/$dir", $opt_package,
                'IgnoreDirs' => ['LOCAL', 'JatsDocTools'],
                'KeepSrcTail' => 1);
}

for my $file (qw(Readme.txt ChangeLog.txt))
{
    Message "Copy in: $file";
    CopyFile ( "$opt_root/$file", $opt_package );
}

for my $file (qw(PostInstall.sh))
{
    Message "Copy in: $file";
    CopyFile ( $file, $opt_package );
}

#
#   Update version info in some files
#
foreach my $file (qw( TOOLS/jats.sh TOOLS/jats.bat TOOLS/jats.pl ))
{
    Message "Insert version into: $file";
    my @opts;
    push @opts, ( $file =~ m~\.bat$~ ? '-dos' : '-unix' );
    unlink "$opt_package/$file";
    JatsTool ("jats_transform_file.pl",
                 "-infile=$opt_root/$file",
                 "-outfile=$opt_package/$file",
                 "-tag=VERSION_TAG,$opt_buildversion",
                 "-tag=PACKAGE_TAG,$opt_buildname",
                 "-tag=RELEASE_TAG,",
                 @opts
                );
}

#
#   Ensure that the jats.pl file has the correct version information
#   inserted into it, by this tool
#
Message ("Validate version embedded into jats.pl" );
my $file = "$opt_package/TOOLS/jats.pl";
my $jversion;
open ( FH, '<', $file ) || Error ("Cannot open: $file", "Reason: $!");
while ( <FH> )
{
    next unless ( m~\s*my\s+\$GBE_VERSION\s+=\s+['"](.*)['"]~ );
    $jversion = $1;
    last;

}
close FH;


#
#   Generate the HTML documenation from the POD
#   Generate the HTML TOc
#
Message ("Generate HTML documentation" );
use JatsDocTools::JatsDocTools;
JatsDocTools::UpdateHTML( 'force' => 0,
                          'verbose' => $opt_verbose,
                          'htmldir' => FullPath("$opt_package/HTML"),
                          'prefix' => FullPath($opt_package),
                          'cacheDir' => FullPath($opt_interface),
                          'ChangeLog' => FullPath("$opt_root/ChangeLog.txt"),
                          'index' => 1,
                          );

Error ("Cannot locate GBE_VERSION in jats.pl" ) unless ( $jversion );
Error ("GBE_VERSION definition in jats.pl Does not match released version.",
        "Expecting: $opt_buildversion",
        "Got      : $jversion") unless( $jversion eq $opt_buildversion );



exit 0;

#-------------------------------------------------------------------------------
#   Documentation
#

=pod

=head1 NAME

MakePackage - Release Jats

=head1 SYNOPSIS

 MakePackage [options]

 Options:
    -help               - Brief help message
    -help -help         - Detailed help message
    -man                - Full documentation
    -BuildName=text     - Name of the package being built
    -BuildVersion=text  - Version of the package being built
    -PackageDir=path    - Path to the packaging target directory
    -BuildRoot=path     - Path to the root of the build
    -Verbose=text       - Verbosity control
    

=head1 OPTIONS

=over 8

=item B<-help>

Print a brief help message and exits.

=item B<-help -help>

Print a detailed help message with an explanation for each option.

=item B<-man>

Prints the manual page and exits.

=head1 DESCRIPTION

No user servicable parts in this script.

=cut


