#!/bin/sh -

. $HOME/.mp3player.cfg

if [ $# -ne 0 ]
then
	case $1 in
		--local)
			playlist=$localplaylist
			find $localplaydir -type f -name '*.mp3' | \
				sort > $playlist
		;;

		--home)
			playlist="$homeplaylist"
		;;

		--external)
			playlist="$externalplaylist"
		;;

		--status)
			fuser $audio_device | sed 's/.*://' | \
				xargs ps -p 2>/dev/null | \
				grep `basename $mp3player` > /dev/null

			if [ $? -eq 0 ]; then
			        echo "playing: 1"
			else
			        echo "playing: 0"
			fi
			exit 0
		;;

		*)
			args="$@"
		;;
	esac
else
	ifconfig="`/sbin/ifconfig -a | gawk 'BEGIN { FS=\"\n\"; RS=\"\n\n\"; OFS=\" \"; ORS=\"\n\"; } { for (n=1; n <= NF; n++) { printf $n } print \"\" }' | egrep '^(eth|fxp)' | grep 'UP' | grep -v 'unspec addr' | grep 'inet addr: *[0-9]'`"

	if [ x"$ifconfig" = x"" ]; then
		playlist=$localplaylist
		find $localplaydir -type f -name '*.mp3' | sort > $playlist
	else
		search="`grep ^search /etc/resolv.conf | head -1 | sed 's/^search[ 	]*//'`"

		case "$search" in
			$home)
				playlist="$homeplaylist"
			;;

			$external)
				playlist="$externalplaylist"
			;;

			*)
				echo "Where are you... going local" >&2
				playlist=$localplaylist
				find $localplaydir -type f -name '*.mp3' | \
					sort > $playlist
			;;
		esac
	fi
fi

if [ x"$playlist" != x"" ]; then
	if echo $playlist | grep "^http://" > /dev/null; then
		ftp -o - $playlist | gzip -cd > $playliststorage
		args=$playliststorage
	else
		args=$playlist
	fi
fi

exec $mp3player $args
