#!/bin/bash

# Define the path and any password options for MPD
MY_MPC="/usr/bin/mpc -h 192.168.100.1"

# This is the GPIO pin connected to the magic button
MagicButton=4

# Set the polarity of the switch:
# depends if switch is normally open or closed
ASSERT=0
NEGATE=1

echo "$MagicButton" > /sys/class/gpio/export
echo "in" > /sys/class/gpio/gpio$MagicButton/direction
old=$NEGATE
start=0
end=0
diff=0
while [ TRUE ]; do
  button=$(cat /sys/class/gpio/gpio$MagicButton/value)
  uptime=$(</proc/uptime)
  uptime=${uptime%% *}
  uptime=${uptime/.}
  #echo "MagicButton: ${button} ${old} ${uptime} ${start} ${end} ${diff}"
  # Check for button state
  if [ ${button} -eq $ASSERT ] && [ ${old} -eq $NEGATE ]; then
    # Button pressed
    old=$ASSERT
    start=${uptime}
  fi
  if [ ${button} -eq $NEGATE ] && [ ${old} -eq $ASSERT ]; then
    # Button released
    old=$NEGATE
    end=${uptime}
    diff=`expr ${end} - ${start}`
    # Now act on the length of button press
    if [ ${diff} -le 35 ]; then
      # Skip track
      echo "MagicButton: Skipping track"
      $MY_MPC -q next
    fi
    if [ ${diff} -gt 35 ] && [ ${diff} -le 200 ]; then
      # Restart track
      echo "MagicButton: Restarting track"
      $MY_MPC -q seek 00:00:00
    fi
    if [ ${diff} -ge 500 ]; then
      # Reboot
      echo "MagicButton: Rebooting server"
      reboot
    fi
  fi
  sleep 0.1
done
