#!/bin/sh
. /etc/profile

# Set variables
FW_VERSION_A=/tmp/extparam/system_A_firmware_version
FW_VERSION_B=/tmp/extparam/system_B_firmware_version
GDS=/opt/gira/bin/devicestack
DEVCFG=/opt/gira/bin/devcfg
BREAKING_CHANGE_VERSION=/opt/gira/etc/breakingchangeversion
KNX_DL_PATH=/opt/userdata/knxdevice

delete_knx_download() {
	echo "Creating backup for version ${1}.${2} download."
	oldfile=$(ls ${KNX_DL_PATH}/device*.xml)
	# delete possible old backups
	rm -f ${KNX_DL_PATH}/device*.xml.*.*
	mv ${oldfile} ${oldfile}.${1}.${2}
	echo "Deleted old KNX download, because we have a breaking change in the versions."
}

case "$1" in
  start)
    # create a valid extparam structure:
	$(mkdir -p /tmp/extparam ; cd /tmp/extparam ; ${DEVCFG} --write-to-files)
	# check if a backup is present for the running version
	CURRENT_MAJOR=$(${GDS} -cfv | cut -d . -f 1)
	CURRENT_MINOR=$(${GDS} -cfv | cut -d . -f 2)
	if [ -f ${KNX_DL_PATH}/device*.xml.${CURRENT_MAJOR}.${CURRENT_MINOR} ]; then
		echo "Detected an KNX download backup for my version ${CURRENT_MAJOR}.${CURRENT_MINOR} - restoring this backup."
		backup=$(ls ${KNX_DL_PATH}/device*.xml.${CURRENT_MAJOR}.${CURRENT_MINOR})
		original=${backup%.${CURRENT_MAJOR}.${CURRENT_MINOR}}
		rm -f ${KNX_DL_PATH}/device*.xml
		mv ${backup} ${original}
	fi
	# check if the present KNX download is incompatible.
	if [ -f ${KNX_DL_PATH}/device*.xml ]; then
		BOOTED_SYSTEM=$(${GDS} --booted-system)
		if [ "${BOOTED_SYSTEM}" == "A" ]; then
			OLD_VERSION_MAJOR=$(cat ${FW_VERSION_B} | cut -d . -f 1)
			OLD_VERSION_MINOR=$(cat ${FW_VERSION_B} | cut -d . -f 2)
		elif [ "${BOOTED_SYSTEM}" == "B" ]; then
			OLD_VERSION_MAJOR=$(cat ${FW_VERSION_A} | cut -d . -f 1)
			OLD_VERSION_MINOR=$(cat ${FW_VERSION_A} | cut -d . -f 2)
		else
			exit
		fi
		if [ -f ${BREAKING_CHANGE_VERSION} ]; then
			BC_MAJOR=$(cat ${BREAKING_CHANGE_VERSION} | cut -d . -f 1)
			BC_MINOR=$(cat ${BREAKING_CHANGE_VERSION} | cut -d . -f 2)
			if [ "${BC_MAJOR}" -gt 0 ]; then
				if [ "${BC_MAJOR}" -gt "${OLD_VERSION_MAJOR}" ]; then
					delete_knx_download ${OLD_VERSION_MAJOR} ${OLD_VERSION_MINOR}
				elif [ "${BC_MAJOR}" -eq "${OLD_VERSION_MAJOR}" ]; then
					if [ "${BC_MINOR}" -gt "${OLD_VERSION_MINOR}" ]; then
						delete_knx_download ${OLD_VERSION_MAJOR} ${OLD_VERSION_MINOR}
					fi
				fi
			fi
		fi
	fi
	if [ "$(diff ${FW_VERSION_A} ${FW_VERSION_B})" == "" ]; then
		# both system equal, delete backup if present.
		if [ -f ${KNX_DL_PATH}/device*.xml.*.* ]; then
			echo "Detected obsolete KNX download backup file, because both firmware versions are equal and more recent."
			rm -f ${KNX_DL_PATH}/device*.xml.*.*
		fi
	fi
	$(rm -rf /tmp/extparam)
    ;;
  stop)

    ;;
  *)
    echo "Usage: $0 (start|stop)"
    exit 1
esac

exit 0