#!/bin/bash
set -euo pipefail

###############################################################################
# Internet Radio Appliance Provisioner
# Debian 13
#
# Station: Smooth 95.3 Sydney
# Player:  mpv -> ALSA
# Cache:   60 seconds
###############################################################################

STREAM_URL='https://playerservices.streamtheworld.com/api/livestream-redirect/SMOOTH953_AAC320.aac'
CACHE_SECS='60'
RESTART_DELAY='2'
DEFAULT_VOLUME='60'

CONFIG_DIR='/etc/internet-radio'
CONFIG_FILE="${CONFIG_DIR}/radio.conf"
PLAYER='/usr/local/sbin/internet-radio-player'
VOLUME_TOOL='/usr/local/sbin/radio-volume'
SERVICE='/etc/systemd/system/internet-radio.service'

echo
echo "============================================================"
echo " Internet Radio Appliance Provisioning"
echo "============================================================"
echo

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: Run this script as root." >&2
    exit 1
fi

echo "[1/8] Installing required packages..."
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
    mpv \
    alsa-utils \
    ca-certificates \
    curl

echo
echo "[2/8] Detecting ALSA hardware..."

if ! grep -q '^[[:space:]]*[0-9]' /proc/asound/cards 2>/dev/null; then
    echo "ERROR: No ALSA sound card was detected."
    echo
    echo "Detected PCI audio hardware:"
    lspci -nn | grep -i -E 'audio|multimedia' || true
    exit 1
fi

cat /proc/asound/cards
echo
aplay -l || true

CARD=0

CONTROL=''
for candidate in Master Speaker Headphone PCM; do
    if amixer -c "$CARD" scontrols 2>/dev/null |
       grep -Fq "Simple mixer control '$candidate',0"; then
        CONTROL="$candidate"
        break
    fi
done

if [ -z "$CONTROL" ]; then
    echo
    echo "ERROR: Could not find a suitable ALSA playback volume control."
    echo "Available controls:"
    amixer -c "$CARD" scontrols || true
    exit 1
fi

echo
echo "Using ALSA card:    $CARD"
echo "Using volume control: $CONTROL"

echo
echo "[3/8] Creating radio configuration..."
install -d -m 0755 "$CONFIG_DIR"

cat >"$CONFIG_FILE" <<EOF
# Internet Radio Appliance configuration
STREAM_URL='$STREAM_URL'
CACHE_SECS='$CACHE_SECS'
RESTART_DELAY='$RESTART_DELAY'
ALSA_CARD='$CARD'
ALSA_CONTROL='$CONTROL'
EOF

chmod 0644 "$CONFIG_FILE"

echo
echo "[4/8] Creating player launcher..."

cat >"$PLAYER" <<'EOF'
#!/bin/bash
set -euo pipefail

CONFIG='/etc/internet-radio/radio.conf'

if [ ! -r "$CONFIG" ]; then
    echo "Configuration file not found: $CONFIG" >&2
    exit 1
fi

. "$CONFIG"

: "${STREAM_URL:?STREAM_URL is not configured}"
: "${CACHE_SECS:=60}"
: "${ALSA_CARD:=0}"

exec /usr/bin/mpv \
    --no-video \
    --ao=alsa \
    --audio-device="alsa/default:CARD=${ALSA_CARD}" \
    --cache=yes \
    --cache-secs="$CACHE_SECS" \
    --ytdl=no \
    "$STREAM_URL"
EOF

chmod 0755 "$PLAYER"

echo
echo "[5/8] Creating persistent remote volume command..."

cat >"$VOLUME_TOOL" <<'EOF'
#!/bin/bash
set -euo pipefail

CONFIG='/etc/internet-radio/radio.conf'

if [ ! -r "$CONFIG" ]; then
    echo "Configuration file not found: $CONFIG" >&2
    exit 1
fi

. "$CONFIG"

CARD="${ALSA_CARD:-0}"
CONTROL="${ALSA_CONTROL:-Master}"

usage() {
    cat <<USAGE
Usage:
  radio-volume          Show current volume
  radio-volume <0-100>  Set volume percentage
  radio-volume +<n>     Increase by n percentage points
  radio-volume -<n>     Decrease by n percentage points
  radio-volume mute     Mute output
  radio-volume unmute   Unmute output
USAGE
}

