#!/bin/sh

me="[S11factoryreset]"
printf "%s Enter.\\n" "${me}"

source /opt/gira/share/devicestack/ipmodule-vars

start()
{
	if [ -f "${EMERGENCY_FACTORY_RESET_FILE}" ]
	then
		# cat file and remove spaces, newlines, cariagereturns and tabs if any.
		FACTORY_RESET_CONDITION=`cat ${EMERGENCY_FACTORY_RESET_FILE} | tr -d '\040\011\012\015'`
		if [ "enabled" = "${FACTORY_RESET_CONDITION}" ]
		then
			printf "%s Emergency factory reset found enabled. Calling %s.\\n" "${me}" "${FACTORY_RESET}"
			${FACTORY_RESET}
			printf "%s Removing file: %s\\n" "${me}" "${EMERGENCY_FACTORY_RESET_FILE}"
			rm -f ${EMERGENCY_FACTORY_RESET_FILE}
			printf "%s Done.\\n" "${me}"
			exit 0
		fi
	fi

	CONDITION_RESULT=0
	LEDS="prg1,prg2,system,knx"

	if [ -x "${CHK_FACTRSTCOND_TOOL}" ]
	then
		${CHK_FACTRSTCOND_TOOL} --leds ${LEDS} --message_queue /progButton 2>&1 > /var/log/check-factory-reset.log
		CONDITION_RESULT=$?
	else
		printf "%s %s not found.\\n" "${me}" "${CHK_FACTRSTCOND_TOOL}"
	fi
	if [ ${CONDITION_RESULT} -eq 1 ]
	then
		printf "%s Button press sequence detected, executing factory reset.\\n" "${me}"
		${FACTORY_RESET}
	elif [ ${CONDITION_RESULT} -eq 2 ]
	then
		printf "%s Factory reset override detected, executing factory reset.\\n" "${me}"
		${FACTORY_RESET}
	elif [ ${CONDITION_RESULT} -eq 3 ]
	then
		# The configuration-reset script requires a mounted userdata
		printf "%s Configuration reset override detected, will reset configuration\\n" "${me}"
		printf "%s when the userdata is mounted.\\n" "${me}"
		printf "enabled\\n" > ${CONFIGURATION_RESET_FILE}
	else
		printf "%s No request detected.\\n" "${me}"
	fi
}

case "$1" in
	start)
		start
		;;
	stop|restart|reload)
		;;
	*)
		printf "Usage: %s {start}\\n" "$0"
		exit 1
esac

exit 0
