#!/bin/sh
set -e

menu=wdmenu

search(){
    music=$(mpc playlist --format '%artist% : %title%' | sed '/^ : $/d' | $menu)
    if [ "$music" = "" ]
    then
        exit 1
    fi

    artist=$(echo "$music" | perl -pe 's/(.*) : (.*)/\1/')
    title=$(echo "$music"  | perl -pe 's/(.*) : (.*)/\2/')

    mpc --quiet searchplay artist "$artist" title "$title"
}

delete(){
    [ -n "$XDG_CONFIG_HOME" ] &&
      config_root="$XDG_CONFIG_HOME" ||
      config_root="$HOME/.config"
    music_root=$(awk '/^music_directory/ {
                        gsub(/"/,"");
                        gsub(/~/,"'$HOME'");
                        print $2
                      }' $config_root/mpd/mpd.conf)
    current="$music_root"/"$(mpc current -f %file%)"
    answer=$(printf "nothing\n$current" | $menu -p"delete?" )
    if [ "$answer" = "$current" ]
    then
        trash "$answer"
        mpc --quiet next
        mpc --quiet update
    fi
}

usage(){
    cmdname=$(basename "$0")
    echo "Commands: "
    echo "  $cmdname search     -- Searches the current playlist for songs and plays it."
    echo "  $cmdname delete     -- Prompts to delete the current song."
}

case "$1" in
    delete)
        delete ;;
    search)
        search ;;
    *)
        usage
        search
        ;;
esac
