#!/bin/sh
# ############################################################################
# (c) Copyright Virata Limited 1998
#
# Virata Limited Confidential and Proprietary
#
# The following software shell script ("Software") is strictly confidential and
# is proprietary to Virata Limited ("Virata").  It may only be read, used,
# copied, adapted, modified or otherwise dealt with by you if you have
# entered into a confidentiality agreement with Virata and then subject to the
# terms of that confidentiality agreement and any other applicable agreement
# between you and Virata.  If you are in any doubt as to whether you are
# entitled to access, read, use, copy, adapt, modify or otherwise deal with
# the Software or whether you are entitled to disclose the Software to any
# other person you should contact Virata.  If you have not entered into a
# confidentiality agreement with Virata granting access to this Software you
# should forthwith return all media, copies and printed listings containing
# the Software to Virata.
#
# Virata reserves the right to take legal action against you should you breach
# the above provisions.
#
# If you are unsure, or to report violations, please contact
# support@virata.com
# ############################################################################

# The format of this version string MUST BE "x.yy".
MKPRODUCT_VERSION="1.15"
export MKPRODUCT_VERSION

PROGRAM_NAME=`basename $0`
aconfig=aconfig

# Find a suitable version of touch. We specify /usr/bin/touch as on Solaris
# there are multiple (incompatible) versions of touch.
touch=/usr/bin/touch
if [ ! -f /usr/bin/touch ]; then
    touch=touch
fi

usage()
{
    cat <<EOF
usage: $PROGRAM_NAME [options] <product directory> [<hardware type>]
Version: $MKPRODUCT_VERSION

Options:
    -h     - Produce this help text
    -n     - Build a flash.bin which is network bootable
    -d     - Debug build
    -V     - Report version number
    -c dir - 'cd' to this directory before starting
    -v     - Be verbose
    -D     - Rebuild dependencies
    -C     - Clean (delete) build directories
    -k     - Keep going when some targets can't be made
    -W opt - Pass 'opt' through to 'aconfig'
    -b dir - Change build directory
    -j num - Passed through to make, number of jobs to run in parallel
    <product directory> = Name of *directory* containing the product
	                  .cfg file.
    <hardware tpye>     = Name of a hardware file

Examples:

Produce a flash.bin file in the build/products/modem-bd3000 directory:

    mkproduct products/modem-bd3000

Produce a network bootable flash.bin file in the build/products/bd3000-eth-gateway directory:

    mkproduct -n eth-gateway bd3000

EOF
    exit 1
}

error()
{
    echo "Error: $*" 1>&2
    exit 1
}

#
# Executed on exit. Removes the temporary directory
# created when dependencies are rebuilt.
#
cleanup() {
    if [ x$mkproduct_tmp != x ]; then
        if [ x$cwd != x ]; then
            cd $cwd
            rm -fr $BUILD_DIR/$mkproduct_tmp
        fi
    fi
}
trap cleanup EXIT


# Parse command line options.
BUILD_DIR="./build"
ACONFIG_ARGS="-M -n"
ACONFIG_ARGS_CACHE="aconfig_args"
MKFLASH_ARGS=""
SIMULATOR_BUILD=0
DEBUG_BUILD=0
DEBUG_DIR=""
REBUILD_DEP=0
VERBOSE_V=""
VERBOSE_v=""
VERBOSE_s="-s"
KEEP_GOING=""
CLEAN=0
NETWORK_BOOT=0
MAKE_JOBS=""

export DEBUG_DIR NETWORK_BOOT

