#!/bin/bash

HWTOOL=/opt/phion/bin/hwtool
BOXINFO=/opt/phion/bin/boxinfo

VIRTTYPE=$(${HWTOOL} -x)

MNTOLDROOT=
CONFIGROOT=$MNTOLDROOT/opt/phion/config/configroot/
CONFIGACTIVE=$MNTOLDROOT/opt/phion/config/active/
MERGECONF=/etc/phion/bin/mergeconf

BOXNETCONFACTIVE=${CONFIGACTIVE}boxnet.conf
BOXNETCONFROOT=${CONFIGROOT}boxnet.conf
BOXNETCONFSTRIPPED=${CONFIGACTIVE}boxnet.conf.stripped
BOXNETCONFTMP=${CONFIGACTIVE}boxnet.conf.tmp
BOXNETCONFMERGED=${CONFIGACTIVE}boxnet.conf.merged
BOXCONF=${CONFIGACTIVE}box.conf
BOXCONFROOTOUT=/etc/phion/bin/boxconf_rollout.net
DEVNAME=

IPREGEX='^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'

APMOD=$($HWTOOL -m)

source /etc/phion/functions

function createDefaultBoxnetConf(){
	cat > $BOXNETCONFTMP <<- EOF
		AADSL = n
		ADHCP = n
		AUMTS = n
		CHECKLESS = 0
		HOSTNAME = $Hostname
	EOF

	if [ -n ${Default_Gateway} ]; then
		cat >> $BOXNETCONFTMP <<- EOF
		[addroute_boxdev]
		DEST = ${Default_Gateway}
		FOREIGN = y
		Name = boxdev
		TARGET = 0.0.0.0/32
		Type = gw

		EOF
	else
		echo "No Default Route specified!"
	fi


	cat >> $BOXNETCONFTMP <<- EOF
		[boxnet]
		DEV = $DEVNAME
		IP = ${Management_IP}
		MASK = ${MASK}
		NTPD = y
		PING = y
		REALM = 1

	EOF

	cat >> $BOXNETCONFTMP <<- EOF
		[saccess]
		SAUTH = n
		SLIP =
		SRIP = 192.168.255.254

		[vpnc]
		VPNOPMODE = VPN2

		[zdev_eth0]
		NAME = eth0
	EOF

}

function errecho(){
	echo $1 >&2
}

function trim(){
	echo $1;
}


