#!/bin/sh
#
# A shell script for easily managing some of the
# Vagalume features available via its D-Bus interface.
#
# Copyright (C) 2008, 2010 Igalia, S.L.
# Authors: Mario Sanchez Prada <msanchez@igalia.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
set -e

PROGNAME="$(basename $0)"

# D-Bus basic parameters
DBUS_SERVICE='com.igalia.vagalume'
DBUS_OBJECT=/com/igalia/vagalume
DBUS_IFACE=com.igalia.vagalume

# Available D-Bus commands
DBUS_METHOD_PLAY="Play"
DBUS_METHOD_STOP="Stop"
DBUS_METHOD_SKIP="Skip"
DBUS_METHOD_LOVETRACK="LoveTrack"
DBUS_METHOD_BANTRACK="BanTrack"
DBUS_METHOD_PLAYURL="PlayUrl"
DBUS_METHOD_VOLUMEUP="VolumeUp"
DBUS_METHOD_VOLUMEDOWN="VolumeDown"
DBUS_METHOD_SETVOLUME="SetVolume"
DBUS_METHOD_CLOSEAPP="CloseApp"
DBUS_METHOD_TOPAPP="top_application"
DBUS_METHOD_SHOWWINDOW="ShowWindow"
DBUS_METHOD_HIDEWINDOW="HideWindow"

# Print the usage for this shell script
print_usage ()
{
    echo "Usage:"
    echo "  $PROGNAME <COMMAND>"
    echo "     (Vagalume will be automatically started if not already running)"
    echo
    echo "  COMMAND:"
    echo "     play:              start playing the current radio"
    echo "     skip:              skip to the nex song in the current radio"
    echo "     stop:              stop playing the current radio"
    echo "     love:              mark the current song as 'loved'"
    echo "     ban:               mark the current song as 'banned'"
    echo "     globaltag <TAG>:   change to a 'global tag' radio."
    echo "     artist <ARTIST>:   change to a 'similar artists' radio"
    echo "     group <GROUP>:     change to a 'last.fm group' radio"
    echo "     loved <USER>:      change to a 'loved' radio for a specific user"
    echo "     mix <USER>:        change to a 'mix' radio for a specific user"
    echo "     neighbours <USER>: change to a 'neighbours' radio for a specific user"
    echo "     library <USER>:    change to a 'library' radio for a specific user"
    echo "     playlist <USER>:   change to a 'playlist' radio for a specific user"
    echo "     playurl <URL>:     just play the specified URL on Vagalume"
    echo "     volumeup [INC]:    increase playback volume"
    echo "     volumedown [INC]:  decrease playback volume"
    echo "     volume <VALUE>:    set the playback volume to a specific value"
    echo "     start:             start Vagalume (if not already running)"
    echo "     close:             close Vagalume (if not already closed)"
    echo "     show:              show the player window"
    echo "     hide:              hide the player window"
    echo "     help:              print this information"
    echo
    echo " Double quotes are REQUIRED when specifying parameters to some commands,"
    echo " such as TAG or ARTIST, because of the white spaces they might contain, e.g:"
    echo
    echo "     $ $PROGNAME globaltag \"hard rock\""
    echo "     $ $PROGNAME artist \"Led Zeppelin\""
    echo
}

