#!/bin/bash

/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation [START]"

startService()
{
        echo starting $1
	if [ "`systemctl is-active $1`" != "active" ]
        then
	        systemctl enable $1
                systemctl start $1
        fi
	echo ok
}


# start atd
startService "atd"
## directory structure
[ ! -L /mail ] && {
	mkdir -p /phion0/mail
	ln -sf /phion0/mail /mail
}

[ ! -d /var/run/mariadb ] && {
	mkdir -p /var/run/mariadb
	chown mysql:mysql /var/run/mariadb
}   
[ ! -d /mail/mariadb ] && {
	mkdir -p /mail/mariadb
	chown mysql:mysql /mail/mariadb
}

[ ! -L /var/lib/mariadb ] && {
	rm -rf /var/lib/mariadb
	ln -sf /var/run/mariadb /var/lib/mariadb
}

[ ! -d /mail/transactions ] && {
	mkdir -p /mail/transactions
}

[ ! -d /mail/tmp ] && {
	mkdir -p /mail/tmp
	chmod 0777 /mail/tmp
}

[ ! -d /mail/tmp/fastcgi_tmp ] && {
	mkdir -p /mail/tmp/fastcgi_tmp
	chown nobody:root /mail/tmp/fastcgi_tmp
}

[ ! -d /mail/tmp/tmpcharts ] && {
	mkdir -p /mail/tmp/tmpcharts
	chmod 0777 /mail/tmp/tmpcharts
}

[ ! -d /home/product/code/config/certificates ] && {
    mkdir -p /home/product/code/config/certificates
}

for dir in err in out pid; do 
	[ ! -d /var/run/jobs/$dir ] && {
		mkdir -p /var/run/jobs/$dir
		chown nobody:nogroup /var/run/jobs/$dir
	}
done

[ ! -d /home/product/code/firmware/current/web/certificates ] && {
    mkdir -p /home/product/code/firmware/current/web/certificates
}

## required links
[ ! -L /etc/cudamodel ] && ln -sf /etc/barracuda/model /etc/cudamodel
#[ ! -L /usr/local/lib/perl5 ] && ln -s /usr/lib/perl5 /usr/local/lib/perl5

## required system adaptations
#install -o root -g root -m 755 /home/product/code/firmware/current/create/perl.5.20.1.tgz /perl.5.20.1.tgz
install -o root -g root -m 644 /home/product/code/firmware/current/create/etc/my.cnf /etc/my.cnf
systemctl restart mariadb
install -o root -g root -m 755 /home/product/code/firmware/current/create/home/product/code/config/dhparams.pem /home/product/code/config/dhparams.pem
install -o root -g root -m 755 /home/product/code/firmware/current/create/home/product/code/config/ssl_initial_cert.pem /home/product/code/config/ssl_initial_cert.pem


## perl hack
FWROOT=/home/product/code/firmware/current
#(tar xzf /perl.5.20.1.tgz -C / && rm /perl.5.20.1.tgz && rm /home/product/code/firmware/current/create/perl.5.20.1.tgz)
#(tar xzf /perl.5.20.1.tgz -C / && rm /perl.5.20.1.tgz)
(unset PERL5LIB 2>&1)
export PERL5LIB=/home/bfw/code/webui-perl/lib/5.20.1:$PERL5LIB
export PERL5LIB=/home/bfw/code/webui-perl/lib/5.20.1/x86_64-linux-5.20.0-64int-ld:$PERL5LIB
export PERL5LIB=/home/bfw/code/webui-perl/lib/site_perl:$PERL5LIB
export PERL5LIB=/home/bfw/code/firmware/current/lib/perl5:$PERL5LIB
export LD_LIBRARY_PATH=/home/bfw/code/firmware/current/lib:$LD_LIBRARY_PATH

