#!/bin/sh

################################################################################
## Description: Merges a Fastboot IPL with a BSP to create a single .zip file
################################################################################

USAGE="Usage: fastboot_bsp_merge [-h -d] ipl_package.zip bsp_package.zip output_package.zip"

optDelete=0

while getopts "hd" OPT 
do
    case $OPT in
	h)	echo $USAGE
		exit 0
		;;
	d)	optDelete=1
		;;
    esac
done
shift `expr $OPTIND - 1`

# We need at least 3 arguments
if [ $# -lt 3 ]; then
	echo $USAGE >&2
	exit 1
fi

srcIplZip=$1
srcBspZip=$2
destZip=$3
destZipBaseName=`basename $destZip`
baseDir=`pwd`

# Make sure the destination doesn't exist or delete it if -d was specified
if [ -f "$destZip" ]; then
	if [ $optDelete == 1 ]; then
		rm -f $destZip
		if [ $? != 0 ]; then
			echo "ERROR: Couldn't delete $destZip" >&2
			exit 1
		fi
	else
		echo "ERROR: $destZip already exists, you must specify -d to overwrite it." >&2
		exit 1
	fi
fi

# Unzip the IPL source to a temporary directory
tempDir=`mktemp -d`
mkdir $tempDir/ipl
unzip $srcIplZip -d $tempDir/ipl

# Copy the BSP zip and add the IPL files to the combined zip. We must cd because
# the files added to the zip are added with paths relative to the current dir.
cp $srcBspZip $tempDir/$destZipBaseName
cd $tempDir/ipl
zip -ru ../$destZipBaseName .
cd $baseDir
mv $tempDir/$destZipBaseName $destZip

# Clean up after ourselves
rm -rf $tempDir

if [ -f "$destZip" ]; then
	echo "Successfully created $destZip"
else
	echo "ERROR: Failed to merge Fastboot and BSP"
fi

