#!/usr/bin/perl -w

# $Id: export-nitro,v 1.19 2006/11/28 01:11:47 craig Exp $

#               Copyright (C) 2006, BroadOn Communications Corp.
#
#  These coded instructions, statements, and computer programs contain
#  unpublished  proprietary information of BroadOn Communications Corp.,
#  and  are protected by Federal copyright law. They may not be disclosed
#  to  third  parties or copied or duplicated in any form, in whole or in
#  part, without the prior written consent of BroadOn Communications Corp.


# Script to modify a Nitro SDK tree to compile GBA libraries

# To use this script, either GBA_SRC_ROOT environment variable
# needs to be set to the root of a gba source tree, or the script
# needs to be invoked from within a gba source tree.



use strict;
use Getopt::Long;
use Cwd;
use File::Basename;
use File::Path;
use POSIX qw(tmpnam);

my $homeDir = "tools/ds-sdk";

my $makefileTemplate = "$homeDir/Makefile.template";

# srcFiles - is an single array of source locations within the
#            gba source tree.
# incFiles - is an array of lists of the same form as @globalIncludes

# These files are installed into $NitroSDK/build/libraries/$libName, along
# with a Makefile generated from a template.

my @exportLibList = (
     {
        libName         => "csl",
        srcFiles        => ["common/lib/libcsl/aes_api.c",
                            "common/lib/libcsl/aes_imp.c", 
			    "common/lib/libcsl/integer_math.c",
                            "common/lib/libcsl/poly_math.c",
			    "common/lib/libcsl/elliptic_math.c",
			    "common/lib/libcsl/algorithms.c",
			    "common/lib/libcsl/convecc.c",
			    "common/lib/libcsl/convrsa.c",
			    "common/lib/libcsl/cslsha.c",
			    "common/lib/libcsl/cslecc.c",
			    "common/lib/libcsl/cslrsa.c",
			    "common/lib/libcsl/cslhmac.c",
			    "common/lib/libcsl/cslaes.c"],
        incFiles        => [
			    ["common/lib/libcsl/aes_api.h", ""], 
			    ["common/lib/libcsl/aes_imp.h", ""],
			    ["common/lib/libcsl/algorithms.h", ""],
			    ["common/lib/libcsl/conversions.h", ""],
			    ["common/lib/libcsl/elliptic_math.h", ""],
			    ["common/lib/libcsl/integer_math.h", ""],
			    ["common/lib/libcsl/poly_math.h", ""],
			   ],  
        internal        => 0,
    },		  
    {
        libName         => "isfs",
        srcFiles        => ["common/lib/fs/fs.c",
                            "common/lib/ioslibc/string/strnlen.c"],
        incFiles        => [
                           ],  
        internal        => 0,
    },
    {
        libName         => "es",
        srcFiles        => ["common/lib/es/es.c",
                            ],
        incFiles        => [
                           ],  
        internal        => 0,
    },
    {
        libName         => "ios",
        srcFiles        => ["ds/lib/ios/ios.c",
                            ],
        incFiles        => [
                           ],  
        internal        => 0,
    },
    {
        libName         => "card-nc",
        srcFiles        => [
                                "ds/lib/card-nc/card-api.c",
                                "ds/lib/card-nc/card-backup-api.c",
                            ],
        incFiles        => [
                             ["ds/lib/card-nc/card-api.h",     ""],
                             ["ds/lib/card-nc/card-lock.h",     ""],
                             ["ds/lib/card-nc/card-nc.h",       ""],
                           ],  
        internal        => 0,
    },
    {
        libName         => "screen-text",
        srcFiles        => [
                                "ds/lib/screen-text/screen-text.c",
                                "ds/lib/screen-text/font.c",
                            ],
        incFiles        => [
                             ["ds/lib/screen-text/text-internal.h",    ""],
                           ],  
        internal        => 1,
    },
    {
        libName         => "vio",
        srcFiles        => [
                              "ds/lib/vio/vio_usb.c",
                              "common/lib/ioslibc/stdio/printf.c",
                              "common/lib/ioslibc/stdio/snprintf.c",
                            ],
        incFiles        => [
                              ["common/lib/ioslibc/stdio/printf.h", ""],
                           ],  
        internal        => 0,
    },
);  #exportLibList

