#!/bin/bash

# exit on error
set -e

source ../Config.sh

mksdk_usage () {
cat <<EOF
mksdk - make software development kit from eric_firmware

Create a sdk from the eric_firmware. The sdk consists of everything to enhance
the firmware with vendor specific programs. It contains the install_root in
binary form as well as the include files, the uClib and the compiler chain.
In addition an sdk can contain a configurable part of the peppercon sourcecode.

USAGE:

mksdk -r [ auto | <tag> ] -c <configfile> -f <firmwarefile>

-r  Revision information
    Each sdk is associated with exactly one sourcecode revision.
      auto          Retrieve the revision string from the from the fwbuildinfo
                    file that is copied to mksdk from the mkfirmware.pl
                    script. This option should be used right after building 
                    (and tagging) the firmware.
      <tag>         Allows the creation of SDKs that are not derived from CVS
                    tags. Inofficial SDKs are named explicitly. <tag> must be
                    one word without spaces or special characters.

-c  Config file
    Specifies a configuration file that adds additional sourcecode packages to
    the sdk. Use default_sdk.cfg if no special SDK configuration is required.
      <configfile>  The name of the configuration file

-f Firmware file
   Since 15.11.2005 the firmware file corresponding to the SDK is a part of
   the SDK. This options specifies which firmware file this SDK is related with.
   The file must exist and will be packed with the SDK.
     <firmwarefile>  The name of the firmware file to include

   
EXAMPLE

mksdk -r auto -c ipmi_sdk.cfg \
    -f ../mkfirmware/fw-lara-kimmsi-msidc-peppercon_040100-9999.bin


EOF
}

FWMSG="       Make sure there is a matching firmware for this SDK\n\
       that has been created with mkfirmware.pl. This will copy\n\
       the required information to ./fwbuildinfo !!!"

basedir=`pwd`

# parse the command line
if [ "$#" -lt 6 ] ; then
    mksdk_usage
    exit 1
fi
if ( [ "$1" != "-r" -o "$3" != "-c" -o "$5" != "-f" ] ) ; then
    mksdk_usage
    exit 1
fi

firmware_file=$6
if ! [ -e "$firmware_file" ] ; then
    mksdk_usagec
    echo -e
    echo -e ERROR: firmware file not found
    echo -e
    exit 1
fi

if [ "$2" = "auto" ] ; then
    # comparing with a file in mkfirmware is just a simple up to date test
    if [ -r ./fwbuildinfo -a ! ./fwbuildinfo -ot $firmware_file ]
    then
      revision_tag=`cat fwbuildinfo`
    else 
     mksdk_usage
     echo -e
     echo -e "ERROR: ./fwbuildinfo is not present or most probably not up to date!\n"
     echo -e "${FWMSG}\n"
     exit 1
    fi
else
    revision_tag="${2}"
fi

# check for version and build number in revision_tag, bail out if not there
FW_VERSION=`echo $revision_tag | sed 's/.*_\([0-9]\{6\}\)-\([0-9]\{4\}\)/\1/'`
FW_BUILDNR=`echo $revision_tag | sed 's/.*_\([0-9]\{6\}\)-\([0-9]\{4\}\)/\2/'`
if [ "$FW_VERSION" = "" -o "$FW_BUILDNR" = "" ] ; then
  echo -e "\nERROR: can't determine version and build-nr from fw-tag!\n\
       fw-tag=$revision_tag\n\
       fw-version=$FW_VERSION\n\
       fw-buildnr=$FW_BUILDNR\n"
  echo -e "${FWMSG}\n"
  exit 1
fi

config_file=$4
if ! [ -e "$config_file" ] ; then
    mksdk_usage
    echo -e
    echo -e ERROR: config file not found
    echo -e
    exit 1
fi


# parse the configuration file
#
# command to read the config file, remove comments and empty lines:
# sed -e 's/#.*$//g' -e '/^ *$/d' -e 's/^ *//g'

# get the first data line with the config name
config_name=`sed -e 's/#.*$//g' -e '/^ *$/d' -e 's/^ *//g' -e 'q' $config_file`

#get the remaining lines and concatenate them to a list of source subdirectories
source_dir_list=""
for subdir in `sed -e 's/#.*$//g' -e '/^ *$/d' -e 's/^ *//g' $config_file | sed -e '1D'`; do
    subdir_expanded="`eval echo $subdir`"
    source_dir_list=`echo -e "$source_dir_list\n$subdir_expanded"`
