#!/usr/bin/env bash
set -euo pipefail

DEFAULT_SECONDS="${SG_AUDIO_RECORD_SECONDS:-10}"
DEFAULT_RATE="${SG_AUDIO_RATE:-48000}"
DEFAULT_FORMAT="${SG_AUDIO_FORMAT:-S16_LE}"
DEFAULT_CHANNELS="${SG_AUDIO_CHANNELS:-2}"

pcm_dev(){ sg-audio pcm; }

record_direct() {
    local profile="$1" seconds="$2" output="$3" rate="${4:-$DEFAULT_RATE}" fmt="${5:-$DEFAULT_FORMAT}"
    local pcm
    pcm="$(pcm_dev)"
    sg-audio "$profile"
    echo "=================================================="
    echo "Recording starts now. Please speak now."
    echo "Profile : $profile"
    echo "Output  : $output"
    echo "Format  : ${rate} Hz, ${fmt}, ${DEFAULT_CHANNELS} channel(s)"
    echo "Note    : V34 does not trim or discard any recorded audio."
    echo "=================================================="
    arecord -D "$pcm" -f "$fmt" -r "$rate" -c "$DEFAULT_CHANNELS" -d "$seconds" "$output"
    ls -lh "$output"
}

play_file() {
    local file="$1" profile="${2:-hp}" pcm
    [[ -f "$file" ]] || { echo "ERROR: file not found: $file" >&2; exit 1; }
    pcm="$(pcm_dev)"
    sg-audio "$profile" >/dev/null || true
    aplay -D "$pcm" "$file"
}

usage() {
    cat <<'USAGE'
Usage:
  sg-audio-test hp [file.wav]               # play WAV through headphone output
  sg-audio-test spk [file.wav]              # play WAV through DA7212 SPK / Lineout output
  sg-audio-test mp3 <file.mp3>              # play MP3 through DA7212 explicitly
  sg-audio-test headset-mic                 # headset MIC / MIC1 test, no trimming
  sg-audio-test headset-mic-ref             # raw reference profile test, no trimming
  sg-audio-test headset-compare             # record both headset MIC modes, no trimming
  sg-audio-test aux                         # AUX input recording test, no trimming
  sg-audio-test onboard-mic                 # two onboard MICs together: MIC2_P + MIC2_N differential, no trimming
  sg-audio-test onboard-mic-p               # onboard MIC U1 / MIC2_P single-MIC test, no trimming
  sg-audio-test onboard-mic-n               # onboard MIC U2 / MIC2_N single-MIC test, no trimming
  sg-audio-test onboard-mic-compare         # record U1 and U2 separately, no trimming
  sg-audio-test onboard-mic-diff            # alias of onboard-mic, two-MIC combined mode
  sg-audio-test leds                        # blink green and blue LEDs
  sg-audio-test button [seconds]            # wait for the D27 button press
  sg-audio-test capture-info

Playback volume:
  DA7212 DAC playback volume is capped at 100 in V34.

Environment:
  SG_AUDIO_RECORD_SECONDS=10                # recording duration in seconds
  SG_AUDIO_RATE=48000                       # sample rate
  SG_AUDIO_FORMAT=S16_LE                    # sample format
  SG_AUDIO_CHANNELS=2                       # 2 = dual-mono/stereo WAV, 1 = mono WAV

Notes:
  This V34 test utility does not call sox trim and does not discard the beginning
  of the recording. Start speaking after the "Recording starts now" prompt.
USAGE
}

capture_info() {
    local idx
    idx="$(sg-audio card)"
    echo "CARD_ID=$(sg-audio card-id)"
    echo "CARD_INDEX=$idx"
    echo "PCM=$(sg-audio pcm)"
    echo
    echo "=== /proc/asound/cards ==="
    cat /proc/asound/cards || true
    echo
    echo "=== playback devices ==="
    aplay -l || true
    echo
    echo "=== capture devices ==="
    arecord -l || true
    echo
    echo "=== capture hw_params ==="
    cat "/proc/asound/card${idx}/pcm0c/sub0/hw_params" 2>/dev/null || true
    echo
    echo "=== playback hw_params ==="
    cat "/proc/asound/card${idx}/pcm0p/sub0/hw_params" 2>/dev/null || true
    echo
    echo "=== /etc/asound.conf ==="
    cat /etc/asound.conf 2>/dev/null || true
}