while (expr $# \> 0 >/dev/null)
do
    option=$1

    case $option in
    -h)
        usage
        ;;

    -help)
        usage
        ;;

    -b)
	shift
	BUILD_DIR="$1"
	shift
	;;

    -c)
        shift
        cd $1
        shift
	;;

    -k)
	KEEP_GOING="-k"
	shift
	;;

    -C)
	CLEAN=1
	shift
	;;

    -j)
        shift
        MAKE_JOBS="-j $1"
        shift
        ;;

    -v)
        VERBOSE_V="-V"
	VERBOSE_v="-v"
	VERBOSE_s=""
	shift
        ;;

    -d)
	DEBUG_BUILD=1
	DEBUG_DIR=".debug"
	ACONFIG_ARGS="-Sdebug_system $ACONFIG_ARGS"
	shift
        ;;

    -n)
        NETWORK_BOOT=1
        shift
        ;;
    -V)
        echo $PROGRAM_NAME version $MKPRODUCT_VERSION
        exit 0
        ;;

    -D)
	REBUILD_DEP=1
	shift
	;;

    -W)
	shift
	ACONFIG_ARGS="$1 $ACONFIG_ARGS"
	shift
	;;

    -*)
	echo "Unknown option '$1'"
        usage
        ;;

    *)  if [ "$#" != "1" ] && [ "$#" != "2" ]; then
	    echo "Unknown argument '$1'"
	    usage
	fi
	break
	;;

    esac
done

# Check we've been given the right number of args.
if [ "$#" != "1" ] && [ "$#" != "2"  ]; then
    echo "Invalid number of arguments."
    usage
fi

# Check we can find a 'products' directory.
if [ ! -d ./products ]; then
    error "Could not find a 'products' directory - check that you are running inside an atmos tree."
fi

# Set up all our path variables (which could be overridden by the
# source "$PRODUCT_FILE" line later on.
PRODUCT_DIR=`basename $1`
if [ "$#" != "1" ]; then
    HWTYPE=`basename $2`
else
    # No hardware specified - use default if there is one
    if [ "$VIRATA_HWTYPE" != "" ]; then
        HWTYPE=$VIRATA_HWTYPE
        echo "Using hardware $HWTYPE"
    fi
fi

PRODUCT_MKFLASH_FILE="./products/$PRODUCT_DIR/mkflash.cfg"
PRODUCT_FILE="./products/$PRODUCT_DIR/mkproduct.cfg"
PRODUCT_POST_BUILD="./products/$PRODUCT_DIR/mkproduct.pbd"
PRODUCT_POST_PRCS="./products/$PRODUCT_DIR/mkproduct.pst"
PRODUCT_USER_POST_PRCS="./products/$PRODUCT_DIR/mkproduct.usr"
BUILD_FAILED=0
FLASHFS_DIR="./flashfs"

if [ $DEBUG_BUILD = 0 ]; then
    MKFLASH_ARGS="-DDEBUG= $MKFLASH_ARGS"
else
    MKFLASH_ARGS="-DDEBUG=$DEBUG_DIR $MKFLASH_ARGS"
fi

ARCH_EXT=""
if [ $SIMULATOR_BUILD = 1 ]; then
    ARCH_EXT="_`uname -sr | sed -e 's/ //' -e 's/\..*//'`"
    BUILD_DIR="./build$ARCH_EXT"
fi

# Read in config file for this build.
if [ ! -f $PRODUCT_FILE ]; then
    error "Cannot find product config file ($PRODUCT_FILE)."
fi

# Note this file could do absolutely anything but usually it just sets
# a few environment variables. But it could override certain functions
# if desired.
. "$PRODUCT_FILE"

# Does the build directory exist? If not create it.
mkdir -p $BUILD_DIR || error "Failed to create $BUILD_DIR"

# Set up hardware type prefix if the product wants us to use them
# this is determined by the "USE_HWTYPE" variable being set by mkproduct.cfg
if [ "$HWTYPE" != "" ] && [ "$USE_HWTYPE" != "" ]; then
    HWTYPE_PREFIX="$HWTYPE-"
    ACONFIG_ARGS="-Shwtype=$HWTYPE $ACONFIG_ARGS"
else
    HWTYPE_PREFIX=""
fi
MKFLASH_ARGS="-DHWTYPE=$HWTYPE_PREFIX $MKFLASH_ARGS"
PRODUCT_BUILD_DIR="$BUILD_DIR/products/$HWTYPE_PREFIX$PRODUCT_DIR"
export PRODUCT_BUILD_DIR

# Get the chip type that this hardware uses
if [ -f "source/hardware/$HWTYPE.hw" ]; then
    CHIP_TYPE=`grep HWCHIP source/hardware/$HWTYPE.hw`
    if [ "$CHIP_TYPE" != "" ]; then
        CHIP_TYPE=`echo $CHIP_TYPE | sed 's/^.*HWCHIP://'`
    fi
