#!/bin/bash
tmp=""" "

# PART 1: the bash rc.d service

. /etc/rc.conf
. /etc/rc.d/functions

case "$1" in

  _keypress)
    case "$2" in
      play-pause) mpc toggle;;
      stop-cd)    mpc stop;;
      forward)    mpc next;;
      back)       mpc prev;;
    esac
  ;;

  start)
    stat_busy "Starting Mediakeys"
    [ -z "`pgrep -f 'python /etc/rc.d/mediakeys'`" ] && python /etc/rc.d/mediakeys &>/dev/null
    if [ $? -ne 0 ]; then
      stat_fail
    else
      add_daemon mediakeys
      stat_done
    fi
  ;;

  stop)
    stat_busy "Stopping Mediakeys"
    pkill -f 'python /etc/rc.d/mediakeys' &>/dev/null
    if [ $? -ne 0 ]; then
      stat_fail
    else
      rm_daemon mediakeys
      stat_done
    fi
  ;;

  restart)
    $0 stop
    sleep 1
    $0 start
  ;;

  *)
    echo "usage: $0 {start|stop|restart}"
esac

exit 0
"
"""

# PART 2: the python D-Bus monitor

import dbus, dbus.mainloop.glib, gobject, os

if os.fork() <> 0:
	exit(0)

if os.geteuid() == 0:
	os.setegid(99)
	os.seteuid(99)

def press(p, key):
	os.spawnl(os.P_WAIT, "/bin/bash", "/bin/bash", "-", "/etc/rc.d/mediakeys", "_keypress", key)

dloop = dbus.mainloop.glib.DBusGMainLoop()
gloop = gobject.MainLoop()
bus = dbus.SystemBus(mainloop=dloop)
bus.add_signal_receiver(handler_function=press, signal_name='Condition', dbus_interface='org.freedesktop.Hal.Device', arg0='ButtonPressed')

gloop.run()

