#!/bin/sh
###############################################################################
#                                                                             #
#                           Update gw software                                #
#                                                                             #
###############################################################################

. /usr/local/bin/telem/functions
. /usr/local/bin/gwconf-files/gwconf-common

###############################################################################
#                                                                             #
#                         Gateway6 files and folders                          #
#                                                                             #
###############################################################################

SDD=/mnt/sd
ETC_TELEM=/usr/local/etc/telem
STATS_DIR=/var/local/telem/stats
I2C_PROBLEM_FILE=/var/local/telem/errors/i2c-bus
GWS_GROUP=gws

###############################################################################
#                                                                             #
#                             Script functions                                #
#                                                                             #
###############################################################################

die () {
	logg "${1}"
	exit 1
}

log_rm() {
	rm "${1}" \
	&& logg "Removing '${1}'"
}

LocateUpdate()
{
	# update from SD?
	if [ -f '/mnt/sd/setup.new.tar.xz' ]; then
		cp '/mnt/sd/setup.new.tar.xz' "${new_setup_file}"
		return 0
	fi

	if [ -f "${new_setup_file}" ]; then
		# no need to copy
		return 0
	fi

	# Configuration from SD card
	if [ -f "${current_sdd_config}" ]; then
		if ! diff -q "${current_sdd_config}" "${current_setup_file}"; then
			logg "Config on SD card is different from current, reconfiguring"
			cp "${current_sdd_config}" "${new_setup_file}"
			return 0
		fi
	fi

	if doClearSetup; then
		newClearSetup && return 0
	fi

	return 1
}

doClearSetup() {
	if [ ! -e "${current_setup_file}" ] && [ ! -e "${new_setup_file}" ]; then
		logg "Current setup file not found"
		return 0
	fi

	test -e "${I2C_PROBLEM_FILE}" && rm "${clear_setup_on_boot_file}"

	test -e "${clear_setup_on_boot_file}" && {
		logg "Found 'clear_setup_on_boot_file'"
		return 0
	}

	test ! -e /etc/shadow && {
		logg "/etc/shadow not found"
		return 0
	}

	# no clear setup
	return 1
}

newClearSetup() {
	logg "Starting clear setup procedure"

	! rm "${clear_setup_on_boot_file}" 2>/dev/null

	if [ -f "${DEFAULT_USER_SETUP_FILE}" ]; then
		cp "${DEFAULT_USER_SETUP_FILE}" "${new_setup_file}"
		return
	fi
	if [ -f "${DEFAULT_SETUP_FILE}" ]; then
		cp "${DEFAULT_SETUP_FILE}" "${new_setup_file}"
		return
	fi

	return 1
}

prepareClearSetup() {
	default_setup_dir=
	if isSystemDefault "${new_setup_file}"; then
		default_setup_dir="${DEFAULT_SETUP_FILE%/*}"
		logg "Using system's default setup."
	fi
	if isUserDefault "${new_setup_file}"; then
		default_setup_dir="${DEFAULT_USER_SETUP_FILE%/*}"
		logg "Using user's default setup."
	fi
}

updatePermissions()
{
	chmod +x '/usr/local/bin/telem/check_permissions' "$1"
	/usr/local/bin/telem/check_permissions "$1"
}

