#!/bin/sh
# Description: Script to be executed during a liveburner upgrade
# but before the installation of the application packages.
# It will mount the safezone and restore the files.

EMMC_DEVICE="NOT_SUPPORTED"
SAFEZONE_MOUNTPOINT="/tmp/safezone"
KEROS_CONFIGS_ARCHIVE="keros_config.tar.gz"
LOGFILE="${SAFEZONE_MOUNTPOINT}/upgrade.log"

# BSCC
BSCC_CONFFILE="var.xml"

# WMC
WMC_CONFIGS_ARCHIVE="wmc_config.tar.gz"
WMC_SYSUPGRADE_FILE="/etc/sysupgrade.d/openvpn.conf"
WMC_OPENVPN_CONFIG="/etc/openvpn/client-openvpn.conf"
WMC_FIREWALL_RULES="/etc/firewall.d/iptables_openvpn.rules"
WMC_SYSUPGRADE_FILES="${WMC_OPENVPN_CONFIG}"

# Basic Station
BS_CONFIGS_ARCHIVE="bs_config.tar.gz"

fatal_error()
{
	echo "$1"
	exit 1
}


detect_emmc()
{
	for i in $(seq 0 9); do
		if [ -b "/dev/mmcblk${i}" ]; then
			EMMC_DEVICE="mmcblk${i}"
			break
		fi
	done

	if [ "${EMMC_DEVICE}" == "NOT_SUPPORTED" ]; then
		fatal_error "Emmc device not found. Kernel version: ${KERNEL_VERSION}. Please fix."
	fi
}


klk_mount() {
	local blkpart=${1}
	local mountpoint=${2}
	local options=${3}

	[ -d ${mountpoint} ] || mkdir -p ${mountpoint}

	# Check if not yet mounted
	mount | grep -q "${blkpart}"
	if [ ${?} -eq 0 ]
	then
		# Check mountpoint
		mount | grep -q "${mountpoint}"
		if [ ${?} -eq 0 ]
		then
			# Yet mounted on right mountpoint : Nothing to do
			return 0
		else
			# unmount before remount it on right mountpoint
			umount ${blkpart}
		fi
	fi

	mount ${options} ${blkpart} ${mountpoint}

	return ${?}
}


# Mount the safezone mountpoint in ${SAFEZONE_MOUNTPOINT}
#
mount_safezone()
{
	echo "Mounting safezone"
	echo 0 > /sys/block/${EMMC_DEVICE}boot0/force_ro
	klk_mount "/dev/${EMMC_DEVICE}boot0" ${SAFEZONE_MOUNTPOINT} "-t ext2 -o rw" || echo "Mounting safezone failed"
	echo "Safezone ready to use"
}

# Restore configuration saved in safezone by preinst in
# the new filesystem.
#
restore_keros_configurations()
{
	echo "Restoring KerOS configurations from safezone..."
	if [ -f ${SAFEZONE_MOUNTPOINT}/${KEROS_CONFIGS_ARCHIVE} ]
	then
		tar -xvzf ${SAFEZONE_MOUNTPOINT}/${KEROS_CONFIGS_ARCHIVE} -C /
		echo "Restoration finished"
	else
		echo "No restoration files in safezone. Nothing done."
	fi
}


# Adapt KerOS system configuration files restored from
# previous version. In this version, only OpenVPN configuration
# is adapted to manage secrets with bscc.p12 and bscc.password instead
# of secrets in TZdata
#
adjust_keros_configurations()
{
	echo "Adjusting KerOS configurations..."

	echo "Patching /etc/openvpn/bscc.conf to use secrets in file systead instead of TZsw"
	[ -f /etc/openvpn/bscc.conf ] && sed -i 's:^pkcs12 \[\[INLINE\]\].*:pkcs12 /etc/openvpn/bscc.p12\naskpass /etc/openvpn/bscc.password:g' /etc/openvpn/bscc.conf

	echo "Patching /etc/default/lorafwd to manage lorafwd multi-instance"
	[ -f /etc/default/lorafwd ] && sed -i 's:^EXTRA_ARGS=.*:EXTRA_ARGS="-vv -p /var/run/lora/lorafwd.pid -s /var/lib/lorafwd/database.sqlite":g' /etc/default/lorafwd

	echo "Patching /etc/kgpsd.conf to manage ZDA frame"
	[ -f /etc/kgpsd.conf ] && sed -i 's:^zda=no:zda=yes:g' /etc/kgpsd.conf

	echo "Patching /etc/lorafwd.toml to manage new parameters"
	lorafwdctl gwmp.timeout 3
	lorafwdctl gwmp.report_tx_power false

	echo "Patching /etc/snmp/snmpd.conf to manage the connection to SNMP server"
	[ -f /etc/snmp/snmpd.conf ] && sed -i 's:^informsink  snmp  public 10162:informsink 172.17.0.1 public 10162:g' /etc/snmp/snmpd.conf

	echo "Adjustements finished"
}


# Some files are added to file system
#
copy_new_files_to_rootfs()
{
	echo "Extracting files to add to root FS"
	if [ -f ${SAFEZONE_MOUNTPOINT}/burner/rootfs.tar.gz ]; then
		tar -xvzf ${SAFEZONE_MOUNTPOINT}/burner/rootfs.tar.gz -C /
	fi
}


