#!/bin/bash
#
# Publishes Amarok's currently playing song as a "XEP-0118: User Tune" node via Psi's file interface
#
# Authors (in chronological order) :
#          Silian Della Ragione
#          Andres Gomez Garcia 
#          Antoine  Gassot 
#          Albert
#	   mbishop 
#	   Jean-Marc Liotier 
#
# Changelog :
#          20080204 Modified to fix stream/mp3 tune strings by mbishop 
#          20080508 "XEP-0118: User Tune" near-conformance by Jean-Marc Liotier 
#
# Version: 0.0.4
#
# License GNU/GPL
############################################################################
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
#########################################################################

# This is the default file interface path,
# good if the user did not change the standard Psi configuration path
# which is a reasonable assumption
psi_tune_file=~/.psi/tune

psi_tune_file_temp=~/.psi/.tune.tmp

change () {
    title=`dcop amarok player title`
    artist=`dcop amarok player artist`
    album=`dcop amarok player album`
    track=`dcop amarok player track`
    # trackTotalTime and not totalTime because the time must be in seconds
    length=`dcop amarok player trackTotalTime`
    rating=`dcop amarok player rating`

    if [ "$type" = "Stream" ];
      then
	tune="${title} - ${album}"
	echo ${tune} > ${psi_tune_file}
      else
	# Psi is watching the tune file
	# so we need to assemble its content in a temporary file
	# and only show it to Psi when complete
	rm -f ${psi_tune_file_temp}
	touch ${psi_tune_file_temp}
	# Psi relies on the order of those lines in the filei
	# read Psi 0.11's src/tools/tunecontroller/filetunecontroller.cpp to know the actual order :
	# 	tune.setName(stream.readLine());
        # 	tune.setArtist(stream.readLine());
        # 	tune.setAlbum(stream.readLine());
        # 	tune.setTrack(stream.readLine());
        # 	tune.setTime(stream.readLine().toUInt());
	echo "${title}" >> ${psi_tune_file_temp}
	echo "${artist}" >> ${psi_tune_file_temp}
	echo "${album}" >> ${psi_tune_file_temp}
	echo "${track}" >> ${psi_tune_file_temp}
	echo "${length}" >> ${psi_tune_file_temp}
	# Psi itself ignores the rating
	# Maybe the user does not want that private information leaked anyway
	# Rating is optional un XEP-0118
#	echo "${rating}" >> ${psi_tune_file_temp}
	mv ${psi_tune_file_temp} ${psi_tune_file}
    fi
}

stop () {
    rm ${psi_tune_file}
}

terminate () {
    stop
    exit 0
}

trap terminate 0 1 2 5 15

while [ 1 ]
do
    read input
    input=$(echo $input | sed -e 's/engineStateChange:\ //')

    case "$input" in
    "playing" | "trackChange" )
        change
        ;;
    "paused" | "empty" | "idle" )
        stop
        ;;
    esac
done