#!/bin/sh -b

USAGE='music mo v0.1\n
yiyus (JGL) 2007\n
FS'

MP3LIST=${MOLIST:-"$HOME/.mp3list"}

add2list() {
	touch $MP3LIST && cat $MP3LIST - | sort -u | uniq > $MP3LIST
}

mostop() {
	ps -A | grep ' mpg123$' | awk '{print $1}' | head -n1 | xargs /bin/kill > /dev/null 2>&1
	ps -A -o pid,cmd | grep ' '`basename $0`' next$' | awk '{print $1}' | head -n-1 | xargs /bin/kill > /dev/null 2>&1
	ps -A | grep ' mpg123$' | awk '{print $1}' | head -n1 | xargs /bin/kill > /dev/null 2>&1
}

moplay() {
	(song="`head -n 1 $MP3LIST`"; echo -e '1m$\nwq' | ed -s $MP3LIST && mpg123 -q "$song" > /dev/null 2>&1 && nohup `basename $0` next & )& >/dev/null 2>&1
}

set -b

if [ $# -gt 0 ]; then
	case "$1" in
		next)
			if [ -f "$MP3LIST" ]; then
				next=${2-"1"}
				mostop
				if [ $next -gt 1 ]; then
					echo -e '1,'$((next - 1))'m$\nwq' | ed -s $MP3LIST
				fi
				moplay
				disown
			fi
			shift
			;;
		play)
			if [ -f "$MP3LIST" ]; then
				mostop
				moplay
			fi
			shift
			;;
		prev)
			if [ -f "$MP3LIST" ]; then
				mostop
				echo -e '$m1\nwq' | ed -s $MP3LIST
				moplay
			fi
			shift
			;;
		stop)
			mostop
			shift
			;;
		first)
			if [ -f "$MP3LIST" ]; then
				next=${2-"1"}
				if [ $next -gt 1 ]; then
					echo -e $next'm0\nwq' | ed -s $MP3LIST
				fi
			fi
			shift
			;;
		add)
			while [ $# -gt 1 ]; do
				if [ "$2" = "R" ]; then
					`basename $0` random
				else
					find "$2" -name '*.mp3' | add2list
				fi
				shift
			done
			shift
			;;
		del)
			echo -e ${2-'1'}','${3-${2-'1'}}'d\nwq' | ed -s $MP3LIST
			shift
			;;

		clear)
			if [ -f "$MP3LIST" ]; then
				rm $MP3LIST
			fi
			shift
			;;
		list)
			num=1
			if [ -f "$MP3LIST" ]; then
				list="cat \$MP3LIST | while read line; do echo \"[\$num] \$line\"; num=\$((num+1)); done"
				if [[ $2 > 0 ]]; then eval $list | head -n $2
				#elif [ $((2 * (-1))) -gt 0 ]; then eval $list | tail -n $((2 * (-1))) #FIXME
				else eval $list
				fi

			fi
			shift
			;;
		whatlist)
			echo "$MP3LIST"
			shift
			;;
		sort)
			if [ -f "$MP3LIST" ]; then
				cat $MP3LIST | sort -u > $MP3LIST
			fi
			shift
			;;
		random)
			if [ -f "$MP3LIST" ]; then
				cat $MP3LIST | while read line; do echo "$RANDOM:$line"; done | sort -n | cut -d ':' -f2- > $MP3LIST
			fi
			shift
			;;
		current)
			currentsong="`(ps -C "mpg123" h -o etime,cmd||echo "silence!")|sed 's/mpg123 -q//;s/^      //'`"
			if [ $2 -a $2 = "allways" ]; then
				while true; do
					echo '('`cat $MP3LIST | wc -l`') '`echo "$currentsong" | cut -d ' ' -s -f3-` ' [ '`echo "$currentsong" | cut -d ' ' -f1`' ]'
					sleep 1
					currentsong="`(ps -C "mpg123" h -o etime,cmd||echo "silence!")|sed 's/mpg123 -q//;s/^      //'`"
				done
				shift
			else
				echo '('`cat $MP3LIST | wc -l`') '`echo "$currentsong" | cut -d ' ' -s -f3-` ' [ '`echo "$currentsong" | cut -d ' ' -f1`' ]'
			fi
			shift
			;;
	esac
	shift
else
	echo -e $USAGE
fi

exit 0