cp /home/product/code/firmware/current/etc/templates/* /home/product/code/config/

echo "Mounting tmpfs for transactions on '/phion0/mail/transactions'"
mkdir -p /phion0/mail/transactions
if [ $(mountpoint /phion0/mail/transactions -q ; echo $?) -eq 1 ]; then mount -t tmpfs -o defaults,size=200M tmpfs /phion0/mail/transactions/; fi

# ------------------------------------------------------------------------------------------
PRODUCT="bfw"
LOGFILE="box_System_phionrc"

if [ -f /etc/phion/functions ]; then
	source /etc/phion/functions
		logerror="LogError ${LOGFILE}"
	else
		logerror=echo
fi

fakeCuda()
{
	[ ! -d /art/barracuda ] && mkdir -p /art/barracuda
	[ ! -L /etc/barracuda ] && ln -sf /art/barracuda /etc/barracuda
	[ ! -f /etc/barracuda/serial ] && (
		SERIAL=$(/opt/phion/bin/hwtool -s)
		if [ x"$SERIAL" = x"none" ]; then
			echo "no serial available" #echo "6996" > /etc/barracuda/serial
		else
			echo $SERIAL > /etc/barracuda/serial
		fi
	)
	[ ! -f /etc/barracuda/product ] && echo ${PRODUCT} > /etc/barracuda/product
	# [ ! -f /etc/barracuda/product ] && echo ${PRODUCT} > /etc/barracuda/product
	echo ${PRODUCT} > /etc/barracuda/product
	echo ${PRODUCT} > /etc/barracuda/mode
        MODEL=$(/opt/phion/bin/hwtool -m | tr 'a-z' 'A-Z')
        [ ! -f /etc/barracuda/model ] && (
                if [ x"$MODEL" = x"VM" ]; then echo "VF1000" > /etc/barracuda/model
                else echo "$MODEL" > /etc/barracuda/model
                fi
        )
	[ ! -f /etc/barracuda/activated ] && touch /etc/barracuda/activated
	[ ! -f /etc/barracuda/platform ] && echo -n "2"> /etc/barracuda/platform
}

readConfig()
{
	BOXSERIAL=$(cat /etc/barracuda/serial)
	MODEL=$(cat /etc/barracuda/model)
	$logerror "Info" "${0}[$$]: Detected appliance ${MODEL} with serial ${BOXSERIAL}"
}

createMachineFile()
{
	MACHINEFILE="/root/machine${BOXSERIAL}"
	echo "serial_number ${BOXSERIAL}" >> $MACHINEFILE
	echo -n "mac_address " >> $MACHINEFILE
	SYSTEMDEV=$(grep -A2 boxnet\] /opt/phion/config/active/boxnet.conf | grep '^DEV *= *' | awk '{ print $3}')
	test -n "$SYSTEMDEV" || SYSTEMDEV="p1"  # default if no management DEV set
	ip link show $SYSTEMDEV | tail -1 | awk '{print $2}' >> $MACHINEFILE
	echo "model $MODEL" >> $MACHINEFILE
	echo "rev v" >> $MACHINEFILE
	echo -n "build_date " >> $MACHINEFILE
	date >> $MACHINEFILE
}

autoConfigInterfaces()
{
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - Automatically configure interfaces"
	ifaceCount=$(ls -l /sys/class/net/*/device/driver | wc -l) # detect hardware interface count (which do have a driver)
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - interfaces found: $ifaceCount"
	sectionName=$(grep "cards_" /opt/phion/config/configroot/boxnet.conf | sed 's/[][]//g') # detect 1st card section name
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - section found: $sectionName"
	/opt/phion/bin/editconf --file boxnet.conf --section "$sectionName" --put NUM --value $ifaceCount -S
	if [ $? -eq 0 ]; then
		/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - changing interfaces in boxnet successful"
	else
		/etc/phion/bin/phionlog_api box_System_webui Error "commitNGInstallation - Error while changing interfaces in boxnet"
	fi
	/opt/phion/bin/webuicmd activateboxnet
	if [ $? -eq 0 ]; then
		/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - Boxnet activation successful"
	else
		/etc/phion/bin/phionlog_api box_System_webui Error "commitNGInstallation - Error while activating boxnet"
	fi
}

applyNGRevConfig()
{
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig [START]"
	
	# will be moved to boxnet because of BNNGF-54589 
	#if [ $(/opt/phion/bin/hwtool -m) == "VM" ]; then
	#	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - this is a virtual machine"
	#	autoConfigInterfaces
	#else
	#	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - this is NOT a virtual machine"
	#fi
	
	$logerror "Info" "${0}[$$]: Applied initial configuration"
	if [ ! -f /opt/phion/preserve/cuda.vars ]; then
		/opt/phion/bin/writeCudaVars.pl
	fi
	
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - reverse mapping [START]"
	/opt/phion/bin/webuicmd db2conf revsql 2>/root/revmapping.out|/usr/bin/mysql -t config
	/etc/phion/bin/phionlog_api box_System_webui Info -f < /root/revmapping.out
	rm -f /root/revmapping.out
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - reverse mapping [END]"
	
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - rawdump [START]"
	/opt/phion/bin/webuicmd db2conf rawdump /opt/phion/preserve/cuda.vars - > /opt/phion/preserve/cudadb.last
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - rawdump [END]"
	
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - deltaactivate [START]"
	/opt/phion/bin/webuicmd db2conf deltaactivate - /opt/phion/preserve/cuda.vars - > /root/fwdmapping.out
	/etc/phion/bin/phionlog_api box_System_webui Info -f < /root/fwdmapping.out
	rm -f /root/fwdmapping.out
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig - deltaactivate [END]"
	
	rm -f /opt/phion/preserve/boxnet.conf
	
	# create new ui cert
	#/home/product/code/firmware/current/create/etc/cron.weekly/certreplace.pl --force --noinstall
	/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation - applyNGRevConfig [END]"
}