# Restore configuration saved in safezone by preinst in
# the new filesystem.
#
restore_bscc_configurations()
{
	echo "Restoring BSCC configurations from safezone..."
	if [ -f ${SAFEZONE_MOUNTPOINT}/${BSCC_CONFFILE} ]
	then
		mkdir -p /user/bscc/
		cp -f ${SAFEZONE_MOUNTPOINT}/${BSCC_CONFFILE} /user/bscc/
		echo "Restoration finished"
	else
		echo "No restoration files in safezone. Nothing done."
	fi
}

# Restore Prove&Core SecureStorage information.
restore_securestorage()
{
	echo "Restore Prove&Core SecureStorage..."
	if [ -f ${SAFEZONE_MOUNTPOINT}/pcore_data.img.gz ]; then
		gunzip -c ${SAFEZONE_MOUNTPOINT}/pcore_data.img.gz | dd of=/dev/${EMMC_DEVICE} bs=512 seek=10240
		echo "Prove&Core SecureStorage restored"
	else
		echo "No Prove&Core SecureStorage found. Nothing done."
	fi
}

# Adapt WMC configuration files for new firmware (if necessary)
#
adapt_wmc_configurations()
{
	echo "Adapting WMC configuration files..."

	# Sysupgrade
	echo "${WMC_SYSUPGRADE_FILES}" > ${WMC_SYSUPGRADE_FILE}

	# Tunneling Tools 3.0 modifications
	#

	# OpenVPN configuration
	sed -i 's/^route-up/;route-up/g' ${WMC_OPENVPN_CONFIG}

	# Firewall rules
	cat << EOF > ${WMC_FIREWALL_RULES}
#Firewall rules to accept OpenVPN traffic

*filter
-I INPUT  -m udp -p udp --sport 1194 --dport 1024:65535 -j ACCEPT
-I INPUT  -m udp -p udp --sport 30000:35000 --dport 1024:65535 -j ACCEPT
-I OUTPUT -m udp -p udp --sport 1024:65535 --dport 1194 -j ACCEPT
-I OUTPUT -m udp -p udp --sport 1024:65535 --dport 30000:35000 -j ACCEPT
COMMIT
EOF

	# forcibly set lns, snmp & ntp addresses
	awk -F "\t" '
		$2 == "lns" || $2 == "snmp" || $2 == "ntp.ran.com"	{ next }
		{ print }
		END {
			printf "172.17.0.1\tlns\n"
			printf "172.17.0.1\tsnmp\n"
			printf "172.17.0.1\tntp.ran.com\n"
		}' < /etc/hosts > /etc/hosts.new \
		&& mv -f /etc/hosts.new /etc/hosts

	echo "Done"
	
}

# Restore WMC configuration from safezone
restore_wmc_configurations()
{
	echo "Restoring WMC configurations from safezone..."
	if [ -f ${SAFEZONE_MOUNTPOINT}/${WMC_CONFIGS_ARCHIVE} ]
	then
		# Restore the configuration
		tar -xvzf ${SAFEZONE_MOUNTPOINT}/${WMC_CONFIGS_ARCHIVE} -C /

		# Adapt for KerOS 4.0
		adapt_wmc_configurations

		echo "Restoration finished"
	else
		echo "No restoration files in safezone. Nothing done."
	fi
}

# Restore Basic Station configuration from safezone
restore_basic_station()
{
  echo "Restoring Basic Station configuration from safezone..."
  if [ ! -d /user/basic_station ]; then
    echo "Warning: basic station doesn't seem to be installed, it will have to be installed manually"
    mkdir -p /user/basic_station/etc
  fi

  if [ -f ${SAFEZONE_MOUNTPOINT}/${BS_CONFIGS_ARCHIVE} ]
  then
    # Restore the configuration
    tar -xvzf ${SAFEZONE_MOUNTPOINT}/${BS_CONFIGS_ARCHIVE} -C /user/basic_station/etc/

    echo "Restoration finished"
  else
    echo "No restoration files in safezone. Nothing done."
  fi
}

####################
# MAIN KEROS PART
####################

detect_emmc
mount_safezone

echo -e "\n== Start of PREAPPS script ==\n" 2>&1 | tee -a ${LOGFILE}

# KerOS configuration
restore_keros_configurations 2>&1 | tee -a ${LOGFILE}
adjust_keros_configurations 2>&1 | tee -a ${LOGFILE}
copy_new_files_to_rootfs 2>&1 | tee -a ${LOGFILE}

# BSCC configuration
restore_bscc_configurations 2>&1 | tee -a ${LOGFILE}

# WMC configuration
restore_wmc_configurations 2>&1 | tee -a ${LOGFILE}

# Basic Station
restore_basic_station 2>&1 | tee -a ${LOGFILE}

####################
# MAIN CUSTOMER PART
####################

# Example:
# cp -fR ${SAFEZONE_MOUNTPOINT}/* /etc/

echo -e "\n== End of PREAPPS script ==\n" 2>&1 | tee -a ${LOGFILE}
sync
