#!/bin/bash

TPUT="`which tput`"
if test -t 0 -a -t 1 -a -n "$TPUT"; then
        CI="`$TPUT setf 6 || true`"; CE="`$TPUT setf 4 || true`"
        CX="`$TPUT setf 2 || true`"; CN="`$TPUT sgr0 || true`"
else    CI=''; CE=''; CX=''; CN=''
fi

CUR_DIR=`pwd`
ZIP_FILE=$1
INSTALLER_BIT=$2
OUTPUT_FILE=installer.bin
cp $CUR_DIR/installer_stub installerstub_cp
INSTALLSTUB="installerstub_cp"

echo "checking"
ORI_MD5SUM=`md5sum "$ZIP_FILE" | awk '{ print $1 }'`
ORI_LEN=`wc -l "$INSTALLSTUB" | awk '{ print $1 }'`
ORI_LEN=`expr $ORI_LEN + 1`

echo "making"
sed -e "s|\$\$\$\$__CHKSUM_REPLACE__\$\$\$\$$|\"$ORI_MD5SUM\"|g" $INSTALLSTUB > _temp_1
sed -e "s|\$\$\$\$__FILE_LENGTH_REPLACE__\$\$\$\$$|\"$ORI_LEN\"|g" _temp_1 > _temp_2
sed -e "s|\$\$\$\$__INSTALLER_BIT__\$\$\$\$$|\"$INSTALLER_BIT\"|g" _temp_2 > _temp_3

cp _temp_3 $OUTPUT_FILE
cat $ZIP_FILE >> $OUTPUT_FILE
rm _temp_1 _temp_2 _temp_3

echo "add +x"
chmod +x $OUTPUT_FILE
