#!/bin/sh

# CONFIGURE
EVENT_DEV="/dev/input/event0"    # change if your reset button is on a different event device
KEY_CODE="KEY_RESTART"           # as reported by evtest
LED_PATH="/sys/class/leds/bcm47xx:green:dmz"  # adjust to your LED name from ls /sys/class/leds
FAILSAFE_IP="192.168.1.1"
FAILSAFE_BCAST="192.168.1.255"

# Bring up LAN
ip link set up dev eth0
ip addr add ${FAILSAFE_IP}/24 broadcast ${FAILSAFE_BCAST} dev eth0

# Warn the user
netmsg ${FAILSAFE_BCAST} "Press reset now, to enter Failsafe!"
echo "Press reset now to enter Failsafe!"
sleep 2 &

# Check for reset press during the 2s window
# We'll read the event stream for KEY_RESTART with value 1 (press)
pressed=0
timeout 2 sh -c "
    evtest ${EVENT_DEV} 2>/dev/null | \
    grep -m1 '${KEY_CODE}.*value 1' && exit 0 || exit 1
"
if [ $? -eq 0 ]; then
    pressed=1
fi

if [ "$pressed" -eq 1 ]; then
    # Blink LED in background
    (
        while :; do
            echo 1 > ${LED_PATH}/brightness
            sleep 0.5
            echo 0 > ${LED_PATH}/brightness
            sleep 0.5
        done
    ) &

    netmsg ${FAILSAFE_BCAST} "Entering Failsafe!"
    telnetd
    exit 1
else
    ip addr flush dev eth0
fi

