#!/bin/bash
#
# Raspberry Pi restart/shutdown with push button
# Hold button for 2 seconds: reboot
# Hold button for 5 seconds: poweroff
#

# Define variables
PWRBTN="1"

# Export pins
if [ ! -e /sys/class/gpio/gpio16 ]; then
        echo "16" > /sys/class/gpio/export
fi

if [ ! -e /sys/class/gpio/gpio12 ]; then
        echo "12" > /sys/class/gpio/export
fi

# Set pins as input/output
echo "in" > /sys/class/gpio/gpio16/direction
echo "out" > /sys/class/gpio/gpio12/direction

while true; do
		# Read pins
		read PWRBTN < /sys/class/gpio/gpio16/value
        if [ $PWRBTN = "0" ]; then
                sleep 2s
                read PWRBTN < /sys/class/gpio/gpio16/value
                if [ $PWRBTN = "0" ]; then
                        sleep 3s
                        read PWRBTN < /sys/class/gpio/gpio16/value
                        if [ $PWRBTN = "0" ]; then
                                echo "1" > /sys/class/gpio/gpio12/value
                                sleep 1s
                                echo "0" > /sys/class/gpio/gpio12/value
                                sleep 1s
                                echo "1" > /sys/class/gpio/gpio12/value
                                echo "Shutting down..."
                                sleep 1s
                                poweroff
                        else
                                echo "1" > /sys/class/gpio/gpio12/value
                                echo "Rebooting..."
								sleep 1s
                                reboot
                        fi
                fi
        fi
        sleep 1s
done
