#!/bin/sh

type=$1
beroconf="/usr/local/bin/beroconf"
FWIMGDIR=/tmp/images
if [ ! -d "${FWIMGDIR}" ]; then
	mkdir -p ${FWIMGDIR}
fi

use_dhcp=`${beroconf} get root use-dhcp-settings | grep -v failed`
if [ "${use_dhcp}" = "yes" ] || [ "${use_dhcp}" = "1" ]; then
	prov_type=`${beroconf} get root dhcp-prov-type | grep -v failed`
else
	prov_type=`${beroconf} get root provisioning-option | grep -v failed`
fi


cd /usr/conf

function get_file {

#prov_type="http"
if [ "${prov_type}" = "http" ] ; then
	if [ "${use_dhcp}" = "yes" ] || [ "${use_dhcp}" = "1" ]; then
                http_host=$(${beroconf} get root dhcp-http-host | grep -v failed)
                http_path=$(${beroconf} get root dhcp-http-path | grep -v failed)
	else
		http_host=$(${beroconf} get root http-host | grep -v failed)
		http_path=$(${beroconf} get root http-url | grep -v failed)
	fi

	if [ -n "${http_host}" ]; then
		echo "  == http fetching file $url/$1"

                MAC=`/sbin/ifconfig eth0 |/bin/grep HWaddr | awk '{ print $5 }'`
                eval $(cat /proc/cmdline)
                SERIAL=$carduuid
                http_path=$(echo $http_path | sed "s/^\///")
                http_path=$(echo $http_path | sed "s/\/$//")
                http_path=$(echo $http_path | sed "s/{mac}/$MAC/")
                http_path=$(echo $http_path | sed "s/{serial}/$SERIAL/")
                http_path1=$(echo $http_path | sed "s/{file}/$1/")
                #echo $http_path
                #echo $http_path1
                if [ "$http_path" = "$http_path1" ] ; then
                        echo "/usr/bin/wget http://$http_host/$http_path/$1"
                        /usr/bin/wget http://$http_host/$http_path/$1
                else
                        echo "/usr/bin/wget http://$http_host/$http_path1"
                        /usr/bin/wget http://$http_host/$http_path1
                fi
                #prepared to transmit user-agent when busybox wget supports this option
                #/usr/bin/wget --user-agent '<berofix:'$Hwaddress'>' http://$http_host/$http_path/
	fi
elif [ "${prov_type}" = "tftp" ]; then
	if [ "${use_dhcp}" = "yes" ] || [ "${use_dhcp}" = "1" ]; then
		host=`${beroconf} get root dhcp-tftp-host | grep -v failed`
		path=`${beroconf} get root dhcp-tftp-path | grep -v failed`
	else
		host=`${beroconf} get root tftp-host | grep -v failed`
		path=`${beroconf} get root tftp-url | grep -v failed`
	fi

	if [ -n "${host}" ]; then
		echo "  == tftp fetching file ${path}/${1}"
        	/usr/local/bin/tftp ${host} > /dev/null <<EOF
timeout 1
get ${path}/${1}
EOF
	fi
fi
}
function check_file {
checkfile=$1
if ( ! [ -s /usr/conf/$checkfile ] ); then
    cp -f /usr/conf/backup/$checkfile /usr/conf/
    echo "missing file " $checkfile " has been replaced"
fi

}

function reload_settings {
        echo "reloading settings"
        STR=$(echo 'rd'|nc localhost 54322 -q1)
        sleep 1
        STR=$(echo 'rs'|nc localhost 54322 -q1)
}
function update_config {

	ret=1

        if [ -s conf-update.conf ]; then
                . conf-update.conf
                if ( [ "$CONF_DOWNLOAD" = "yes" ] || [ "$CONF_DOWNLOAD" = "1" ] ); then
                        #echo "  = $prov_type update: checking for files on $host:/$url"
                        mkdir -p backup
                        cp -f isgw.* backup/
                        cp -f *.conf backup/
                        rm -rf isgw.conf isgw.sip isgw.dialplan isgw.isdn isgw.gsm
                        rm -rf hardware.conf isgw.analog misc.conf filter.conf isgw.tones isgw.causes
                        sync
                        get_file hardware.conf
                        get_file isgw.conf
                        get_file isgw.dialplan
                        get_file isgw.analog
                        get_file isgw.isdn
                        get_file isgw.gsm
                        get_file isgw.sip
                        get_file isgw.causes
                        get_file isgw.tones
                        get_file misc.conf
                        get_file filter.conf
                        sync
                        sleep 1
			if ( ! [ -s hardware.conf ]  || ! [ -s isgw.conf ] || ! [ -s isgw.dialplan ] || ! [ -s isgw.sip ]); then
				rm -f /usr/conf/conf-update.conf
				sync
				echo "config_update:$prov_type:error:Download_Config_Files_Failed"
				exit 0
			fi

			check_file isgw.isdn
			check_file isgw.analog
			check_file isgw.gsm
			check_file misc.conf
			check_file isgw.causes
			check_file isgw.tones
			check_file filter.conf

			/usr/bin/env -i bash -c "/usr/local/www/berogui/misc/ini_to_db.php"
			
			if [ "$?" -eq 0 ] ; then
				sync
				echo "config_update:$prov_type:success"
			else
				echo "config_update:$prov_type:error:Check_Config_Files"
			fi
        	else
                        echo "config_update:$prov_type:failed:No_Config_Download_Selected"
			ret=0
                fi
                sync
else
        echo "config_update:$prov_type:failed:Downloading_conf-update.conf"
	ret=1
fi

rm -f /usr/conf/conf-update.conf
sync

return ${ret}
}