done

# start building the sdk
#########################################

myapp=`which $0`
mypath=`dirname $myapp`
pushd ${mypath}

source ../Config.sh

sdk_dir_name="${config_name}_sdk-${revision_tag}"
oem_dir_name="OEM/${PP_BOARD}_${PP_PRODUCT}_${PP_OEM}"

# cleanup dir if it exists
if [ -d "../mksdk/$sdk_dir_name" ]; then
    sudo rm -rf ../mksdk/$sdk_dir_name
fi
mkdir $sdk_dir_name
mkdir $sdk_dir_name/install_root_devel

echo "copy sdk-skeleton to $sdk_dir_name..."
tar -C sdk --exclude '.#*' --exclude '*~' --exclude CVS -cf - . |  tar -C $sdk_dir_name -xmf -
if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi

echo "create VERSION..."
now=`date`
cat > $sdk_dir_name/VERSION <<EOF
SDK Version Information:
created:  $now
------------------------------------------
PP_BOARD     = $PP_BOARD
PP_SUBBOARD  = $PP_SUBBOARD
PP_PRODUCT   = $PP_PRODUCT
PP_OEM       = $PP_OEM
SDK_TYPE     = $config_name
FW_VERSION   = $FW_VERSION
FW_BUILDNR   = $FW_BUILDNR
EOF
if [ $? -ne 0 ] ; then exit 1; fi

if [ "$source_dir_list" != "" ] ; then
    echo "Additional SDK sources" | cat >> $sdk_dir_name/VERSION
    
    for subdir in $source_dir_list; do
        echo -e "  ${subdir}" | cat >> $sdk_dir_name/VERSION
    done
fi

pushd ..

if [ "$PP_PRODUCT" = "msidc" ]; then
    echo "Adding MSI specific ipmitool scripts"
    cp bmc/test/msi*fru.sh mksdk/$sdk_dir_name/tools
fi

###################################
# copy essential stuff to SDK dir

echo "collect build system, clean it up first..."
./build_fw clean build_sys
tar --exclude '.#*' --exclude '*~' --exclude CVS -cf - build_sys | tar -C mksdk/$sdk_dir_name -xmf -
if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi
cp build_fw mksdk/$sdk_dir_name
cp build_fw_target.cfg mksdk/$sdk_dir_name || exit 1
cp toolchain.cfg mksdk/$sdk_dir_name || exit 1
cat >> mksdk/$sdk_dir_name/build_fw_target.cfg <<EOF

# add hint that we are in SDK (also disables deleting/relinking of includes)
in_sdk = 1

EOF
if [ $? -ne 0 ] ; then exit 1; fi

