#!/usr/bin/sh
#
# $Id: lcd_display.in,v 1.6 2023-06-30 20:28:25+05:30 Cprogrammer Exp mbhangui $
#
# You need the nc command for this script to write to a remote LCD. nc
# comes from the netcat package
# If you have installed mpdev this script will get called.
#
# 1. If lcd-daemon is running locally you need to do nothing
# 2. if lcd-daemon is running on a remote host, you need to set
#    LCD_HOST, LCD_PORT environment variable in /service/mpdev/variables
#    like this
#    echo w.x.y.z > /service/mpdev/variables/LCD_HOST
#    echo port    > /service/mpdev/variables/LCD_PORT
#

set_command()
{
	if [ -n "$LCD_FIFO" ] ; then
		cmd="/bin/cat > $LCD_FIFO"
		return 0
	elif [ -n "$LCD_HOST" ] ; then
		if [ -z "$LCD_PORT" ] ; then
			LCD_PORT=1806
		fi
		cmd="nc -w 1 -u $LCD_HOST $LCD_PORT"
		return 0
	fi
	if [ -d /run ] ; then
		lcdfifo="/run/lcd-daemon/lcdfifo"
	elif [ -d /var/run ] ; then
		lcdfifo="/var/run/lcd-daemon/lcdfifo"
	else
		lcdfifo="/tmp/lcd-daemon/lcdfifo"
	fi
	if [ -p $lcdfifo ] ; then
		cmd="/bin/cat > /run/lcd-daemon/lcdfifo"
		return 0
	elif [  -x /usr/bin/nc ] ; then
		if [ -n "$LCD_HOST" ] ; then
			lcdhost=$LCD_HOST
		else
			lcdhost=$(grep lcdhost /etc/hosts|awk '{print $1}')
		fi
		if [ -z "$LCD_PORT" ] ; then
			LCD_PORT=1806
		fi
		if [ -n "$lcdhost" ] ; then
			cmd="nc -w 1 -u $lcdhost $LCD_PORT"
			return 0
		fi
	fi
	exit 1
}

if [ -z "$MPDEV_TMPDIR" ] ; then
	MPDEV_TMPDIR=/tmp/mpdev
fi

case $1 in
	play)
		set_command
		echo "3 0 0:PL Vo $(mpc vol|cut -d: -f2|cut -d% -f1)" | sh -c "$cmd"
	;;
	pause-song|pause)
		set_command
		echo "3 0 0:PS Vo $(mpc vol|cut -d: -f2|cut -d% -f1)" | sh -c "$cmd"
	;;
	end-song)
		set_command
		echo "3 0 0:ST Vo $(mpc vol|cut -d: -f2|cut -d% -f1)" | sh -c "$cmd"
	;;
	now-playing)
		set_command
		(
		echo "0 0 2:$SONG_TITLE"
		echo "1 0 0:$SONG_ARTIST"
		echo "2 0 0:$SONG_ALBUM"
		printf "3 0 0:PL Vo %+3s R %2d P %d\n" $(mpc vol|cut -d: -f2|cut -d% -f1) $RATING $PLAYCOUNT
		) | tee $MPDEV_TMPDIR/lcd.out | sh -c "$cmd"
	;;
	mixer)
		set_command
		case "$PLAYER_STATE" in
			play)
				t=PL
			;;
			pause)
				t=PS
			;;
			stop)
				t=ST
			;;
			*)
				t=$PLAYER_STATE
			;;
		esac
		printf "3 0 0:%s Vo %+3s\n" "$t" $(mpc vol|cut -d: -f2|cut -d% -f1) | sh -c "$cmd"
	;;
esac