createServices()
{
	/opt/phion/bin/webuicmd createngservices
}

setServiceDefaults()
{
	/opt/phion/bin/webuicmd setngservicedefaults
}

create_db_and_table()
{
	/opt/phion/bin/create_database.sh
}

#XXX: attention! if changed here, change also in cmd_ng.cc/db_keys_to_backup[]
set_db_defaults()
{
        cmds=""
        # ------------------------------
	cmds+="REPLACE INTO config VALUES ('branding_device_name','CloudGen Firewall','global','','System Name',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('system_default_hostname','BarracudaFirewall','global','','System Hostname',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('fw_settings_enable_urlcat','no','global','','Enable URLCAT per default on new boxes',NULL,20140220101010);"
	cmds+="REPLACE INTO config VALUES ('backup_config','1','global','','Backup global config',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('backup_consolidate','1','global','','Format of backup files',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('backup_life','5','global','','Number of backups to keep on the remote server',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('backup_port','21','global','','Default Backup Server Connection Port',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('backup_type','off','global','','Type of server to backup to',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('https_allow_ssl2','Yes','global','','Allow The SSL Protocol v2 To Be Used In HTTPS',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('https_links','No','global','','Use HTTPS Links In Quarantine Notifications',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('https_only','No','global','','Use HTTPS Only Flag',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('https_port','443','global','','HTTPS Web Interface Port',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('http_port','80','global','','HTTP Interface Port',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('http_session_length','20','global','','HTTP Interface Session Length',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('http_shutoff','No','global','','Turns off HTTP access',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('support_tunnel_timeout','432000','global','','Support tunnel timeout in seconds',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('system_ntp_server','update01.barracudanetworks.com','global','','System NTP Server',NULL,20111206101010);"
	#cmds+="INSERT INTO config VALUES ('system_password','admin','global','',NULL,NULL,20111206101010);" # see BNNGF-44108
	cmds+="REPLACE INTO config VALUES ('system_ssh_enable','Yes','global','',NULL,NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('system_timezone','America/Los_Angeles','global','','System Timezone',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('migration_tasks_done','rename_sip_switch','global','','Migration steps that have benn completed and must not be repeated',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('system_ssl_protocols','TLSv1.1 TLSv1.2','global','','Poodle Mitigation values for nginx conf',NULL,20111206101010);"
	cmds+="REPLACE INTO config VALUES ('system_ssl_ciphers','HIGH:!aECDH:!ADH:!3DES:!MD5:!DSS:!RC4:!EXP:!eNULL:!NULL:!aNULL','global','','Default values for ciphers',NULL,20111206101010);"
        # ------------------------------
	echo $cmds | mysql config
}

restore_db_defaults()
{
        NUM=$(/opt/phion/bin/webuicmd db shownum dbdefaults /opt/phion/config/configroot/webui.conf)
        i=0

	if [ "$NUM" != '' ]; then
                return
	fi
        while [ $i -lt $NUM ]; do
                RET=$(/opt/phion/bin/webuicmd db showentry dbdefaults /opt/phion/config/configroot/webui.conf $i)
                IFS=':' read -r -a data <<< "$RET"
                /opt/phion/bin/webuidb insert "${data[0]}" "${data[1]}"
                let i=$i+1
        done
}

restore_db_frontendonly()
{
        NUM=$(/opt/phion/bin/webuicmd db shownum dbfrontendonly /opt/phion/config/configroot/webui.conf)
        i=0

	if [ "$NUM" != '' ]; then
                return
	fi

	while [ $i -lt $NUM ]; do
                RET=$(/opt/phion/bin/webuicmd db showentry dbfrontendonly /opt/phion/config/configroot/webui.conf $i)
                IFS=':' read -r -a data <<< "$RET"
                /opt/phion/bin/webuidb insert "${data[0]}" "${data[1]}"
                let i=$i+1
        done
}

