#!/bin/sh

me="[S11factoryreset]"
echo "${me} Enter."

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

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
		echo "${me} Emergency factory reset found enabled. Calling ${FACTORY_RESET}."
		${FACTORY_RESET}
		echo "${me} Removing file: ${EMERGENCY_FACTORY_RESET_FILE}"
		rm -f ${EMERGENCY_FACTORY_RESET_FILE}
		echo "${me} Done."
		exit 0
	fi
fi

CONDITION_RESULT=0
GPIO_BUTTON=101
LEDS="progred,workgreen,netred,netgreen"

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

exit 0