# Invalid parameters: print usage and exit with error code
invalid_params ()
{
    # Print error message, if specified
    if [ $# -gt 0 ]; then
	echo "Error: "${1};
	echo;
    fi

    print_usage;
    exit 1;
}

# Check number of parameteres
if [ $# -lt 1 ]; then
    invalid_params;
fi

if ! which dbus-send > /dev/null 2>&1; then
    echo "ERROR: dbus-send not found"
    exit 1
fi

# Check the command and execute it
COMMAND=${1}
if [ $# -eq 1 ]; then
  # Commands requiring no parameters
  case ${COMMAND} in
    "stop") DBUS_METHOD_CALL=${DBUS_METHOD_STOP};;
    "play") DBUS_METHOD_CALL=${DBUS_METHOD_PLAY};;
    "skip") DBUS_METHOD_CALL=${DBUS_METHOD_SKIP};;
    "love") DBUS_METHOD_CALL=${DBUS_METHOD_LOVETRACK};;
    "ban") DBUS_METHOD_CALL=${DBUS_METHOD_BANTRACK};;
    "volumeup") DBUS_METHOD_CALL=${DBUS_METHOD_VOLUMEUP};;
    "volumedown") DBUS_METHOD_CALL=${DBUS_METHOD_VOLUMEDOWN};;
    "close") DBUS_METHOD_CALL=${DBUS_METHOD_CLOSEAPP};;
    "start") DBUS_METHOD_CALL=${DBUS_METHOD_TOPAPP};;
    "close") DBUS_METHOD_CALL=${DBUS_METHOD_CLOSEAPP};;
    "show") DBUS_METHOD_CALL=${DBUS_METHOD_SHOWWINDOW};;
    "hide") DBUS_METHOD_CALL=${DBUS_METHOD_HIDEWINDOW};;
    "help") print_usage; exit 0;;
    *) invalid_params;;
  esac
elif [ $# -eq 2 ]; then
  # Commands requiring a parameter
  ENCODED_PARAM=`echo ${2} | tr " " "+"`
  case ${COMMAND} in
    "globaltag") URL="lastfm://globaltags/"${ENCODED_PARAM};;
    "artist") URL="lastfm://artist/"${ENCODED_PARAM};;
    "group") URL="lastfm://group/"${ENCODED_PARAM};;
    "loved") URL="lastfm://user/"${ENCODED_PARAM}"/loved";;
    "mix") URL="lastfm://user/"${ENCODED_PARAM}"/mix";;
    "neighbours") URL="lastfm://user/"${ENCODED_PARAM}"/neighbours";;
    "library") URL="lastfm://user/"${ENCODED_PARAM}"/personal";;
    "playlist") URL="lastfm://user/"${ENCODED_PARAM}"/playlist";;
    "playurl") URL=${ENCODED_PARAM};;
    "volumeup") DBUS_METHOD_CALL=${DBUS_METHOD_VOLUMEUP};;
    "volumedown") DBUS_METHOD_CALL=${DBUS_METHOD_VOLUMEDOWN};;
    "volume") DBUS_METHOD_CALL=${DBUS_METHOD_SETVOLUME};;
    *) invalid_params;;
  esac;

  # Parse numerical parameters, if needed
  case ${COMMAND} in
    "volumeup"|"volumedown"|"volume")
	  if echo ${2} | grep -q '^[0-9]\+$'; then
	      DBUS_METHOD_PARAMS="uint32:${2}";
	  else
	      invalid_params "The specified parameter must be a positive number";
	  fi;;
  esac;

  if [ -n "${URL}" ]; then
      DBUS_METHOD_CALL=${DBUS_METHOD_PLAYURL}" string:"${URL};
  fi
else
  invalid_params;
fi

# Check whether vagalume is or not already running
if { { which pidof && pidof vagalume    ; }   || \
     { which pgrep && pgrep -x vagalume ; } } > /dev/null 2>&1; then
    if [ ${COMMAND} = "start" ]; then
        echo "Vagalume already running."
        exit 0
    fi
elif [ ${COMMAND} = "close" ]; then
    # Exit cleanly without executing the 'close' command when Vagalume is not running
    echo "Vagalume not running: no need to close it"
    exit 0
fi

# At last, execute the command
dbus-send --print-reply --type=method_call \
          --dest=${DBUS_SERVICE} ${DBUS_OBJECT} ${DBUS_IFACE}.${DBUS_METHOD_CALL} ${DBUS_METHOD_PARAMS} > /dev/null

echo "Command '"$COMMAND"' successfully executed"
