#!/usr/bin/env bash
# gig_record.sh — lean, always-on stereo master capture (compressed, black-box style).
# NOT a replacement for the Ardour multitrack session — that's the pristine, per-orbit
# archival copy. This is the cheap always-running safety net + the source for quick
# 1-minute slop-visuals test slices, so a take never goes uncaptured.
#
# Usage:
#   gig_record.sh start          start recording in the background (opus, hourly segments)
#   gig_record.sh stop           stop the background recorder
#   gig_record.sh status         is it running? which file? how big?
#   gig_record.sh slice FILE START_SEC MINUTES OUT   fast lossless-cut a test excerpt
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_DIR="$DIR/recordings"
PID_FILE="$OUT_DIR/.recorder.pid"
LOG_FILE="$OUT_DIR/recorder.log"
BITRATE="${GIG_RECORD_BITRATE:-160k}"
SEGMENT_SECS="${GIG_RECORD_SEGMENT:-3600}"

mkdir -p "$OUT_DIR"

default_monitor() {
    local sink
    sink="$(pactl get-default-sink 2>/dev/null)"
    [ -n "$sink" ] || { echo "gig_record: no default sink found" >&2; return 1; }
    echo "${sink}.monitor"
}

cmd_start() {
    if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        echo "gig_record: already running (pid $(cat "$PID_FILE"))"
        return 0
    fi
    local monitor
    monitor="$(default_monitor)" || return 1
    echo "gig_record: capturing '$monitor' -> $OUT_DIR/%Y-%m-%d_%H%M%S.opus (opus @ $BITRATE, ${SEGMENT_SECS}s segments)"
    nohup ffmpeg -nostdin -loglevel warning \
        -f pulse -i "$monitor" \
        -c:a libopus -b:a "$BITRATE" -vbr on \
        -f segment -segment_time "$SEGMENT_SECS" -strftime 1 \
        "$OUT_DIR/%Y-%m-%d_%H%M%S.opus" \
        >>"$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    disown
    echo "gig_record: started (pid $(cat "$PID_FILE"))"
}

cmd_stop() {
    if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        kill "$(cat "$PID_FILE")"
        rm -f "$PID_FILE"
        echo "gig_record: stopped"
    else
        echo "gig_record: not running"
        rm -f "$PID_FILE"
    fi
}

cmd_status() {
    if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        echo "gig_record: RUNNING (pid $(cat "$PID_FILE"))"
        ls -lh "$OUT_DIR"/*.opus 2>/dev/null | tail -3
        du -sh "$OUT_DIR" 2>/dev/null
    else
        echo "gig_record: not running"
    fi
}

# Fast, lossless (stream-copy) excerpt for auditioning / slop-visuals testing.
cmd_slice() {
    local file="$1" start="$2" minutes="$3" out="${4:-}"
    [ -f "$file" ] || { echo "gig_record: no such file: $file" >&2; return 1; }
    [ -n "$out" ] || out="$OUT_DIR/slice_$(basename "$file" .opus)_${start}s_${minutes}m.opus"
    ffmpeg -nostdin -loglevel warning -y -ss "$start" -t "$((minutes * 60))" -i "$file" -c copy "$out"
    echo "gig_record: wrote $out"
}

case "${1:-}" in
    start)  cmd_start ;;
    stop)   cmd_stop ;;
    status) cmd_status ;;
    slice)  shift; cmd_slice "$@" ;;
    *) echo "usage: $0 {start|stop|status|slice FILE START_SEC MINUTES [OUT]}" >&2; exit 1 ;;
esac
