#!/usr/bin/env ocamlscript
(*
 * multimedia-keys
 * ---------------
 * Copyright : (c) 2009, Jeremie Dimino <jeremie@dimino.org>
 * Licence   : BSD3
 *
 * This file is a part of obus, an ocaml implementation of D-Bus.
 *)

Ocaml.packs := ["lwt.syntax"; "obus.syntax"; "obus"]
--

(* Simple script which listen keyboard events emited by hal and run
   commands *)

open Lwt

(* Configuration *)
let commands = [
  ("volume-up", "amixer -q set Master 5%+");
  ("volume-down", "amixer -q set Master 5%-");
]

lwt () =
  lwt bus = Lazy.force OBus_bus.system in

  (* Tell the message bus we want to receive ButtonPressed events from
     hal. *)
  lwt () = OBus_bus.add_match bus (OBus_match.rule
                                     ~sender:"org.freedesktop.Hal"
                                     ~interface:"org.freedesktop.Hal.Device"
                                     ~member:"Condition"
                                     ~arguments:[(0, "ButtonPressed")] ()) in

  (* Add a message filter. We use that instead of adding a signal
     receiver because we do not care about which object send the
     event. *)
  ignore (Lwt_sequence.add_l
            (function
               | { OBus_message.typ = OBus_message.Signal(_, "org.freedesktop.Hal.Device", "Condition");
                   OBus_message.body = OBus_value.V.([Basic(String "ButtonPressed"); Basic(String button)]) } ->
                   begin match try Some(List.assoc button commands) with Not_found -> None with
                     | Some command ->
                         ignore_result (Lwt_unix.system command)
                     | None ->
                         ()
                   end;
                   Some msg
               | msg ->
                   Some msg)
            (OBus_connection.incoming_filters bus));

  (* Wait forever, the program will exit when the connection is
     closed *)
  fst (wait ())