function upgrade_firmware {


if [ -s firmware-update.conf ] ; then
        . firmware-update.conf

	ret=1

	if [ -f "/usr/local/FILENAME" ]; then
		INST_FILE=`cat /usr/local/FILENAME`
		inst_vers=`expr match "${INST_FILE}" ".*appfs-\(.*\)\.tar\.gz"`
		prov_vers=`expr match "${FIRMWARE_FILE}" ".*appfs-\(.*\)\.tar\.gz"`

		if [ "${prov_vers}" != "" ]; then
			/usr/sbin/comp-app-vers.sh ${inst_vers} ${prov_vers}
			if [ ${?} -eq 0 ]; then
				echo "firmware_update:${prov_type}:success:Already_InstalledOrNewer_'${FIRMWARE_FILE}'"
				return 0
			fi
		fi
	fi

        if [ "$FIRMWARE_DOWNLOAD" = "yes" ] || [ "$FIRMWARE_DOWNLOAD" = "1" ] ; then
                #echo "  ** Firmware Update Request, using '$FIRMWARE_FILE'"
                #cd /mnt/images
                cd $FWIMGDIR
                rm -rf *
                get_file $FIRMWARE_FILE
                if ! [ -s $FWIMGDIR/$FIRMWARE_FILE ] ; then
                	echo "firmware_update:$prov_type:failed:Invalid_Firmware_File_'$FIRMWARE_FILE'"
			ret=1
		else
                	if [ "$FIRMWARE_INSTALL" = "yes" ] || [ "$FIRMWARE_INSTALL" = "1" ] ; then
                        	/usr/local/sbin/install.sh $FIRMWARE_FILE
                        	if [ $? != "0" ] ; then
                             		echo "firmware_update:$prov_type:error:Firmware_Archive_Integrity"
					ret=1
                        	else
                              		/usr/local/bin/beroconf set root app-image $FIRMWARE_FILE
                               		echo "firmware_update:$prov_type:success:Installed_'$FIRMWARE_FILE'"
					ret=0
                        	fi
                	else
                        	echo "firmware_update:$prov_type:failed:Install=No_Selected"
				ret=0
                	fi
		fi
        else
                echo "firmware_update:$prov_type:Download=No_Selected"
		ret=0
        fi
else
      echo "firmware_update:$prov_type:failed:Missing_File_firmware-update.conf"
      ret=1
fi

rm -f /usr/conf/firmware-update.conf
sync

return ${ret}
}

function restoreoldconfig {
     echo "Restore old Config"
     cp -f backup/isgw.* .
     cp -f backup/*.conf .
     /usr/bin/env -i bash -c "/usr/local/www/berogui/misc/ini_to_db.php"
     sync
     sleep 1
}


#first refresh config files from Database
wget -O - http://localhost/app/berogui/includes/create_files.php >> /dev/null

if [ "$type" = "config" ] ; then
	get_file conf-update.conf
	update_config

	exit ${?}
fi

if [ "$type" = "firmware" ] ; then
	get_file firmware-update.conf
	upgrade_firmware

	exit ${?}
fi

if [ "$type" = "restore" ] ; then
	if ( [ -s backup/hardware.conf ] || [ -s backup/isgw.conf ] || [ -s backup/isgw.dialplan ] || [ -s backup/isgw.sip ] ); then
		restoreoldconfig
	    echo "restoreoldconfig:success"
	else
	    echo "restoreoldconfig:failed"
	fi
fi
