#!/bin/bash
#
# Script to build iBMC platform firmware
# Must be placed in and invoked from the <Project>/scripts directory
#
# Revsion history:
#    2007-03-08 Initial version
#    2007-03-16 Simplify build process
#    2007-04-18 Link /root/cc to cc if it doesn't exist
#   2011-09-23 Signatures are now mandatory, and adding new support for
#              replacement signatures (using devbuild as default).
#   2011-09-24 Review and revise to correctly support replacements.
#              Refactor and clean up code.
#

####################################################################
# Usage

function DisplayUsage()
{
    # Currently, Custom processing only means translate english to chinese for Lenovo's special build.
    echo "Usage:$0 <BuildType> <PlatformName> [ | <AutoSign>| <RELEASETYPE> ]"
    echo "OR $0 -t BuildType -p PlatformName { -autosign } { -r (RELEASE|DEV) }{ -k KEYSETNAME }"
    echo "   invocation format can be mixed up til the first - at which point any following require a -opt." 
    echo "   <BuildType> can be BUILD/REBUILD/CLEAN or BUILDDEV/REBUILDDEV/CLEANDEV or IMAGE or WIPE"
    echo "   For compatibility it can also be MKOPEN/OPENTAR/MKPDK for certain special builds."
    echo "   If a replacement key is present in the configs.IBMC directory, it will be integrated."
    echo "   RELEASETYPE (-r) determines whether or not to use the default keys in the DevKeys directory,"
    echo "   or to use the Release key set.  Note, -k will override this default and will select another"
    echo "   key set.  The key set is a tar file and must exist in the DevKeys directory."
    echo "   Platform Name is needed only if there is more than one platform configs directory"
    echo "   <AutoSign> can be AUTOSIGN_ENABLED/AUTOSIGN_DISABLED to enable or disable converting unsigned"
    echo "   images to signed images, but this may be unsupported by called scripts."
    echo " Note, prepend CUSTOM_ to <BuildType> to enable the Lenovo build. e.g. CUSTOM_BUILD"
    exit 1
}

#  Algorithm: Determine whether to do BUILD, REBUILD, or CLEAN, or an IMAGE
#  build, or a WIPE.  The BUILDDEV etc are mostly redundant since this
#  script won't support reading release keys. Further, they use the
#  BUILDDEV script, which is not used in the current build paradigm
#
#  For a WIPE, erase the Build.PROJECT directory, even if it's IBMC.
#              erase the configs.PROJECT directory except if it's IBMC
#  For a CLEAN, same as WIPE
#  For a BUILD, erase the Build directory EXCEPT if it's IBMC. Don't erase
#  the configs dir.
#  For a REBUILD, don't erase any directory.
#  For an IMAGE, don't erase any directory

#  Notes re:numbering differences if maintaining this program vs. the PHP version:
#  For the shell, $# is always the number of arguments, not including the
#  command name.  For php, using $argc, the command name IS included.
# 

minArg=1;