my @exportTestList = (
     {
        testName        => "text",
        Makefile        => "ds/test/text/Makefile",
        srcFiles        => [
                             "ds/test/text/text-driver.c",
			   ],
        incFiles        => [
			   ],  
    },		  
); #exportTestList

# Array is: location within the gba src tree
#           sub-directory where the file should be copied
#           (Note: empty string means top of destination tree)
my @globalIncludes = (
                             ["common/include/estypes.h",           ""],
                             ["common/include/fs.h",                ""],
                             ["common/include/types.h",             ""],
                             ["common/include/iosctypes.h",         ""],
                             ["common/include/types.h",             ""],
                             ["common/include/iosccert.h",          ""],
                             ["common/lib/libcsl/csltypes.h",       ""],
                             ["common/lib/libcsl/sha1.h",           ""],
                             ["common/lib/es/es.h",                 ""],
                             ["common/include/es_int.h",            ""],
		             ["common/lib/libcsl/cslsha.h",         ""],
		             ["common/lib/libcsl/csl.h",            ""],
                             ["sc/include/addr_map.h",              "sc"],
                             ["sc/include/sc.h",                    "sc"],
                             ["ds/include/iostypes.h",              "ds"],
                             ["ds/lib/ios/ios.h",                   "ds"],
                             ["ds/lib/tp/tp_ipc.h",                 "ds"],
                             ["ds/lib/vio/vio.h",                   "ds"],
                             ["ds/lib/vio/ioslibc.h",               "ds"],
);

my $NITRO_ROOT_NAME = "NITROSDK_ROOT";
my $Verbose = 0;
my $NitroGlobalIncludeDir = "include/netcard";
my ($NitroRootDos, $NitroRootDosForward, $NitroRoot);

# ********************************************************************
sub
usage()
{
    print "Usage: $0\n";
    print " Options:\n";
    print "           -h          - Print help message\n";
    print "           -i          - Export internally used components\n";
    print "           -v          - Print output as script runs\n";
    print "Note: the environment variable $NITRO_ROOT_NAME must be set\n";
    print "      to something like 'C:/NitroSDK'\n";
}

# ********************************************************************

# Add a library to a Makefile.  The library is added to
# the variable NITRO_LIBS

sub
addLibraryToMakefile($$)
{
    my ($makefile, $libraryName) = @_;
    my ($line);
    my $libLineFound = 0;
    my $returnVal = 0;
    my $tempMakefile;

    $tempMakefile = tmpnam();

    unless (open MAKE_IN, "$makefile") {
        print STDERR "$0: Can't open file $makefileTemplate: $!\n";
        goto end;
    }
    unless (open MAKE_OUT, ">$tempMakefile") {
        print STDERR "$0: Can't open file $tempMakefile for writing: $!\n";
        goto end;
    }
    while (defined($line = <MAKE_IN>)) {
        if ($line =~ m/^(\s*NITRO_LIBS\s*\?=\s*)([^\s]+)/o) {
            print MAKE_OUT "$line";
            $line = <MAKE_IN>;
            if (! defined($line)) {
                print STDERR "$0: Only one library defined for NITRO_LIBS\n";
                goto end;
            }
            print MAKE_OUT "$line";
            # Grab the indent from the line
            $line =~ m/^(\s*)[^\s+]+/o;
            print MAKE_OUT
                  "$1" . "lib$libraryName" . "\$(NITRO_LIBSUFFIX).a \\ \n";
            $libLineFound = 1;
        }
        else {
            print MAKE_OUT "$line";
        }
    }
    close(MAKE_IN);
    close(MAKE_OUT);
    if ($libLineFound == 0) {
        print STDERR "$0: Can't find line of the form 'NITRO_LIBS =' in $makefile\n";
        goto end;
    }
    else {
        unless(rename($tempMakefile, $makefile)) {
            print STDERR "$0: Can't rename $tempMakefile to $makefile ($!)\n";
            goto end;
        }
    }
    $returnVal = 1;
end:
    if (-e $tempMakefile) {
        unlink($tempMakefile);
    }
    return($returnVal);
} # addLibraryToMakefile


# ********************************************************************

# Convert paths of the form "C:\\XXX" to "/cygdrive/c/XXX"
# If the path is already of the form "/cygdrive/c/XXX", just return it.
# Note; Assumes any non-unix path start with only 'C:' or 'c';