fi

# Check if that chip type has any extra configuration
# this is only done if the mkproduct.cfg has set USE_CHIP_CONFIG in mkproduct.cfg
# and if the chip type could be determined from the hardware file
if [ "$USE_CHIP_CONFIG" != "" ] && [ "$CHIP_TYPE" != "" ]; then
    if [ -f "products/chip_config/$CHIP_TYPE.cfg" ]; then
        . products/chip_config/$CHIP_TYPE.cfg
    fi
fi


# Backwards compatibility check. If some of the system files end in ".debug"
# then we should not automatically add .debug to the end. Ie. mkproduct.cfg
# files made before version 1.02 of mkproduct need this fix.
found_debug_system_file=0
for system in $SYSTEM_FILES
do
    if [ "$system" != "`echo $system | sed 's/.debug\$//'`" ]; then
	found_debug_system_file=1
    fi
done

if [ $found_debug_system_file = 1 ]; then
    echo -e "\015\033[1mInvoking backwards compatibility fix for mkproduct.cfg file.\033[0m"
    DEBUG_DIR=""
fi

atmosroot=`perl -MCwd -e 'print getcwd'`/source

# df - check if latest cygwin and if true change the path
if [ `echo $atmosroot | grep 'cygdrive'` ]; then
	atmosroot=`echo $atmosroot | sed 's/cygdrive\///'`
	atmosroot=`echo $atmosroot | sed 's/\/\([A-Za-z]\)/\1:/'`
fi

atmosroot=`echo $atmosroot | sed 's/tmp_mnt\///'`

# Have we been asked to rebuild dependencies?
for system in $SYSTEM_FILES
do
    system_dir="$HWTYPE_PREFIX$system$DEBUG_DIR"
    cwd=`pwd`

    # See if any 'aconfig' files have changed.
    if [ -f $BUILD_DIR/$system_dir/config.depend ]; then
	cd $BUILD_DIR/$system_dir
	make -f config.depend > /dev/null 2>&1
	config_dep=$?
	cd $cwd
    else
	config_dep="0"
    fi

    # Check if the 'aconfig arguments' are different for this build than previously
    # If so, then we need to rebuild dependencies.
    if [ -f $BUILD_DIR/$system_dir/$ACONFIG_ARGS_CACHE ]; then
        echo $ACONFIG_ARGS | diff -q $BUILD_DIR/$system_dir/$ACONFIG_ARGS_CACHE - >/dev/null 2>&1

        if [ "$?" != "0" ]; then
            config_dep=1
        fi

    fi

    # Do this if we've been forced to rebuild dependecies or if any aconfig file
    # have changed.
    if [ $REBUILD_DEP = 1 ] || [ "$config_dep" != "0" ]; then
	# 1) Take a copy of the old directory structure, makefiles and init.
	# 2) Re-run aconfig in real build directory.
	# 3) Diff all files, and restore date on any that were the same.

	# Is there a build directory for this system, and do we have an appropriate
	# system file?
	if [ -d $BUILD_DIR/$system_dir ] && [ -f ./system/$system ]; then
	    echo -e "\015\033[1mRebuilding dependencies for $system_dir:\033[0m"
	    # If no makefile then a previous invokation of aconfig failed
	    # so it's not a case of rebuilding deps, it's a case of rebuilding
	    # everything.
	    if [ -s $BUILD_DIR/$system_dir/makefile ]; then
		just_run_aconfig=0
	    else
		just_run_aconfig=1
	    fi

	    # Create a temporary working directory for ourselves, and take a copy of
	    # the old files.
	    if [ $just_run_aconfig = 0 ]; then
		mkproduct_tmp="__mkproduct_tmp_$$"
		rm -fr $BUILD_DIR/$mkproduct_tmp
		mkdir $BUILD_DIR/$mkproduct_tmp

		# Take a copy of the old files.
		cd $BUILD_DIR/$system_dir
		tar cf ../$mkproduct_tmp/_tmp.tar init syslink.input `find . \( -name \*makefile -o -name '*.module' -o -name '*.[ch]' \) -print`
		cd ../$mkproduct_tmp
		tar xf _tmp.tar
		cd ../..
	    fi

	    # Re-run aconfig
	    cd $BUILD_DIR/$system_dir

	    if [ "$VERBOSE_V" = "-V" ]; then
		echo "$aconfig $ACONFIG_ARGS $VERBOSE_V $atmosroot/../system/$system -r $atmosroot"
	    fi
	    
	    if $aconfig $ACONFIG_ARGS $VERBOSE_V $atmosroot/../system/$system -r $atmosroot; then
                # it worked
                true
            else
		BUILD_FAILED=1
		[ "$KEEP_GOING" != "" ] || error "Failed to build system $system_dir. ($?)"
	    fi

            # Record the aconfig arguments used
            echo $ACONFIG_ARGS >$ACONFIG_ARGS_CACHE

	    # Now put date back on files that are NOT different.
	    if [ $just_run_aconfig = 0 ]; then
		files=`diff -r -s . ../$mkproduct_tmp | grep 'File.*identical'\$ | awk '{print $2}'`

		for file in $files
		do
		    $touch -r ../$mkproduct_tmp/$file $file
		done

		rm -fr ../$mkproduct_tmp
	    fi
	fi
    fi

    cd $cwd
