#!/usr/bin/env bash
# Update mpc database, adding all songs to the playlist, sorted by title
#. ~/lib/util.sh
current=$(mpc current -f '%file%')
mpc -q --wait update && {
	BASH_XTRACEFD=42
	mpc -q crop || mpc -q clear
	mpc add /
# sort playlist by title and artist
	sorted=$(mktemp)
#	mpc playlist -f '%title%[ - %artist%]\b%file%' \
#		| sed 1d \
#		| perl -e \
#			'sub f {
#				my $v = lc shift;
#				$v =~ s/^(a|the) //;
#				return $v;
#			}
#			print for sort {f($a) cmp f($b)} <>' \
#		| cut -d $'\b' -f 2- > "$sorted"
	mpc playlist -f '%artist%\b%album%\b%track%\b%title%\b%file%' \
		| sed 1d \
		| perl -w -e \
			'sub f {
				my $v = lc shift;
				$v =~ s/^(a|the) //;
				return $v;
			}
			print "$_\n" for
				map {$_->{file}}
				sort {$a->{artist} cmp $b->{artist}}
				sort {$a->{album} cmp $b->{album}}
				sort {$a->{track} <=> $b->{track}}
				sort {$a->{title} cmp $b->{title}}
				map {
					chomp;
					my @F = split(/\010/, $_);
					{
						artist => $F[0],
						album => $F[1],
						track => int $F[2],
						title => $F[3],
						file => $F[4],
					}
				}
				<>;
			' \
		| cut -d $'\b' -f 2- > "$sorted"
	mpc -q crop || mpc -q clear
	mpc add < "$sorted"
	rm -f "$sorted"
# remove duplicate of currently played song
	[[ $current ]] && mpc playlist -f '%file%' \
		| grep -Fxn "$current" | sed '1d; s/:.*//' | mpc del
	true
} 42>&2 >/dev/null 2>&1