sub
convertToUnixPath($)
{
    my ($path) = @_;
    my ($firstPart, $remainder);

    $firstPart = lc(substr($path, 0, 2));
    if ($firstPart eq "c:") {
        my $done = 0;
        my $firstChar;

        $remainder = substr($path, 2);
        do {
            $firstChar = substr($remainder, 0, 1);
            if ($firstChar eq "\\" || $firstChar eq "/") {
                $remainder = substr($remainder, 1);
            }
            else {
                $done = 1;
            }
        } while (! $done);
        return("/cygdrive/c/$remainder");
    }
    else {
        return($path);
    }
}

# ********************************************************************

# Attempt to make the directory whose path is passed in.
# It is OK if it already exists.
# Print an error message and return 0 if it cannot be done.
# Return 1 if it went OK.
#
# Note that mkpath() fails if the directory already exists.

sub
errorCheckedMkdir($)
{
    my ($path) = @_;

    if (-d $path) {
        return(1);
    }
    elsif (-f $path) {
        print STDERR
        "$0: Error - Attempting to make directory $path, but it already is a regular file\n";
    }
    elsif (mkpath($path)) {
        return(1);
    }
    else {
        print STDERR "$0: Error - can't make directory $path ($!)\n";
        return(0);
    }
}

# ********************************************************************

# Copy files located in tree rooted at $fromRoot to tree
# rooted at $toRoot.
# The first parameter is an array of lists.  Each list is
# a (fromPath, toPath) pair.  The 'fromPath' is the path to the file
# starting from root 'fromRoot'.  Similarly, 'toPath' is the directory
# rooted at '$toRoot' where the file will be copied.

sub
copyFilesToTree($$$)
{
    my ($fromToArrayRef, $fromRoot, $toRoot) = @_;
    my ($listRef);
    my $returnVal = 0;

    foreach $listRef (@$fromToArrayRef) {
        my ($fromSubPath, $fromPath, $toPath, $toSubPath, $command);
        my ($fileName);

        ($fromSubPath, $toSubPath) = @$listRef;

        $fromPath = "$fromRoot/$fromSubPath";

        if (length($toSubPath) > 0) {
            $toPath   = "$toRoot/$toSubPath";
            if (errorCheckedMkdir($toPath) == 0) {
                goto end;
            }
        }
        else {
            $toPath = $toRoot;
        }
        if (! -f $fromPath) {
            print STDERR
            "$0 (copyFilesToTree): Error - Can't find file $fromPath\n";
            goto end;
        }
        $command = "cp $fromPath $toPath";
        if (system($command) != 0) {
            print STDERR "$0 (copyFilesToTree): Command $command failed\n";
            goto end;
        }
        # Must make the destination file writable, otherwise subsequent
        # copies will fail
        $fileName = fileparse($fromPath);
        $command = "chmod u+rw $toPath/$fileName";
        if (system($command) != 0) {
            print STDERR "$0: Command $command failed\n";
            goto end;
        }
    }
    $returnVal = 1;
end:
    return($returnVal);
}
# ********************************************************************

