#!/bin/bash

if [ -z $1 ] || [ -z $2 ] || [ -z $3 ]; then
	echo "    genBinfile [models] [FW*.pck] [flash_size]"
	exit -1
fi

EnChecksum=$6
models=$1
pck_file=$2
flash_size=$3
pack_name=ipcam
bs_file=BootSector.bin
if [ -z $4 ]; then
	prob_file=norboot.bin
else
	prob_file=$4
fi
echo "prob_file " $prob_file
factory_path=$PROJ_ROOT/factory/$models
cfg_file=config.tgz
out_file=out.bin
info_file=info.txt

# Generate the config.tgz
mkdir config
cd config
tar -zxvf $factory_path/factory_default.tgz 1> /dev/null
if [ $? -ne "0" ]; then
	exit 1
fi
cd ..
tar -zcvf $cfg_file config/ 1> /dev/null
if [ $? -ne "0" ]; then
	exit 1
fi

# Show the Infomation
rm -rf $pack_name.bin
echo ----$(date +%c)---- > $pack_name.log
echo model=$models, fw_version=$5 >> $pack_name.log
echo Info=$info_file >> $pack_name.log
echo BootSector=$bs_file >> $pack_name.log
echo fw_file=$pck_file >> $pack_name.log
echo config_file=$factory_path/factory_default.tgz >> $pack_name.log
echo proboot_file=$prob_file >> $pack_name.log

# Write the Info.txt to the BootSector
./BootSectorModifier $bs_file $info_file | tee -a $pack_name.log

# Generator Bin file
./BinfileGenerator $bs_file $pck_file $cfg_file $prob_file $flash_size $EnChecksum | tee -a $pack_name.log
if [ $? -eq "0" ]; then
	mv $out_file $pack_name.bin
	echo "Bin file is ready!!"
else
	echo "Bin file cannot been generated!!"
fi
rm -rf config
rm -rf $cfg_file