case "${1:-}" in
    aux)
        out="/tmp/sg_aux_48k_s16.wav"
        record_direct aux "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    headset-mic)
        out="/tmp/sg_headset_mic_fixed_48k_s16.wav"
        record_direct headset-mic "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    headset-mic-ref)
        out="/tmp/sg_headset_mic_ref_48k_s16.wav"
        record_direct headset-mic-ref "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    headset-compare)
        record_direct headset-mic "$DEFAULT_SECONDS" "/tmp/sg_headset_mic_fixed_48k_s16.wav" 48000 S16_LE
        record_direct headset-mic-ref "$DEFAULT_SECONDS" "/tmp/sg_headset_mic_ref_48k_s16.wav" 48000 S16_LE
        echo "Generated:"
        echo "  /tmp/sg_headset_mic_fixed_48k_s16.wav"
        echo "  /tmp/sg_headset_mic_ref_48k_s16.wav" ;;
    onboard-mic|onboard-mic2|onboard-mic-diff)
        out="/tmp/sg_onboard_mic_two_mics_diff_48k_s16.wav"
        record_direct onboard-mic-diff "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    onboard-mic-p)
        out="/tmp/sg_onboard_mic_u1_mic2_p_48k_s16.wav"
        record_direct onboard-mic-p "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    onboard-mic-n)
        out="/tmp/sg_onboard_mic_u2_mic2_n_48k_s16.wav"
        record_direct onboard-mic-n "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    onboard-mic-compare|onboard-compare)
        record_direct onboard-mic-p "$DEFAULT_SECONDS" "/tmp/sg_onboard_mic_u1_mic2_p_48k_s16.wav" 48000 S16_LE
        record_direct onboard-mic-n "$DEFAULT_SECONDS" "/tmp/sg_onboard_mic_u2_mic2_n_48k_s16.wav" 48000 S16_LE
        echo "Generated:"
        echo "  /tmp/sg_onboard_mic_u1_mic2_p_48k_s16.wav"
        echo "  /tmp/sg_onboard_mic_u2_mic2_n_48k_s16.wav" ;;
    onboard-mic-diff)
        out="/tmp/sg_onboard_mic2_diff_48k_s16.wav"
        record_direct onboard-mic-diff "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    onboard-mic1)
        out="/tmp/sg_onboard_mic1_48k_s16.wav"
        record_direct onboard-mic1 "$DEFAULT_SECONDS" "$out" 48000 S16_LE
        play_file "$out" ;;
    hp|play)
        play_file "${2:-/usr/local/share/sg-da7212/test_audio/aux_in.wav}" hp ;;
    spk|speaker)
        play_file "${2:-/usr/local/share/sg-da7212/test_audio/aux_in.wav}" spk ;;
    tone)
        pcm="$(pcm_dev)"
        sg-audio hp >/dev/null || true
        speaker-test -D "$pcm" -c 2 -t sine -f "${2:-1000}" -l 1 ;;
    mp3)
        file="${2:-}"
        [[ -n "$file" && -f "$file" ]] || { echo "ERROR: MP3 file required." >&2; exit 2; }
        sg-audio hp >/dev/null || true
        mpg123 -o alsa -a "$(pcm_dev)" "$file" ;;
    leds)
        echo "Testing green LED on BCM23..."
        sg-audio led green blink 3
        echo "Testing blue LED on BCM24..."
        sg-audio led blue blink 3
        echo "Testing both LEDs..."
        sg-audio led all blink 3 ;;
    button)
        sg-audio button status
        sg-audio button wait "${2:-10}" ;;
    capture-info) capture_info ;;
    *) usage; exit 2 ;;
esac