# Export one or more libraries to the Nitro SDK tree rooted
# at $NitroRoot.  The library names and files are passed as
# an array of hashes in @exportList.
#
# Returns: 0 if all went well
#          1 otherwise
sub
exportLibraries($$@)
{
    my ($gbaSrcRoot, $internal, @exportList) = @_;
    my ($libRef, $nitroLibDir, $libDir);
    my $returnVal = 0;
    my @libSubDirs;

    $nitroLibDir = $NitroRoot . "/build/libraries";

    @libSubDirs = ("depend", "include", "lib", "obj", "src");

    foreach $libRef (@exportList) {
        my (%lib, $subDirName, $subDirPath);
        my ($line);

        %lib = %$libRef;

        if ($internal == 0 && $lib{'internal'} != 0) {
            if ($Verbose) {
                print "$0: Skipping internal library '$lib{'libName'}'\n";
            }
            next;
        }

        if ($Verbose) {
            print "$0: Exporting library '$lib{'libName'}'\n";
        }
        unless (chdir($nitroLibDir)) {
            print STDERR "$0: Can't change to directory $nitroLibDir ($!)\n";
            goto end;
        }
        $libDir = $nitroLibDir . "/" . $lib{'libName'};

        unless (errorCheckedMkdir($libDir)) {
            goto end;
        }

        foreach $subDirName (@libSubDirs) {
            $subDirPath = $libDir . "/" . $subDirName;

            if (! -e $subDirPath) {
                unless (mkdir($subDirPath)) {
                    print STDERR "$0: Can't make directory $subDirPath ($!)\n";
                    goto end;
                }
            }
            if (! -d $subDirPath) {
                print STDERR "$0: Error $subDirPath exists, but is not a directory\n";
                goto end;
            }
        }
        # Copy over the library source files
        my ($libFromSubPath, $libFromSubPaths);
        $libFromSubPaths = $lib{'srcFiles'};

        foreach $libFromSubPath (@$libFromSubPaths) {
            my ($libFromPath, $fileName, $command);

            $libFromPath = "$gbaSrcRoot/$libFromSubPath";
            if (! -f $libFromPath) {
                print STDERR "$0: Error - Can't find file $libFromPath\n";
                goto end;
            }
            $command = "cp $libFromPath $libDir/src";
            if (system($command) != 0) {
                print STDERR "$0: Command $command failed\n";
                goto end;
            }
            # Must make the destination file writable, otherwise subsequent
            # copies will fail
            ($fileName) = fileparse($libFromPath);
            $command = "chmod u+rw $libDir/src/$fileName";
            if (system($command) != 0) {
                print STDERR "$0: Command $command failed\n";
                goto end;
            }
        }

        # Copy over the include files
        my ($libIncRef, $libIncFiles);
        $libIncFiles = $lib{'incFiles'};

        unless (copyFilesToTree($libIncFiles, $gbaSrcRoot, "$libDir/include")) {
            goto end;
        }

        # Copy over and modify the Makefile
        unless (copyModifyMakefile("$gbaSrcRoot/$makefileTemplate",
                                   "$libDir/Makefile", $libFromSubPaths,
                                   "$lib{'libName'}", $NitroRoot)) {
            goto end;
        }

    } # foreach library
    $returnVal = 1;

end:
    return($returnVal);
} # exportLibraries
    
# *********************************************************************

# Export one or more tests to the Nitro SDK tree rooted
# at $NitroRoot.  The test names and files are passed as
# an array of hashes in @exportList.
#
# Returns: 0 if all went well
#          1 otherwise
# TODO (maybe) - integrate with exportLibraries
sub
exportTests($@)
{
    my ($gbaSrcRoot, @exportList) = @_;
    my ($testRef, $nitroTestDir, $testDir);
    my $returnVal = 0;
    my @testSubDirs;
    my $nitroMakefile = "$NitroRoot/build/buildtools/commondefs";

    $nitroTestDir = $NitroRoot . "/build/demos";

    @testSubDirs = ("depend", "include", "bin", "obj", "src");

    foreach $testRef (@exportList) {
        my (%test, $subDirName, $subDirPath, $command);
        my ($line);

        %test = %$testRef;

        if ($Verbose) {
            print "$0: Exporting test '$test{'testName'}'\n";
        }
        unless (chdir($nitroTestDir)) {
            print STDERR "$0: Can't change to directory $nitroTestDir ($!)\n";
            goto end;
        }
        $testDir = $nitroTestDir . "/" . $test{'testName'};

        unless (errorCheckedMkdir($testDir)) {
            goto end;
        }

        foreach $subDirName (@testSubDirs) {
            $subDirPath = $testDir . "/" . $subDirName;

            if (! -e $subDirPath) {
                unless (mkdir($subDirPath)) {
                    print STDERR "$0: Can't make directory $subDirPath ($!)\n";
                    goto end;
                }
            }
            if (! -d $subDirPath) {
                print STDERR "$0: Error $subDirPath exists, but is not a directory\n";
                goto end;
            }
        }
        # Copy over the test source files
        my ($testFromSubPath, $testFromSubPaths);
        $testFromSubPaths = $test{'srcFiles'};

        foreach $testFromSubPath (@$testFromSubPaths) {
            my ($testFromPath, $fileName);

            $testFromPath = "$gbaSrcRoot/$testFromSubPath";
            if (! -f $testFromPath) {
                print STDERR "$0: Error - Can't find file $testFromPath\n";
                goto end;
            }
            $command = "cp $testFromPath $testDir/src";
            if (system($command) != 0) {
                print STDERR "$0: Command $command failed\n";
                goto end;
            }
            # Must make the destination file writable, otherwise subsequent
            # copies will fail
            ($fileName) = fileparse($testFromPath);
            $command = "chmod u+rw $testDir/src/$fileName";
            if (system($command) != 0) {
                print STDERR "$0: Command $command failed\n";
                goto end;
            }
        }

        # Copy over the include files
        my ($testIncRef, $testIncFiles);
        $testIncFiles = $test{'incFiles'};

        unless (copyFilesToTree($testIncFiles, $gbaSrcRoot, "$testDir/include")) {
            goto end;
        }

        # Copy over the Makefile
        my ($makefileFromPath);

        $makefileFromPath = "$gbaSrcRoot/$test{'Makefile'}";
        $command = "cp $makefileFromPath $testDir";
        if (system($command) != 0) {
            print STDERR "$0: Command $command failed\n";
            goto end;
        }
    } # foreach test
    $returnVal = 1;

end:
    return($returnVal);
} #exportTests