cleanup() {
	! rm    /usr/local/etc/telem/config.xml
	! rm    /usr/local/etc/telem/setup.xml
	# Remove old stuff that might not be sent from gws.exe
	! rm    /etc/openvpn/client*.conf
	! rm -r /etc/openvpn/tun*
	! rm    /etc/ppp/peers/sim1*
	! rm    /etc/ppp/peers/sim2*
	! rm    /etc/ppp/peers/VMX53/*
	! rm -r /etc/ssl/certs/*_web_server_cert.pem
	! rm -r /etc/ssl/private/*_web_server_key.pem
	! rm -r /var/www-*
	! rm    /usr/local/etc/telem/gwSetup.bin
	! rm    /etc/ppp/chap-secrets
	! rm    /etc/ppp/pap-secrets
	! rm -r /etc/l2tp
	! rm    /etc/ppp/l2tp-ip-up
	! rm    /etc/ppp/l2tp-ip-down
	
	# IPsec racoon
	! rm    /etc/ipsec-tool.conf
	! rm    /etc/racoon/psk.txt
	! rm    /etc/racoon/racoon.conf
	! rm    /etc/racoon/ipsec-ip-up
	! rm    /etc/racoon/ipsec-ip-down
	
	# IPsec strongSwan
	if [ ! -x "/etc/init.d/S83strongswan" ]; then
		! rm /etc/ipsec.conf
		! rm /etc/ipsec.secrets
		! rm /etc/swanctl/swanctl.conf
	fi
	
	! rm -r /etc/ptp4l.d/*
	! rm    /etc/linuxptp.cfg
	
	! rm    /etc/gwpinger.conf
	! rm    /etc/ppp/serial*.conf
	! rm    /etc/default/comtraded
	! rm    /etc/comtrade.conf
	! rm    /etc/comtradessh.conf
	! rm    /etc/comtrade_id
	! rm    /etc/watchdog.conf
	
	! rm    /etc/terminals/*
	
	! rm    /var/local/telem/gps_is_enabled
	! rm    /var/local/telem/ntp_is_enabled
	
	! rm -f /usr/local/etc/telem/hw-run.xml 2> /dev/null
	
	# GW6
	! rm -f /etc/network/interfaces
	! rm -f /etc/init.d/S40network-interfaces

	# pinger
	! rm -rf /etc/pinger/

	! rm -f  /etc/crontab

	# opc-ua
	! rm     /etc/protocol/opc-ua/https-client/*.crt
	! rm     /etc/protocol/opc-ua/https-client/*.key

	echo "nameserver 127.0.0.1" > '/etc/resolv.conf'
	cp -v '/etc/default/setup/log-conf.xml' '/usr/local/etc/telem/log-conf.xml'
	cp -v '/etc/default/setup/ppp-options' '/etc/ppp/options'
}

rotate() {
	logg "Rotating."
	# rename previous setup files
	fileRotate "${current_setup_file}" 3

	mv "${new_setup_file}" "${current_setup_file}"
	chown root "${current_setup_file}"

	# Update configurations on SD card
	if [ -d "$SDDConfig" ]; then
		if ! diff -q "${current_sdd_config}" "${current_setup_file}"; then
			fileRotate "${current_sdd_config}" 8
			cp "${current_setup_file}" "${current_sdd_config}"
		fi
	fi
}

updateFiles() {
	# $1: directory with extracted content
	local TMP_SETUP="${1}"

	cp -r "${TMP_SETUP}/etc" /
	cp -r "${TMP_SETUP}/var" /
	cp -r "${TMP_SETUP}/usr/local" /usr/

	local ssh_auth='/home/martem/.ssh/authorized_keys'
	if [ -e "${TMP_SETUP}${ssh_auth}" ]; then
		mkdir -p /home/martem/.ssh
		cp "${TMP_SETUP}${ssh_auth}" "${ssh_auth}"
		chown martem:martem "${ssh_auth}"
		chmod 600 "${ssh_auth}"
	fi
	
	if test "${default_setup_dir}"; then
		cp -f "${default_setup_dir}/passwd"   '/etc/'
		cp -f "${default_setup_dir}/shadow"   '/etc/'
		cp -f "${default_setup_dir}/profile"  '/etc/'
		cp -f "${default_setup_dir}/group"    '/etc/'
	fi

	# move ssh config to new location
	mv '/etc/ssh_config'  '/etc/ssh/ssh_config'  &>/dev/null
	mv '/etc/sshd_config' '/etc/ssh/sshd_config' &>/dev/null
}

applyConf() {
	local do_rotate=true
	if diff -q "${new_setup_file}" "${current_setup_file}"; then
		logg "New setup file is same as currently used (reload)."
		do_rotate=false
	fi

	! rm -r /tmp/S11-setup* 2>/dev/null
	local TMP_SETUP="$(mktemp -d -t S11-setup.XXXXXX)"
	extractAndTest "${new_setup_file}" "${TMP_SETUP}" \
	|| { log_rm "${new_setup_file}"; rm -r "${TMP_SETUP}"; die "extractAndTest failed"; }

	sha512sum "${new_setup_file}" | awk '{ print $1}' > '/usr/local/etc/telem/setup.sha512'

	updatePermissions "${TMP_SETUP}" &>/dev/null

	cleanup

	updateFiles "${TMP_SETUP}"

	$do_rotate && rotate

	rm -r "${new_setup_file}" "${TMP_SETUP}"

	updatePermissions /

	sync

	Reboot
}

reboot_before_setup() {
	touch "${STATS_DIR}/reboot-before-setup"
	reboot
	exit 0
}

###############################################################################
#                                                                             #
#                                The Script                                   #
#                                                                             #
###############################################################################

start() {
	logg "Starting telem-config extractor"

	# mount SD card if connected
	mountSDp1

	# legacy reload, used only by S99
	# TODO remove
	if [[ -e "${reload_setup_on_boot_file}" ]]; then
		cp "${current_setup_file}" "${new_setup_file}"
		rm -f "${reload_setup_on_boot_file}"
	fi

	# locate folder with new setup
	if LocateUpdate; then
		logg "New setup: ${new_setup_file}"
		test -x /usr/local/bin/telem/parse_ordercode.sh && /usr/local/bin/telem/parse_ordercode.sh
		prepareClearSetup
		applyConf
		rm "${new_setup_file}" 2>/dev/null
	fi
}

apply_new() {
	if LocateUpdate; then
		if isDefaultSetup "${new_setup_file}"; then
			logg "Rebooting before clearing setup"
		else
			logg "Rebooting before taking new setup"
		fi
		reboot_before_setup
	fi
}

stop() {
	return 0
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	apply-new)
		# for S81telem
		apply_new
		;;
	old)
		old_file="${current_setup_file}.${2}"
		test -f "${old_file}" && logg "Old '${old_file##*/}' setup exists..."
		cp -vf  "${old_file}" "${new_setup_file}"
		apply_new
		;;
	list-old)
		/usr/local/bin/gwconf-files/gwconf-list --old
		;;
	*)
		echo "Usage: $0 {start|stop}"
		exit 1
		;;
esac

exit $?
