#!/bin/bash

#
# Remove or move the current playing cmus track and play the next track.
#
# Usage:
#   cmus-track rm
#   cmus-track mv path/to/new/dir
#

function get_field() {
    local row
    row="$(grep "^$1 " <<<"$QUERY_RESULT")"
    echo "${row#"$1 "}"
}

QUERY_RESULT="$(cmus-remote --query 2>/dev/null)"
[ -z "$QUERY_RESULT" ] && exit 1

FILE="$(get_field file)"

ACTION="$1"
if [ "$ACTION" == "rm" ]; then
    rm -vI "$FILE"
    cmus-remote --next
elif [ "$ACTION" == "mv" ]; then
    TARGET_DIR="${2}"
    if ! [ -d "$TARGET_DIR" ]; then
        echo "ERROR: TARGET_DIR doesn't exist: '$TARGET_DIR'." 1>&2
        exit 3
    fi

    mv -iv "$FILE" "$TARGET_DIR" || exit 4
else
    echo "ERROR: Unsupported action '$ACTION'." 1>&2
    exit 2
fi
