#!/usr/bin/env bash

# Scriptlet to check for MPD idle time and shut down after
# inactivity. Needs root privileges. Ideally run from cron.
# Make sure you have MPD's loglevel set to "default" for it
# to work properly; if you need a higher loglevel you need
# to modify the mpd_time check.
# Features:
# - adjustable timeout
# - adjustable inactivity action
# - logs to syslog so you have a clue whether it works or not
# - test sequence to ensure functionality

# Variables that can be set to your preference. Time in seconds.
# Replace the content of the action function (curly brackets)
# with the command you want to be executed.
timeout="1800"
action(){
	/sbin/shutdown -h now
	}


# Check routines. Dates since epoch, in seconds. Makes for easier
# calculating. Won't work after 2038.
mpd_time="$(/bin/date +%s -d $(/usr/bin/tail -1 /var/log/mpd/mpd.log|/usr/bin/awk '{print $3}') )"
pres_time="$(/bin/date +%s)"

## Test sequence. Uncomment if needed or just curious.
#echo "MPD log was last modified on $mpd_time."
#echo "Current time is $pres_time."
#echo "Present time difference is $(( pres_time - mpd_time )) seconds."

mpd_time=$(( mpd_time + timeout ))

if [ $pres_time -ge $mpd_time ]
then
	action	
else
	/usr/bin/logger "Less than $(( timeout / 60 )) minutes since last MPD activity. Not shutting down."
fi
