#!/usr/bin/env bash
# ~/Projects/cuesplit/run — task dispatcher (symlinked into ~/.local/bin)
# Usage: run split
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
CUESPLIT_PY="$SCRIPT_DIR/cuesplit.py"

cmd_split() {
    # Find exactly one .cue file in the current directory
    shopt -s nullglob
    cues=(*.cue *.CUE)
    shopt -u nullglob

    if [ ${#cues[@]} -eq 0 ]; then
        echo "No .cue file found in $(pwd)"
        exit 1
    fi

    if [ ${#cues[@]} -gt 1 ]; then
        echo "Multiple .cue files found, pick one:"
        select cue in "${cues[@]}"; do
            [ -n "$cue" ] && break
        done
    else
        cue="${cues[0]}"
    fi

    echo "Using cue: $cue"
    python3 "$CUESPLIT_PY" "$cue" split

    echo "Opening split/ in Picard..."
    picard "$(pwd)/split" >/dev/null 2>&1 &
    disown
}

case "${1:-}" in
    split)
        cmd_split
        ;;
    *)
        echo "Usage: run <command>"
        echo "Commands:"
        echo "  split   - auto-find .cue in current dir and split the audio"
        exit 1
        ;;
esac