done


# Build all the system files needed for the flash image.
# The SYSTEM_FILES variable should be set in the 'source'ed PRODUCT_FILE.
for system in $SYSTEM_FILES
do
    system_dir="$HWTYPE_PREFIX$system$DEBUG_DIR"
    echo -e "\015\033[1m$system_dir:\033[0m"

    # Clean existing directory?
    if [ $CLEAN = 1 ] && [ -s $BUILD_DIR/$system_dir/makefile ]; then
	# Do the 'make clean'.
	cwd=`pwd`
	cd $BUILD_DIR/$system_dir

	if [ "$VERBOSE_V" = "-V" ]; then
	    echo "Cleaning $system_dir build directory."
	fi

	if make --no-print-directory $VERBOSE_s $KEEP_GOING clean; then
            # it worked
            true
        else
	    BUILD_FAILED=1
	    [ "$KEEP_GOING" != "" ] || exit 1
	fi
	echo

	cd $cwd
    fi

    # Does the build directory exist? If not we need to create it. This
    # is done by first copying any objects that exist in the products/objects
    # directory to the build directory, and then running aconfig on any
    # system files that exist.
    if [ ! -s $BUILD_DIR/$system_dir/makefile ]; then
	# Does the build directory exist for this system?
        mkdir -p $BUILD_DIR/$system_dir || error "Failed to create $BUILD_DIR/$system_dir."

	# Are there any objects?
        # First look in objects/hwtype-system[.debug], then objects/hwtype-system, then
        # objects/chiptype-system[.debug], and finally objects/chiptype-system.
        object_dir=""
        try_object_dir=./products/objects/$system_dir$ARCH_EXT
        if [ -d $try_object_dir ]; then
            object_dir=$try_object_dir
        else
            try_object_dir=./products/objects/$HWTYPE_PREFIX$system$ARCH_EXT
            if [ -d $try_object_dir ]; then
                object_dir=$try_object_dir
            else
                try_object_dir=./products/objects/$CHIP_TYPE-$system$DEBUG_DIR$ARCH_EXT
                if [ -d $try_object_dir ]; then
                    object_dir=$try_object_dir
                else
                    try_object_dir=./products/objects/$CHIP_TYPE-$system$ARCH_EXT
                    if [ -d $try_object_dir ]; then
                        object_dir=$try_object_dir
                    fi
                fi
            fi
        fi

	if [ "$object_dir" != "" ]; then
	    # Soure the object version file.
	    if [ -f $object_dir/object_version ]; then
		. $object_dir/object_version
	    fi

            if [ "$VERBOSE_V" = "-V" ]; then
                echo "Copying objects from  $object_dir"
            fi
	    # Copy the objects.
	    cp $VERBOSE_v -r $object_dir/* $BUILD_DIR/$system_dir || error "Failed to copy objects to build directory."
	fi

	# Is there a system file? If so, run aconfig.
	if [ -f ./system/$system ]; then
	    cwd=`pwd`
	    cd $BUILD_DIR/$system_dir

	    if [ "$VERBOSE_V" = "-V" ]; then
		echo "$aconfig $ACONFIG_ARGS $VERBOSE_V $atmosroot/../system/$system -r $atmosroot"
	    fi

	    if $aconfig $ACONFIG_ARGS $VERBOSE_V $atmosroot/../system/$system -r $atmosroot; then
                # it worked
                true
            else
		BUILD_FAILED=1
		[ "$KEEP_GOING" != "" ] || error "Failed to build system $system_dir."
	    fi

            # Record the aconfig arguments used
            echo $ACONFIG_ARGS >$ACONFIG_ARGS_CACHE

	    cd $cwd
	fi
    fi

    # Has the above stuff got us a top-level makefile, if not something has
    # gone wrong and we cannot continue.
    if [ ! -s $BUILD_DIR/$system_dir/makefile ]; then
	error "Failed to produce top-level makefile for $system_dir.
No system file or object distribution could be found."
    fi

    # Ok, now do the make.
    cwd=`pwd`
    cd $BUILD_DIR/$system_dir
    if [ "$VERBOSE_V" = "-V" ]; then
	echo "Running make."
    fi

    if make -r --no-print-directory $MAKE_JOBS $VERBOSE_s $KEEP_GOING; then
        # it worked
        true
    else
	BUILD_FAILED=1
	[ "$KEEP_GOING" != "" ] || exit 1
    fi

    cd $cwd
done

# Exit here, if a build has failed.
[ $BUILD_FAILED = 0 ] || exit 1

# Now execute a post build processing file if one exists.
if [ -f $PRODUCT_POST_BUILD ]; then
    . "$PRODUCT_POST_BUILD"
fi

# Create the necessary directory structure for the flash.bin file(s).
mkdir -p $BUILD_DIR/products ||
     error "Failed to create $BUILD_DIR/products"

mkdir -p $PRODUCT_BUILD_DIR ||
     error "Failed to create $PRODUCT_BUILD_DIR"

# Build the flash image taking in any files from the 'flashfs' directory.
# The FLASHFS_DIR variable should be set in the 'source'ed PRODUCT_FILE,
# or it uses the default "./flashfs".
if [ "$PRODUCT_MKFLASH_FILE" != "" ] && ([ -f $PRODUCT_MKFLASH_FILE ]); then
    # mkflash has now been replaced by the metamk tools. We therefore report
    # the fact that a mkflash.cfg files exists as a fatal error.
    error "This product directory contains a mkflash.cfg file. The mkflash
tool has now been replaced by the metamk collection of tools. You will
have to alter mkproduct.pst to use metamk, and delete the mkflash.cfg
file."
fi

# If we're doing a simulator build, delete the output from any previous build.
if [ $SIMULATOR_BUILD = 1 ]; then
    # Delete file if it exists.
    if [ -f $PRODUCT_BUILD_DIR/a.out ]; then
	rm $PRODUCT_BUILD_DIR/a.out
    fi

    # Create directory structure for result, if it doesn't exist.
    if [ ! -d $BUILD_DIR/products ]; then
	mkdir $BUILD_DIR/products || exit 1
    fi

    if [ ! -d $PRODUCT_BUILD_DIR ]; then
	mkdir $PRODUCT_BUILD_DIR || exit 1
    fi
fi

# Set Perl locale variable:
export LC_ALL=C

# Now execute the post processing file if one exists.
if [ -f $PRODUCT_POST_PRCS ]; then
    . "$PRODUCT_POST_PRCS"
fi

if [ "$?" != "0" ]; then
    error "$PRODUCT_POST_PRCS failed (rc=$?)"
fi

# Now execute the chip post processing file is one exists, and the
# product wants us to use it
if [ "$USE_CHIP_CONFIG" != "" ] && [ "$CHIP_TYPE" != "" ]; then
    if [ -f "products/chip_config/$CHIP_TYPE.pst" ]; then
      . "products/chip_config/$CHIP_TYPE.pst"
    fi
fi

# Now execute a user post processing file if one exists.
if [ -f $PRODUCT_USER_POST_PRCS ]; then
    . "$PRODUCT_USER_POST_PRCS"
fi

exit 0