show_volume() {
    local output
    output="$(amixer -c "$CARD" sget "$CONTROL")"

    local line
    line="$(printf '%s\n' "$output" |
        grep -m1 -E 'Playback.*\[[0-9]+%\].*\[(on|off)\]' || true)"

    if [ -z "$line" ]; then
        echo "Mixer: $CONTROL"
        printf '%s\n' "$output"
        return
    fi

    local pct state
    pct="$(printf '%s\n' "$line" |
        grep -oE '\[[0-9]+%\]' | head -1 | tr -d '[]')"
    state="$(printf '%s\n' "$line" |
        grep -oE '\[(on|off)\]' | tail -1 | tr -d '[]')"

    echo "Radio volume: ${pct:-unknown}  ${state:-unknown}"
}

save_state() {
    alsactl store "$CARD" >/dev/null 2>&1 || true
}

if [ "$#" -eq 0 ]; then
    show_volume
    exit 0
fi

if [ "$#" -ne 1 ]; then
    usage >&2
    exit 2
fi

case "$1" in
    mute)
        amixer -q -c "$CARD" sset "$CONTROL" mute
        ;;
    unmute)
        amixer -q -c "$CARD" sset "$CONTROL" unmute
        ;;
    +[0-9]*)
        STEP="${1#+}"
        if ! [[ "$STEP" =~ ^[0-9]+$ ]] || [ "$STEP" -gt 100 ]; then
            echo "Invalid adjustment: $1" >&2
            exit 2
        fi
        amixer -q -c "$CARD" sset "$CONTROL" "${STEP}%+"
        ;;
    -[0-9]*)
        STEP="${1#-}"
        if ! [[ "$STEP" =~ ^[0-9]+$ ]] || [ "$STEP" -gt 100 ]; then
            echo "Invalid adjustment: $1" >&2
            exit 2
        fi
        amixer -q -c "$CARD" sset "$CONTROL" "${STEP}%-"
        ;;
    *)
        if [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -le 100 ]; then
            amixer -q -c "$CARD" sset "$CONTROL" "$1%" unmute
        else
            echo "Invalid volume setting: $1" >&2
            usage >&2
            exit 2
        fi
        ;;
esac

save_state
show_volume
EOF

chmod 0755 "$VOLUME_TOOL"

echo
echo "[6/8] Configuring initial mixer state..."

if [ ! -s /var/lib/alsa/asound.state ]; then
    amixer -q -c "$CARD" sset "$CONTROL" "${DEFAULT_VOLUME}%" unmute || true
    alsactl store "$CARD" >/dev/null 2>&1 || true
else
    amixer -q -c "$CARD" sset "$CONTROL" unmute || true
    alsactl store "$CARD" >/dev/null 2>&1 || true
fi

echo
echo "[7/8] Creating systemd service..."

cat >"$SERVICE" <<'EOF'
[Unit]
Description=Internet Radio Appliance
Wants=network-online.target
After=network-online.target sound.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/internet-radio-player
Restart=always
RestartSec=2
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable internet-radio.service

echo
echo "[8/8] Starting radio..."
systemctl restart internet-radio.service

sleep 5

echo
echo "============================================================"
echo " Provisioning complete"
echo "============================================================"
echo

echo "ALSA hardware:"
cat /proc/asound/cards
echo

echo "Playback devices:"
aplay -l || true
echo

echo "Selected mixer:"
echo "  Card:    $CARD"
echo "  Control: $CONTROL"
echo

echo "Current volume:"
"$VOLUME_TOOL" || true
echo

echo "Radio configuration:"
grep -E '^(STREAM_URL|CACHE_SECS|ALSA_CARD|ALSA_CONTROL)=' "$CONFIG_FILE"
echo

echo "Radio service:"
systemctl --no-pager --full status internet-radio.service || true

echo
echo "Useful commands:"
echo
echo "  radio-volume"
echo "  radio-volume 60"
echo "  radio-volume +5"
echo "  radio-volume -5"
echo "  radio-volume mute"
echo "  radio-volume unmute"
echo
echo "  systemctl status internet-radio"
echo "  systemctl restart internet-radio"
echo "  journalctl -u internet-radio -f"
echo
echo "After checking the physical output, perform a reboot test:"
echo
echo "  reboot"
echo
echo "Then verify:"
echo
echo "  radio-volume"
echo "  systemctl status internet-radio --no-pager"
echo
