#!/bin/sh

# This script will reboot device after long press (10 sec) to 'service' button
# Viktor Kovalov, INFOMIR LLC 2019-07

# service button

TYPE="EV_KEY"
CODE="KEY_VENDOR"
NAME="gpio-keys-polled"
DEV=`echo 100 | evtest 2>&1 | grep ${NAME}`
DEV=${DEV%%:*}

i=0
while [ 1 ]; do
    sleep 1

    evtest --query ${DEV} ${TYPE} ${CODE}

    if [ "$?" -eq "10" ]; then
        i=$((i+1))

        # blink front LED once
        if [ -f "/sys/class/leds/mag-front-led/cnt" ]; then
            echo "1" > /sys/class/leds/mag-front-led/cnt
        fi
    else
        i=0
    fi

    if [ "$i" -eq "10" ]; then
        echo "[+] Executing 'RESET (software) for the device'"

        # blink front LED 100 times as an indication of reset
        if [ -f "/sys/class/leds/mag-front-led/cnt" ]; then
            echo "100" > /sys/class/leds/mag-front-led/cnt
        fi

        reboot

        sleep 60
    fi

done

exit 0