if [ $# -lt $minArg ]
then
    DisplayUsage
fi

####################################################################
# Setup

THISDIR=$( readlink -f "$( dirname "${BASH_SOURCE[0]}" )" )
export TOPDIR=`dirname $THISDIR`
export ROOT_DIR=`dirname $TOPDIR`
export PLATFORM
export AUTOSIGN
export PDKDIR="$TOPDIR/development/oem/firmware/IPMI/oem/Intel"
export PATH=$TOPDIR/cc2/bin:$TOPDIR/tools:$TOPDIR/misctools:$PATH

# "Usage: $0 <BuildType> <PlatformName> [ | <AutoSign>| <RELEASETYPE> ]"
# "OR $0 -t BuildType -p PlatformName { -autosign } { -r (RELEASE|DEV) }{ -k KEYSETNAME }"
# Technically, we permit multiple instances of a -switch, using the last
# one. Pragmatically, don't do that. Also, build type and platform MUST be set. 

buildSet=false
platSet=false
positional=true
arg="buildType"
CanRelease=0
KEYSET=""
BLD="DEV"
while [ "x$1" != "x" ]
do
    case $1 in 
        "-t" )
            positional=false
            shift
            if [ "x$1" == "x" ]; then echo "Too few arguments."; DisplayUsage; fi
            BUILD_TYPE=$1
            buildSet=true
            shift
        ;;
        "-p" )
            positional=false
            shift
            if [ "x$1" == "x" ]; then echo "Too few arguments."; DisplayUsage; fi
            PLATFORM=$1
            platSet=true
            shift
        ;;
        "-autosign" )
            positional=false
            shift
            AUTOSIGN="AUTOSIGN_ENABLED"
        ;;
        "-r" )
            positional=false
            shift
            if [ "x$1" == "x" ]; then echo "Too few arguments."; DisplayUsage; fi
            case $1 in 
                "RELEASE" )
                    BLD="RELEASE"
                ;;
                "DEV" )
                    BLD="DEV"
                ;;
                * )
                    echo "Invalid argument to -r $1."
                    exit 1
                ;;
            esac
            shift
        ;;
        "-k" )
            positional=false
            shift
            if [ "x$1" == "x" ]; then echo "Too few arguments."; DisplayUsage; fi
            KEYSET=$1
            shift
        ;;
        * )
            if [ ! $positional ]; then echo "Error: once -option is used, positional options are forbidden."; exit 1; fi
            case $arg in 
            "buildType" )
                BUILD_TYPE=$1
                buildSet=true
                shift
                if [ "x$1" == "x" -a ! $platSet  ]; then echo "Too few arguments."; DisplayUsage; fi
                arg="platformName"
            ;;
            "platformName" )
                PLATFORM=$1
                platSet=true
                shift
                if [ "x$1" == "x" -a ! $buildSet  ]; then echo "Too few arguments."; DisplayUsage; fi
                arg="platformName"
            ;;
            "autoCheck" | "releaseType")
                if [ $arg == "releaseType" -a $1 == "RELEASE" ]
                then
                    BLD="RELEASE"
                fi
                if [ $arg == "releaseType" ]
                then
                    echo "There is no valid option at this point. $1 is nonsense."
                    exit 1
                fi
                if [ $arg == "autoCheck" ]; then arg="releaseType"; else arg="tooMany"; fi
                # Default to disabled.
                AUTOSIGN="AUTOSIGN_DISABLED"
                case $1 in 
                    "AUTOSIGN_ENABLED" )
                        AUTOSIGN="AUTOSIGN_ENABLED"
                        arg="releaseType"
                    ;;
                    "DEV" )
                        BLD="DEV"
                        arg="tooMany"
                    ;;
                    "RELEASE" )
                        BLD="RELEASE"
                    ;;
                    "AUTOSIGN_DISABLED" )
                        AUTOSIGN="AUTOSIGN_DISABLED"
                    ;;
                    * )
                        echo "Unknown argument or parameter $1. Aborting."
                        exit 1
                    ;;
                esac
                shift
                ;;
                "tooMany" )
                    echo "Too many arguments at $1.  Aborting."
                    exit 1
                ;;
            esac
            ;;
    esac
done

PROJ=`basename $TOPDIR`

if ! [ $buildSet -a $platSet ]
then
    echo "Missing either build type or platform name"
    DisplayUsage
    exit 1
else
    # We insist on platform name. So see if it has a configs directory
    if [ ! -d $TOPDIR/configs.IBMC ]
    then
        echo "Can't find $TOPDIR/configs.IBMC directory, Aborting"
        exit 1
    fi
    if [ $PLATFORM != IBMC -a ! -f $TOPDIR/configs.IBMC/config.$PLATFORM ]
    then
        echo "Can't find $TOPDIR/configs.IBMC/config.$PLATFORM file, Aborting"
        exit 1
    fi
fi

export CUSTOMIZE=0
BUILDING=0

