+#!/bin/bash
+# gpiomon waits for two events (rising or falling)
+for((;;)); do
+ a=$(sudo gpiomon --bias pull-down -n 2 -F="%s" 0 109)
+ b=$(echo "$a" | tr -d '=')
+ mapfile -t sec_val <<<"$b"
+ n=$(( sec_val[1] - sec_val[0] ))
+ # n is the time difference between the two events (in seconds)
+ # check if music is playing
+ mpc | grep playing
+ status=$?
+
+ if [ "$n" -gt 1 ]; then # long press, play previous playlist
+ if [ "$status" == 0 ]; then
+ mpc clear
+ cd /home/ubuntu/musica/playlists || exit
+ p_c=$(cat /home/ubuntu/musica/current_playlist)
+ tot=$(ls -1 * | wc -l)
+ if [ "$p_c" -gt 2 ]; then
+ p_n=$(( p_c - 1 ))
+ else
+ p_n=$tot
+ fi
+ echo "$p_n" > /home/ubuntu/musica/current_playlist
+ playlist_file=$(ls * | awk -v x="$p_n" 'NR==x')
+ playlist_file=${playlist_file/.m3u/}
+ mpc clear
+ mpc load "$playlist_file"
+ mpc play
+ else
+ mpc play
+ fi
+ else # short press, play previous song in the current playlist
+ if [ "$status" == 0 ]; then
+ mpc prev
+ else
+ mpc play
+ fi
+ fi
+done