function splitIPMask(){
	if [ ${Management_IP##*/} != ${Management_IP} ]; then
		export MASK=${Management_IP##*/}
		export Management_IP="${Management_IP%%/*}"
	elif [ -n $Netmask ]; then
		bit=$(quad2int $Netmask)
#		export MASK=$((32 - $bit))
		export MASK="$bit"
	else
		export MASK="8"
	fi

}

case "$1" in
precheck)
	if [ ! -d $MNTOLDROOT/opt/phion/config/ ]; then
		errecho "Config directory could not be found in the expected Location."
		exit -1;
	else
		exit 0;
	fi
	;;
*)
	if [ -n "$(trim ${Management_IP})" ] && [ -n "$(trim ${Hostname})" ] && [ -n "$(trim ${Default_Gateway})" ]; then
		splitIPMask

		if [ -z "$(echo ${Management_IP} | grep -E $IPREGEX)" ]; then
			errecho "${Management_IP} is not a valid IP-Address"
			exit -1
		fi
		if [ -z "$(echo ${Default_Gateway} | grep -E $IPREGEX)" ]; then
			errecho "${Default_Gateway} is not a valid IP-Address for a Default Route"
			exit -1
		fi

		echo -n "Retrieving device Name from previous Configuration..."
		DEVNAME=$($BOXINFO config /opt/phion/config/active/boxnet.conf boxnet dev)
		if [ $? -ne 0  ]; then
			errecho "Problems retrieving device name from old configfile"
			exit -1;
		else
			echo "OK"
		fi
		
		echo -n "Removing old configuration..."
		rm -rf ${BOXNETCONFTMP} 
		if [ $? -ne 0 ]; then
			errecho "An error occurred while deleting configuration files"
			exit -1;
		else
			echo "OK"
		fi
		
		echo -n "Creating minimal default config..."
		createDefaultBoxnetConf
		echo "OK"
		echo -n "Merging configuration..."
		# We don't want to duplicate the card configuration
		if [[ -z $(grep cards_ ${BOXNETCONFTMP}) ]]; then
			${MERGECONF} ${BOXNETCONFACTIVE} ${BOXNETCONFTMP} ${BOXNETCONFMERGED}
		else
			${MERGECONF} ${BOXNETCONFACTIVE} ${BOXNETCONFSTRIPPED} -c cards
			if [ $? -eq 0 ]; then
				${MERGECONF} ${BOXNETCONFSTRIPPED} ${BOXNETCONFTMP} ${BOXNETCONFMERGED}
			fi
		fi
		if [ $? -eq 0 ]; then
			mv ${BOXNETCONFMERGED} ${BOXNETCONFACTIVE}
			cp ${BOXNETCONFACTIVE} ${BOXNETCONFROOT}
			rm -f ${BOXNETCONFSTRIPPED} ${BOXNETCONFTMP}
			echo "OK"
		else
			errecho "Error: Merging configuration files has failed"
			exit -1
		fi


		/opt/phion/modules/box/boxnet/bin/activate ${CONFIGACTIVE}boxnet.conf 2>/dev/null
		if [ $? -eq 0 ]; then
			rm /opt/phion/preserve/artmenu-start
			echo "OK"

			BOXTMPNAME=box.conf.$$
			${BOXCONFROOTOUT} ${BOXCONF} ${BOXTMPNAME}
			source ${BOXTMPNAME}
			if [ "${box_ISMANAGEDBYWEBUI}" == "y" ]; then
			        now=$(date +"%Y-%m-%d %H:%M:%S")
			        query="INSERT INTO config (variable, value, scope, changed) VALUES "
			        query+="('system_netmask','${Netmask}','global','$now'),"
			        query+="('system_ip','${Management_IP}','global','$now'),"
			        query+="('system_gateway','${Default_Gateway}','global','$now'),"
			        query+="('system_default_hostname','${Hostname}','global','$now'),"
			        query+="('routing_static_rte_gateway','${Default_Gateway}','global','$now'),"
			        query+="('routing_static_rte_disable','no','global','$now'),"
			        query+="('routing_static_rte_preference','1','global','$now'),"
			        query+="('routing_static_rte_class','Unclassified','global','$now'),"
			        query+="('routing_static_rte_target_net','0.0.0.0/0','global','$now'),"
			        query+="('routing_static_rte_mtu','1500','global','$now')"
			        query+=" ON DUPLICATE KEY UPDATE value=VALUES(value), changed='$now';"
			        printf "Waiting for webui initialization to be done ."
			        i=600
			        while [  $((i--)) -gt 0 -a  \( -f /home/bfw/code/firmware/webui-install-init.pending -o -f /home/bfw/code/firmware/webui-update-init.pending \) ]; do
			                printf '.'
			                sleep 1
			        done
			        printf '[OK]\n'
			        if [ -f /home/bfw/code/firmware/webui-install-init.pending -o -f /home/bfw/code/firmware/webui-update.init.pending ]; then
			            echo "Webui not initialized"
			        else
			            echo "Update db"
			            echo "Please stand by ..."
			            /usr/bin/mysql -D config -e "$query"
			            source /etc/profile.d/webuiprofile.sh
			            /home/product/code/firmware/current/bin/config_read % > /opt/phion/preserve/cudadb.dump 2> /dev/null && /bin/cp -f /opt/phion/preserve/cudadb.dump /opt/phion/preserve/cudadb.last
			            /opt/phion/bin/webuicmd rewritenginxconf
            			/bin/systemctl restart nginx
			        fi
			fi
			rm -f ${BOXTMPNAME}
		fi
	else
		if [ -z "$(trim ${Management_IP})" ]; then
			errecho "Error: Mandatory Field Management IP is missing."
		fi
		if [ -z "$(trim ${Hostname})" ]; then
			errecho "Error: Mandatory Field Hostname is missing."
		fi
		if [ -z "$(trim ${Default_Gateway})" ]; then
			errecho "Error: Mandatory Field Default Gateway is missing."
		fi
		exit -1
	fi
	;;

esac

exit 0;