case $BUILD_TYPE in
    "CUSTOM_BUILDDEV" )
        export CUSTOMIZE=1
        DEVBUILD=1
        BUILDING=1
        if [ $PLATFORM != IBMC ]; then ERASE=1; else ERASE=0; fi
    ;;
    "BUILDDEV" )
        DEVBUILD=1
        BUILDING=1
        if [ $PLATFORM != IBMC ]; then ERASE=1; else ERASE=0; fi
    ;;

    "CUSTOM_BUILD" )
        export CUSTOMIZE=1
        DEVBUILD=0
        BUILDING=1
        if [ $PLATFORM != IBMC ]; then ERASE=1; else ERASE=0; fi
    ;;
    "BUILD" )
        DEVBUILD=0
        BUILDING=1
        if [ $PLATFORM != IBMC ]; then ERASE=1; else ERASE=0; fi
    ;;

    "CUSTOM_REBUILDDEV" )
        export CUSTOMIZE=1
        DEVBUILD=1
        BUILDING=1
        ERASE=0
    ;;
    "REBUILDDEV" )
        DEVBUILD=1
        BUILDING=1
        ERASE=0
    ;;

    "CUSTOM_REBUILD" )
        export CUSTOMIZE=1
        DEVBUILD=0
        ERASE=0
        BUILDING=1
    ;;
    "REBUILD" )
        DEVBUILD=0
        ERASE=0
        BUILDING=1
    ;;

    "CUSTOM_CLEANDEV" )
        export CUSTOMIZE=1
        DEVBUILD=1
        ERASE=0
    ;;
    "CLEANDEV" )
        DEVBUILD=1
        ERASE=0
    ;;

    "CUSTOM_CLEAN" )
        export CUSTOMIZE=1
        DEVBUILD=0
        ERASE=0
    ;;
    "CLEAN" )
        DEVBUILD=0
        ERASE=0
    ;;

    "CUSTOM_IMAGE" )
        export CUSTOMIZE=1
        DEVBUILD=0
        ERASE=0
        BUILDING=1
    ;;
    "IMAGE" )
        DEVBUILD=0
        ERASE=0
        BUILDING=1
    ;;

    "CUSTOM_WIPE" )
        export CUSTOMIZE=1
        DEVBUILD=0
        ERASE=1
    ;;
    "WIPE" )
        DEVBUILD=0
        ERASE=1
    ;;


    "CUSTOM_MKOPEN" | "CUSTOM_OPENTAR" )
        export CUSTOMIZE=1
        DEVBUILD=0
        ERASE=0
        BUILDING=0
    ;;
    "MKOPEN" | "OPENTAR" )
        DEVBUILD=0
        ERASE=0
        BUILDING=0
    ;;

    "CUSTOM_MKPDK" )
        export CUSTOMIZE=1
        DEVBUILD=1
        ERASE=0
        BUILDING=1
    ;;
    "MKPDK" )
        DEVBUILD=1
        ERASE=0
        BUILDING=1
    ;;

    * )
        echo "I don't know what $BUILDTYPE means."
        DisplayUsage
    ;;
esac