# *********************************************************************

# Create a makefile suitable for compiling an exported gba library.
# The makefile is derived from a template.

sub
copyModifyMakefile($$$$$)
{
    my ($makefileTemplate, $destMakefile, $fileListRef,
        $libName, $nitroSdkRoot) = @_;
    my ($line);
    my $srcLineFound = 0;
    my $libLineFound = 0;
    my $returnVal = 0;

    unless (open MAKE_IN, "$makefileTemplate") {
        print STDERR "$0: Can't open file $makefileTemplate: $!\n";
        goto end;
    }
    unless (open MAKE_OUT, ">$destMakefile") {
        print STDERR "$0: Can't open file $destMakefile for writing: $!\n";
        goto end;
    }
    print MAKE_OUT "#! make -f\n\n";
    print MAKE_OUT "# This is a generated file - do not edit it\n\n";
    print MAKE_OUT "LINCLUDES += $NitroRootDosForward/$NitroGlobalIncludeDir/ds\n";
    print MAKE_OUT "LINCLUDES += $NitroRootDosForward/$NitroGlobalIncludeDir\n\n";
    while (defined($line = <MAKE_IN>)) {
        $line = dosChomp($line);
        if ($line =~ m/^\s*SRCS\s*=\s*/o) {
            my ($libSrcFile);

            print MAKE_OUT "SRCS =";

            foreach $libSrcFile (@$fileListRef) {
                my ($name);
                ($name) = fileparse($libSrcFile);
                print MAKE_OUT " $name";
            }
            print MAKE_OUT "\n";
            $srcLineFound = 1;
        }
        elsif ($line =~ m/^(\s*TARGET_LIB\s*=\s*)([^\s]+)/o) {
            my $leftHandSide  = $1;
            my $rightHandSide = $2;

            if ($rightHandSide =~ s/[Xx]+/$libName/o) {
                print MAKE_OUT $leftHandSide;
                print MAKE_OUT $rightHandSide;
            }
            else {
                print STDERR "Can't find reg. exp [Xx]+ in $rightHandSide\n";
                goto end;
            }
            print MAKE_OUT "\n";
            $libLineFound = 1;
        }
        else {
            print MAKE_OUT "$line\n";
        }
    }
    if ($srcLineFound == 0) {
        print STDERR "$0: Can't find line of the form 'SRC =' in $makefileTemplate\n";
        goto end;
    }
    if ($libLineFound == 0) {
        print STDERR "$0: Can't find line of the form 'TARGET_LIB =' in $makefileTemplate\n";
        goto end;
    }
    $returnVal = 1;
end:
    close (MAKE_IN);
    close (MAKE_OUT);
    return($returnVal);
} # copyModifyMakefile

# *********************************************************************

# Get rid of any '\r' or '\n' or both from the end of the string
# Return the string

sub
dosChomp($)
{
    my ($line) = @_;
    my ($lastChar);

    $lastChar = substr($line, -1, 1);
    if ($lastChar eq "\r" || $lastChar eq "\n") {
        $line = substr($line, 0, -1);
    }
    if ($lastChar eq "\r" || $lastChar eq "\n") {
        $line = substr($line, 0, -1);
    }
    return($line);
}


