#!/bin/bash
# onset-detect: Find first audio onset (first "good note") in a file
# Usage: onset-detect <audio_file> [threshold_db=-40] [min_duration=0.1]
#
# Returns the timestamp of the first significant audio onset
# Useful for trimming silence at the start of a recording

set -euo pipefail

FILE="${1:?Usage: onset-detect <audio_file> [threshold_db=-40] [min_duration=0.1]}"
THRESHOLD="${2:--40}"
MIN_DUR="${3:-0.1}"

if [[ ! -f "$FILE" ]]; then
    echo "Error: File not found: $FILE" >&2
    exit 1
fi

# Method 1: Use ffmpeg silencedetect to find end of initial silence
ONSET=$(ffmpeg -i "$FILE" -af "silencedetect=noise=${THRESHOLD}dB:d=${MIN_DUR}" -f null - 2>&1 | \
    grep "silence_end" | head -1 | sed 's/.*silence_end: \([0-9.]*\).*/\1/')

if [[ -n "$ONSET" ]]; then
    # Format nicely
    ONSET_INT=${ONSET%.*}
    ONSET_MS=$(echo "$ONSET" | sed 's/.*\.//' | head -c3)
    printf "First onset: %.3fs (%02d:%02d.%s)\n" "$ONSET" $((ONSET_INT/60)) $((ONSET_INT%60)) "$ONSET_MS"

    # Also show what's at that point
    echo ""
    echo "Audio at onset point:"
    sox "$FILE" -n trim "$ONSET" 1 stats 2>&1 | grep -E "RMS lev|Pk lev"

    # Output just the timestamp for piping
    echo ""
    echo "ONSET_TIMESTAMP=$ONSET"
else
    echo "No onset detected (file may start with audio or be silent)"
    echo "ONSET_TIMESTAMP=0"
fi