# Remove any existing platform config directory and create a new copy for this platform
# We use "erase" to determine whether to remove and recreate the build and configs directories
# We do not remove configs.IBMC though
if [ "$PLATFORM" = "IBMC" ]; then ERASE=0; fi
if [ $ERASE -eq 1 ]
then
    rm -rf $TOPDIR/configs.$PLATFORM
    cp -a $TOPDIR/configs.IBMC $TOPDIR/configs.$PLATFORM

    # Further customize the config files with the platform specific overrides directory
    if [ -e "$TOPDIR/configs.$PLATFORM/overrides/$PLATFORM" ]
    then
        cp -a $TOPDIR/configs.$PLATFORM/overrides/$PLATFORM/* $TOPDIR/configs.$PLATFORM
        if [ $? -ne 0 ]
        then
            echo "Error during platform cloning overrides for $PLATFORM."
            exit 1
        fi
    fi
fi

PDKDIR="$TOPDIR/development/oem/firmware/IPMI/oem/Intel";

if [ !  -d "$TOPDIR/Intel" ]
then
    echo "Creating softlink to Intel development tree ... "
    ln -s $PDKDIR "$TOPDIR/Intel"
    echo "Done"
fi

####################################################################
# Cross-compiler version check

CCCONFIG=cc2.build.log.bz2
CC_DIR=$TOPDIR/cc2
DEFAULT_CC_DIR=/root/cc2

if ! [ -d $CC_DIR ]
then
    if ! [ -d $DEFAULT_CC_DIR ]
    then
        echo "Missing cross-compiler directory $CC_DIR ...Aborting"
        exit 1
    fi

    ln -s $DEFAULT_CC_DIR $CC_DIR
    if [ $? != 0 ]
    then
        echo "Failed to link $DEFAULT_CC_DIR as $CC_DIR ...Aborting"
        exit 1
    fi
fi

if ! [ -e $CC_DIR/$CCCONFIG ]
then
    echo "Missing cross-compiler version file $CC_DIR/$CCCONFIG ...Aborting"
    exit 1
fi

if ! [ -e $TOPDIR/configs.$PLATFORM/$CCCONFIG ]
then
    echo "Missing cross-compiler version file $TOPDIR/configs.$PLATFORM/$CCCONFIG ...Aborting"
    exit 1
fi

cmp $TOPDIR/configs.$PLATFORM/$CCCONFIG $CC_DIR/$CCCONFIG
if [ $? != 0 ]
then
    echo "Wrong version of cross-compiler is present"
    echo "...See $TOPDIR/configs.$PLATFORM/$CCCONFIG for expected version"
    echo "...Aborting"
    exit 1
fi


####################################################################
# Build

# Call PreBuildDev Hook in configs/scripts dir if any
# PreBuildDev does NOT install nor require the keys or certs.
if [ -e $TOPDIR/configs.$PLATFORM/scripts/PreBuildDev ]
then
    sh $TOPDIR/configs.$PLATFORM/scripts/PreBuildDev $1
    if [ $? != 0 ]
    then
        echo "ERROR executing platform PreBuildDev script. Aborting!!!"
        exit 1
    fi
fi

# Actual build
if [ "$BLD" = "RELEASE" ]
then
	RELEASE_OPTION="RELEASE=1"
else
	RELEASE_OPTION=""
fi
echo "Build type $BUILD_TYPE started at:  " `date`
nice ./BuildProject.oem $PROJ:$PLATFORM $BUILD_TYPE $ROOT_DIR $RELEASE_OPTION 2>&1
RESULT=$?
echo "Build type $BUILD_TYPE finished at: " `date`

if [ $RESULT != 0 ]
then
    echo "Build script failed ... Aborting"
    exit 1
fi






if [ $BUILDING -eq 1 ]
then
    # Display the Build Number
    BLDNUMFILE=$TOPDIR/Build.$PLATFORM/buildnumber.h
    if [ -e $BLDNUMFILE ]
    then
        echo ""
        echo "The Build Number for $PLATFORM is" `cat $BLDNUMFILE | grep VERS_BLDNUM | awk '{print $3}'`
        if [ $? != 0 ]
        then
            echo "WARNING: unable to determine the build number"
        fi
    else
        echo "WARNING: $BLDNUMFILE file not found"
    fi
fi

####################################################################
# tftp server setup
#
#SETUPTFTP=./setuptftp
#
#if [ -e $SETUPTFTP ]
#then
#    echo "Copying images to the tftp server directory used during development"
#    sh $SETUPTFTP $1 $2 $3
#    if [ $? != 0 ]
#    then
#        echo "ERROR executing tftp setup script. Aborting!!!"
#        exit 1
#    fi
#fi
#
#
####################################################################
# Done

exit 0