echo "collect includes of compiled libs to 'include'..."
incldir=${mypath}/${sdk_dir_name}/include
mkdir ${incldir}
#./build_fw copyincl ${incldir} || exit 1
#tar -chf - include/* | tar -C $incldir -xmf -
mkdir -p $incldir
cp -rHLf include/* $incldir ||:

echo "create rtsys - copy tared install_root_devel..."
sudo tar -C install_root_devel --exclude dev/* -cf mksdk/$sdk_dir_name/rtsys/install_root_devel.tar .
#if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi

echo "create rtsys - copy kernel image..."
if [ "${PP_BOARD}" = "kira" ]; then
	KERNEL_IMG_DIR="${LINUX_KERNEL_DIR}/arch/arm/boot"
else
	KERNEL_IMG_DIR="${LINUX_KERNEL_DIR}/arch/ppc/boot"
fi
# Kernel 2.6 has uImage under .../boot/, 2.4 has it under .../boot/images/
if ! [ -e "${KERNEL_IMG_DIR}/uImage" ] ; then
	KERNEL_IMG_DIR="${KERNEL_IMG_DIR}/images"
fi
tar -C ${KERNEL_IMG_DIR} -chf - uImage | tar -C mksdk/$sdk_dir_name/rtsys -xmf -
if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi

echo "create rtsys - copy SDK related firmware binary..."
cp $basedir/$6 mksdk/$sdk_dir_name/rtsys

echo "install uClibc binaris and headers needed for build..."
tar --exclude '.#*' --exclude '*~' --exclude CVS --exclude _install/bin --exclude _install/usr -cf - ${UCLIBC_DIR}/_install | tar -C mksdk/$sdk_dir_name -xmf -
if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi

# needed for uCLibc detection heuristic in build_fw.pl
mkdir mksdk/$sdk_dir_name/${UCLIBC_DIR}/libc
mkdir mksdk/$sdk_dir_name/${UCLIBC_DIR}/ldso

echo "collect OEM dir needed for builds..."
tar --exclude '.#*' --exclude '*~' --exclude CVS -cf - $oem_dir_name | tar -C mksdk/$sdk_dir_name -xmf -
oem_top_dir=$(grep "COMMON_OEM_DIR" $oem_dir_name/webpages/Makefile)
while [ ! -z "$oem_top_dir" ]; do
  oem_dir_name=$"`expr match "$oem_top_dir" '.*$(FW_TOPDIR)/\(.*\)'`"
  echo "Copy OEM files from $oem_dir_name"
  tar --exclude '.#*' --exclude '*~' --exclude CVS -cf - $oem_dir_name | tar -C mksdk/$sdk_dir_name -xmf -
  oem_top_dir=$(grep "COMMON_OEM_DIR" $oem_dir_name/webpages/Makefile || true )
done

echo "collect mkfirmware tools, needed to patch a firmware..."
# don't dump symlinks but the files they point to!
tar -chf - bin/mkimage mkfirmware/eRIC_Firmware.pm mkfirmware/update_firmware mkfirmware/data2img.sh mkfirmware/img2data.sh | tar -C mksdk/$sdk_dir_name -xmf -
if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi
cp mkfirmware/replacepart.pl mksdk/$sdk_dir_name/mkfirmware/replacepart.pl
cp mkfirmware/root_fw.sh mksdk/$sdk_dir_name/mkfirmware/root_fw.sh
cp mkfirmware/patch_version.pl mksdk/$sdk_dir_name/mkfirmware/patch_version.pl
cp mkfirmware/cryptpasswd.pl mksdk/$sdk_dir_name/mkfirmware/cryptpasswd.pl
cp mkfirmware/fw-bin-to-prod.pl mksdk/$sdk_dir_name/mkfirmware/fw-bin-to-prod.pl
cp -r mkfirmware/cpan mksdk/$sdk_dir_name/mkfirmware/
chmod u+x mksdk/$sdk_dir_name/mkfirmware/replacepart.pl
chmod u+x mksdk/$sdk_dir_name/mkfirmware/root_fw.sh
chmod u+x mksdk/$sdk_dir_name/mkfirmware/patch_version.pl
chmod u+x mksdk/$sdk_dir_name/mkfirmware/cryptpasswd.pl
chmod u+x mksdk/$sdk_dir_name/mkfirmware/fw-bin-to-prod.pl

function copy_static_lib {
    mkdir -p mksdk/${sdk_dir_name}/`dirname $1`
    cp -f $1 mksdk/${sdk_dir_name}/`dirname $1`
}

echo "copy xdefs.c"
mkdir -p mksdk/${sdk_dir_name}/eric/src/
cp -f eric/src/xdefs.c mksdk/${sdk_dir_name}/eric/src/


############################################################
# copy selected source projects

if [ "$source_dir_list" != "" ] ; then
    echo "clean/copy additional source modules... - $source_dir_list"

    cat >> mksdk/$sdk_dir_name/build_fw.cfg <<EOF
#
# Additional sources
EOF

    # clean subdirs before copying
    ./build_fw clean $source_dir_list

    for subdir in $source_dir_list ; do
        echo "adding $subdir ..."
        if [ -d "$subdir" ] ; then
            # copy source directory 
            tar --exclude '.#*' --exclude '*~' --exclude CVS -cf - $subdir | tar -C mksdk/$sdk_dir_name -xmf -
            if [ "${PIPESTATUS[*]}" != "0 0" ] ; then exit 1 ; fi
        else
            echo "Warning: $subdir cannot be found."           
        fi
    done
    
    echo -e "$source_dir_list" | mksdk/create_build_cfg.pl -b "${PP_BUILD_SYS_DIR}/build_fw.${PP_FW_TYPE}.cfg" -s - >> "mksdk/$sdk_dir_name/build_fw.cfg"
    if [ "$?" != "0" ]; then
	echo "Error creating build_fw.cfg for SDK"
	exit 1
    fi

    cat >> mksdk/$sdk_dir_name/build_fw.cfg <<EOF

# example applications added for SDK only
common|common|none: helloworld
EOF
fi

popd

popd
