#!/bin/sh
# FILE: /usr/sbin/apm (ARM Package Manager)
# Copyright (C) 2012 GuoWenxue <guowenxue@gmail.com>
# This shell script used to upgrade the Application/Firmware

exit_out()
{
   exit $1
}

usage()
{
    printf "Usage: $0 [-r] APM_FILE\n"
    printf "\nUpgrade system firmware or application APM file\n"
    printf "\n\t-r After upgrade reboot system immediately.\n"
    exit_out 1;
}

if [ $# -le 0 ] ; then
    usage
fi

while getopts "rh" opt
do
    case $opt in 
        r) 
            SYSTEM_REBOOT=yes
            shift 1
            break
            ;;

        h)
            usage
            ;;

        ?)
            usage
            ;;
    esac
done

apm_file=$1
if [ -z $apm_file ] ; then 
   usage
fi

#Check APM file exist or not
if [ ! -s $apm_file ] ; then 
   echo "APM file \"$apm_file\" is not found..."
   exit
fi

base_name=`basename $apm_file`
apm_name=`echo $base_name | awk -F "." '{print $1}'`
work_path=/tmp/.$apm_name
patch_file="$work_path/patch.sh"

echo -n "Performing decompression             "
rm -rf $work_path
if ( tar -xzf $apm_file -C /tmp && mv /tmp/$apm_name $work_path )
then
	rm -f $apm_file
	echo "[  OK  ]"
else
	echo "[ FAIL ]"
	exit_out 1
fi

echo -n "Check APM patch file                 "
if [ -s $patch_file ] ; then
	echo "[  OK  ]"
else
	echo "[ MISS ]"
	exit_out 1
fi

chmod 777 "$patch_file"
if ("$patch_file" "$work_path")
then
	echo "Applied APM patch                    [  OK  ]"

else
	echo "Applied APM patch                    [ FAIL ]"
	exit_out 1
fi

if [ "$SYSTEM_REBOOT" = "yes" ] ; then 
	echo "Reboot system now                    [  OK  ]"
	reboot
else	
	echo "Reboot system now                    [ SKIP ]"
fi

exit_out 0
