#!/bin/sh
# $Log: transfer_play.in,v $
# Revision 1.6  2021-02-14 18:43:07+05:30  Cprogrammer
# display list of valid hosts on wrong input
#
# Revision 1.5  2020-09-05 12:32:42+05:30  Cprogrammer
# clear playlist before adding
#
# Revision 1.4  2020-08-30 10:57:30+05:30  Cprogrammer
# use state_file definition in mpd.conf to figure out state_file directory
#
# Revision 1.3  2020-08-11 22:23:23+05:30  Cprogrammer
# use mpc to play and remove playlist
#
# Revision 1.2  2020-07-23 01:47:58+05:30  Cprogrammer
# removed incorrect check for tohost
#
# Revision 1.1  2020-07-22 15:50:47+05:30  Cprogrammer
# Initial revision
#
#
# $Id: transfer_play.in,v 1.6 2021-02-14 18:43:07+05:30 Cprogrammer Exp mbhangui $
#
get_mpd_conf_value()
{
    grep "^$1" /etc/mpd.conf|awk '{print $2}' | \
    sed -e 's{"{{g'
}

get_mpd_state()
{
	host=$1
	(
	do_print=0
	cat $state_dir/mpd_state.$host | while read line
	do
		if [ " $line" = " playlist_begin" ] ; then
			do_print=1
			continue
		fi
		if [ " $line" = " playlist_end" ] ; then
			break
		fi
		if [ $do_print -eq 1 ] ; then
			echo $line
		fi
	done
	) | sed -e 's{^.*:{{'
}

music_dir=`get_mpd_conf_value music_dir`
if [ $? -ne 0 ] ; then
	echo "could not get music directory from mpd.conf" 1>&2
	exit 1
fi

playlist_dir=`get_mpd_conf_value playlist_directory`
if [ $? -ne 0 ] ; then
	echo "could not get playlist directory from mpd.conf" 1>&2
	exit 1
fi
if [ $# -ne 2 ] ; then
	echo "transfer_play fromhost tohost" 1>&2
	exit 1
fi
fromhost=$1
tohost=$2

state_file=`get_mpd_conf_value state_file`
state_dir=$(dirname $state_file)
if [ ! -f $state_dir/mpd_state.$fromhost ] ; then
	echo "No such host $fromhost" 1>&2
	echo "List of valid hosts"
	ls $state_dir/mpd_state.*|cut -d. -f2
	exit 1
fi
out=`mktemp -t mpdevXXXXXXXXXX`
get_mpd_state $fromhost > $out.m3u
mv $out.m3u $playlist_dir
out=`basename $out`
mpc --host="$tohost" clear
echo "mpc --host=$tohost load $out"
mpc --host=$tohost load $out
mpc --host=$tohost play
mpc --host=$tohost rm $out
