#!/bin/sh
# S70mestre-audio — X6200 audio hardware init
#
# Initializes the X6200's audio routing via I2C:
#   1. Calls x6200_control_init() to establish MCU state
#   2. Sets speaker volume
#   3. Switches audio routing from RX-radio to SoC DAC (voice_rec)
#
# Must run after S50pulseaudio (pulseaudio must hold PCM open first
# to keep ALSA clocks active).
#
# The voice_rec bit (0x00008 in sple_atue_trx register, cmd 12)
# switches the X6200's internal audio mux from the RF receiver
# to the SoC DAC — allowing piHPSDR/aplay to be heard in the speaker.

VOLUME=50

do_init() {
    python3 << EOF
import ctypes
lib = ctypes.CDLL("libaether_x6200_control.so")
lib.x6200_control_init.restype = ctypes.c_bool
lib.x6200_control_rxvol_set.argtypes = [ctypes.c_uint8]
lib.x6200_control_spmode_set.argtypes = [ctypes.c_bool]

if not lib.x6200_control_init():
    raise SystemExit("x6200_control_init() failed")

lib.x6200_control_rxvol_set($VOLUME)
lib.x6200_control_spmode_set(False)  # Speaker mode (not headphone)
EOF
}

do_voice_rec() {
    # Switch audio routing: RX-radio -> SoC DAC (voice_rec bit = 0x00008)
    i2ctransfer -y 0 w6@0x72 0x00 0x30 0x08 0x00 0x00 0x00
}

case "$1" in
    start)
        echo "Starting mestre-audio"
        do_init && do_voice_rec && echo "OK" || echo "FAILED"
        ;;
    stop)
        echo "Stopping mestre-audio"
        # Switch back to RX-radio audio
        i2ctransfer -y 0 w6@0x72 0x00 0x30 0x00 0x00 0x00 0x00
        echo "OK"
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}" >&2
        exit 1
        ;;
esac