create_webui_node()
{
	# create hidden webui config node
	touch /opt/phion/config/configroot/webui.conf
	echo -e "read: -1\nwrite: -1\nevent: 0\ncreated: \nmodified: 2017-01-30   17:32:39   root   10.27.33.10" > /opt/phion/config/configroot/webui.param
	echo -e "Type: BOX_CONF\nLabel: WebUI Data\nState: \nAttr: readonly hide \nInst: webui.conf\nLink: \nModule: box/box\nSpecific: conf2\nFamily: \nRelease: 7.1\nBackRelease: \nPlatform: \nDesc: WebUI Data" > /opt/phion/config/configroot/webui.desc
}

applySnapshot()
{
	systemctl status mariadb
	
	if [ $? -ne 0 ]; then
      	    	systemctl start mariadb
		sleep 3
	    
	fi

	# insert defaults into database
	create_db_and_table
	if [ $? -eq 0 ]; then # created db/table -> 1st install
		set_db_defaults
	else # did not create db/table -> backup/restore
		restore_db_defaults
		restore_db_frontendonly
		/opt/phion/bin/webuicmd backup restorecerts
	fi

	# insert management ip into database
	SYSTEMIP=$(grep '^IP *= *' /opt/phion/config/active/boxnet.conf | awk '{ print $3}')
	test -n "$SYSTEMIP" || SYSTEMIP="192.168.200.200"  # default if no management IP set
	echo "DELETE FROM config WHERE variable LIKE 'system_ip';" | mysql -t config
	echo "REPLACE INTO config( variable, value, scope, comment) \
	VALUES('system_ip', '$SYSTEMIP', 'global', ''); \
	" | mysql -t config

	$logerror "Info" "${0}[$$]: Applied snapshot"

	# start reversemapping
	applyNGRevConfig
}

processBoxnet()
{
	/bin/mkdir /tmp/commitNGInstallation.$$/
	TMPBOXNET=/tmp/commitNGInstallation.$$/boxnet.conf.$$
	source /opt/phion/modules/box/boxnet/bin/boxnet_process
	do_process /opt/phion/config/configroot/boxnet.conf ${TMPBOXNET} LOCAL WEBUI $$
	/bin/mv -f ${TMPBOXNET} /opt/phion/config/configroot/boxnet.conf
	/bin/rm -rf /tmp/commitNGInstallation.$$/

	cp /opt/phion/config/configroot/boxnet.conf /opt/phion/preserve/
	/opt/phion/bin/webuicmd activateboxnet

	$logerror "Info" "${0}[$$]: Adapted boxnet for initial startup"
}

fakeCuda
readConfig
createServices
setServiceDefaults
applySnapshot
createMachineFile
processBoxnet

rm -f /opt/phion/preserve/block.ctrl
ln -sf /opt/phion/libs/libcrypto.so.1.0.0 /home/product/code/firmware/current/lib
ln -sf /opt/phion/libs/libssl.so.1.0.0 /home/product/code/firmware/current/lib

FWROOT=/home/product/code/firmware/current
(/home/product/code/firmware/current/bin/migration.pl --task certman_box --mark)
#(/home/product/code/firmware/current/bin/webdebug)
(cat /opt/phion/modules/server/firewall/fwappid/pngs.pack | base64 --decode > /home/product/code/firmware/current/web/images/bfw/pngs.pack.png)
(cp -pf /opt/phion/modules/server/firewall/fwappid/pngidreference /home/product/code/firmware/current/web/images/bfw/pngidreference)

# just in case debug is enable -> disable it here
rm -f /tmp/web.debug
/opt/phion/bin/webuicmd lock destroy webuicmd/debug

# ensure that all template files in code/config/* are updated with the correct values from db
/home/product/code/firmware/current/bin/write_config_from_templates.pl

# postinstall destroys the nginx config. must be rewritten
/opt/phion/bin/webuicmd rewritenginxconf


## nginx, mysql and nginx should start automatically.

# create new ui cert
/home/product/code/firmware/current/create/etc/cron.weekly/certreplace.pl --force --noinstall

/etc/phion/bin/phionlog_api box_System_webui Info "commitNGInstallation [END]"