# *********************************************************************

# Determine if possible the full path name to the 'sw' directory
# in a gba source tree.
# Return the full path, or undef if it cannot be determined.

sub
findGbaSrcRoot()
{
    my ($gbaSrcRoot);

    $gbaSrcRoot = $ENV{'GBA_SRC_ROOT'};
    if (defined ($gbaSrcRoot)) {
        my ($name, $path);

        if (! -d $gbaSrcRoot) {
            print STDERR "$0: Env variable GBA_SRC_ROOT is not a directory\n";
            return (undef);
        }
        ($name, $path) = fileparse($gbaSrcRoot);
        if ($name eq "sw") {
            return($gbaSrcRoot);
        }
        else {
            my $lastChar;

            $lastChar = substr ($gbaSrcRoot, -1, 1);
            if ($lastChar ne "/") {
                $gbaSrcRoot .= "/";
            }
            $gbaSrcRoot .= "sw";
            if (-d $gbaSrcRoot) {
                return($gbaSrcRoot);
            }
            else {
                print STDERR "0: Env variable GBA_SRC_ROOT has invalid value\n";
                return(undef);
            }
        }
    }
    else {
        # Try to get the GBA root by examining the current working
        # directory
        my      ($cwd, $i, @pathFiles);

        $cwd = cwd();
        @pathFiles = split /\//, $cwd;

        # Try to find the last instance of 'sw' in path.
        # If it is found, take the cwd path up to and including
        # the sw and call it the gba source root
        for ($i = $#pathFiles; $i >= 0; $i--) {
            if ($pathFiles[$i] eq "sw") {
                splice(@pathFiles, $i + 1);
                $gbaSrcRoot = join("/", @pathFiles);
                return($gbaSrcRoot);
            }
        }
        print STDERR "$0: Must define GBA_SRC_ROOT to point to root of gba source tree\n";
    }
    return(undef);
}

# *********************************************************************

sub
main()
{
    my ($optReturn, $help, $verbose);
    my ($gbaSrcRoot);
    my $internal;               # Export files only used at Broadon
    my $exitVal = 1;            # Default to exit code for failure

    #print "$0: arguments are: @ARGV\n";

    $optReturn = GetOptions (
                                 "help"    	        => \$help,
                                 "internal"             => \$internal,
                                 "verbose" 	        => \$verbose,
                             );
    unless ($optReturn) {
        print STDERR "$0: Parsing command line options failed\n";
        usage();
        exit(1);
    }
    if (defined ($help)) {
        usage();
        exit(0);
    }
    if (defined($verbose)) {
        $Verbose = 1;
    }
    else {
        $Verbose = 0;
    }
    if (defined($internal)) {
        $internal = 1;
    }
    else {
        $internal = 0;
    }
    if (! defined($ENV{$NITRO_ROOT_NAME})) {
        print STDERR "$0: Error: $NITRO_ROOT_NAME undefined\n";
        goto end;
    }
    $NitroRootDos = $ENV{$NITRO_ROOT_NAME};
    if (! -d $NitroRootDos) {
        print STDERR "$0: Error: Environment variable $NITRO_ROOT_NAME\'s value is not a directory \n";
        goto end;
    }
    $NitroRootDosForward = $NitroRootDos;
    $NitroRootDosForward =~ s/\\/\//go;
    $NitroRoot = convertToUnixPath($NitroRootDos);

    $gbaSrcRoot = findGbaSrcRoot();
    if (! defined($gbaSrcRoot)) {
        print STDERR "$0: Can't determine root directory of gba source tree\n";
        print STDERR "$0: Please define GBA_SRC_ROOT to the root of a gba source tree\n";
        goto end;
    }

    unless (errorCheckedMkdir("$NitroRoot/$NitroGlobalIncludeDir")) {
        goto end;
    }
    unless (copyFilesToTree(\@globalIncludes, $gbaSrcRoot,
                            "$NitroRoot/$NitroGlobalIncludeDir")) {
        goto end;
    }
    unless (exportLibraries($gbaSrcRoot, $internal, @exportLibList)) {
        goto end;
    }

    if ($internal != 0) {
        unless (exportTests($gbaSrcRoot, @exportTestList)) {
            goto end;
        }
    }

    $exitVal = 0;

end:
    exit($exitVal);
} # main

main;
