#!/bin/sh
# Playlist management
# optdepends: highlight python
# env: MUSIC
test $# -gt 0 && command=$1 && shift
test "$1" = '-v' && verbose='true' && shift || verbose='false'
case $command in
  (update)
    for pl; do
      highlight $pl
      cat $pl | rev | cut -d'/' -f-2 | rev | while read f; do
          $verbose && printf "\e[31;1mSearching for '$f'\e[0m\n" >&2
          test -n "$f" || continue
          newpath="$(find $MUSIC -path "*${f#*../}" -prune | grep . || find $MUSIC -path "*${f##* - }" -o -path "*${f##*/}" | grep -m 1 .)"
          $verbose && printf "\e[31;1mFound '$newpath'\e[0m\n" >&2
          test -n "$newpath" && realpath --relative-to $(dirname "$pl") "$newpath" || echo "$f"
        done | tee $pl
    done;;
  (edit) ${EDITOR:-nano} $(find $MUSIC/Playlists -iname "$1\.*" | grep . || find $MUSIC/Playlists -iname "$1*");;
  (make)
    if test $1 = d
    then shift && i=1; while test $i -le ${1:-9}; do $0 make "${2:-Ω}$i" "empty$i"; ((i++)); done
    else echo ${2:-empty} >$1.m3u8
    fi;;
  (fix) sed -i 's/.*\/musi[kc]/../g';;
  (cd) dir=${2:-cd}
    mkdir $dir
    cat $1 | python -c "import sys, urllib as ul; [sys.stdout.write(ul.unquote_plus(l)) for l in sys.stdin]" | sed '=' | sed -r 's/^[0-9]$/0\0/' | sed -r "N; s/(.*)\n(.*\/[0-9 ]*(.*))/'\2'\n'$dir\/\1 \3'/" | xargs -L 2 cp;;
  (*) echo "Unknown subcommand '$1' - Possible subcommands:
    update - update file paths for moved songs in a playlist
    edit - open playlist in default editor
    make - create an empty playlist with given name in current directory (optional second arg provides content)
    > d - creates up to 9 dummy files
    fix - replace absolute by relative paths for all given files (assumes library root at musi[kc] and playlist file one level below)
    cd - copy all songs of a playlist into a folder with indexed names, so they can easily be burned to a CD"
esac
