#! /bin/sh

# dr_unsort - wrapper for unsort(1), based upon mpd-unsort by Wessel Dankers
#
# This file is maintained at http://git.mdcc.cx/draai
# Copyright: © 2008-2009 Wessel Dankers
# Copyright: © 2009 Joost van Baal
# This program is in the public domain.
#
# homsar.uvt.nl:/usr/local/bin/mpd-unsort - by Wessel Dankers
#
# ma 27 11:11 < joostvb> Fruit: Is homsar:/usr/local/bin/mpd-unsort GPL-ed?
# ma 27 11:13 < Fruit> joostvb: eh nee, public domain
# ma 27 11:13 < joostvb> Fruit: ok, thanks!
#  april 2009 [11:14] [joostvb(+i)] [5:meuknet/#uvt] [Act: 3,14]

# unsort doet eerlijk mengen van 2 playlists.
#   of:
# za 05 07:17 < joostvb> Fruit: in mpd's src/playlist.c, naast int
#                       shufflePlaylist(int fd), moet een int
# za 05 07:17 < joostvb> unsortPlaylist(int fd) komen.
# za 05 07:17 < joostvb> Fruit: ja echt
# za 05 07:17 < joostvb> damnit
# za 05 07:17 < joostvb> en t protocol moet dan ook nog uitgebreid worden.
#                        command unsort naast command shuffle
# .
# > laat draai in /var/lib/mpd/playlists krassen, en gebruik op die
# > manier unsort.  playlists exporteren over nfs indien nodig.
# .
# Tue 29 13:39 < joostvb> maar ik heb toch schrijfrechten op
#                         homsar:/var/lib/mpd/playlists nodig?
# Tue 29 13:40 < Fruit> Toevoegen gebruiker `joostvb' aan groep `audio'...
# .
# ~/.draai/playlists should be symlink to /var/lib/mpd/playlists


playlists=${DR_PLAYLISTS:-/var/lib/mpd/playlists}

for uid in $UID $LOGNAME $USER;do :;done
prefix=${uid}_unsort_

unsort=${DR_UNSORT:-`command -v unsort`}

unset LANG LC_ALL

set -e

exec >/dev/null

current=$(mpc | sed -n 's|^\[[^]]*\] *#\([0-9]\+\)/.*$|\1|p')

case $current in *[!0-9]*|0*|'')
	echo "Can't get number of currently playing track ($current)" >&2
	exit 2
esac

if [ -f $playlists/${prefix}in.m3u ]
then
	mpc rm ${prefix}in
fi
mpc save ${prefix}in

trap 'rm -f $playlists/${prefix}head.m3u $playlists/${prefix}tail.m3u' EXIT

head -n $(( $current - 1 )) $playlists/${prefix}in.m3u >$playlists/${prefix}head.m3u

tail -n +$(( $current + 1 )) $playlists/${prefix}in.m3u |
	$unsort "$@" >$playlists/${prefix}tail.m3u

mpc --no-status random off
while ! mpc crop
do
	sleep 1
done
mpc load ${prefix}head
mpc move 1 $current
mpc load ${prefix}tail
mpc rm ${prefix}in