#!/bin/sh
# Prepare the radio volumes, start the in-container Icecast server, wire up
# PulseAudio and exec liquidsoap. Existing files are never overwritten -
# live-edited script/params/playlists always win.
set -e

DATA="${RADIO_DATA_DIR:-/srv/betoniarka/data}"
MUSIC="${RADIO_MUSIC_DIR:-/srv/betoniarka/music}"
SECRETS="${RADIO_SECRETS_DIR:-/srv/betoniarka/secrets}"
CREDS="$SECRETS/icecast_credentials.json"
mkdir -p "$DATA" "$MUSIC" "$SECRETS"

# Seed the script + persistent interactive params from the image on first run.
[ -e "$DATA/radio_conjurer.liq" ] || cp /app/radio_conjurer.liq "$DATA/"
if [ ! -e "$DATA/script.params" ]; then
    if [ -e /app/script.params ]; then cp /app/script.params "$DATA/"; else : > "$DATA/script.params"; fi
fi

# Playlists + logs the script watches/writes; empty files keep it happy until
# the musician/betoniarka populate them.
for f in all_playlist.playlist priority_queue.playlist hit.playlist \
         request.playlist jingles.playlist persistence.log; do
    [ -e "$DATA/$f" ] || : > "$DATA/$f"
done

# The icecast secret is provisioned at install time, like the other services'
# secrets (bot: /srv/conjurer/secrets/.netrc). A placeholder keeps the stack
# bootable, but both icecast and the stream stay locked until you fix it.
if [ ! -e "$CREDS" ]; then
    printf '{\n"password" : "CHANGE_ME"\n}\n' > "$CREDS"
    echo "WARNING: $CREDS was missing - seeded a CHANGE_ME placeholder." >&2
    echo "         Put the real password there (see docs) and restart." >&2
fi

# Render /etc/icecast2/icecast.xml from the template with passwords from the
# secret. Optional fields admin_password/relay_password default to password.
SOURCE_PW=$(jq -r '.password' "$CREDS")
ADMIN_PW=$(jq -r '.admin_password // .password' "$CREDS")
RELAY_PW=$(jq -r '.relay_password // .password' "$CREDS")
ICECAST_HOSTNAME="${ICECAST_HOSTNAME:-localhost}"
sed -e "s|__SOURCE_PASSWORD__|$SOURCE_PW|" \
    -e "s|__ADMIN_PASSWORD__|$ADMIN_PW|" \
    -e "s|__RELAY_PASSWORD__|$RELAY_PW|" \
    -e "s|__HOSTNAME__|$ICECAST_HOSTNAME|" \
    /app/icecast.xml.tpl > /etc/icecast2/icecast.xml
chown icecast2:icecast /etc/icecast2/icecast.xml 2>/dev/null || true
chmod 640 /etc/icecast2/icecast.xml

# Start Icecast in the background as its unprivileged user.
mkdir -p /var/log/icecast2 && chown -R icecast2:icecast /var/log/icecast2
su -s /bin/sh icecast2 -c "icecast2 -b -c /etc/icecast2/icecast.xml" \
    || echo "WARNING: icecast2 failed to start - the stream output will retry" >&2

# single() aborts the whole script when its file is missing; guarantee the
# emergency fallback exists (5s of silence beats a dead radio).
EMERGENCY="$MUSIC/Youtube/Dr. Peacock - Trip to Ireland [GvrvQTUbUcA].mp3"
if [ ! -e "$EMERGENCY" ]; then
    mkdir -p "$MUSIC/Youtube"
    if ffmpeg -loglevel error -f lavfi -i anullsrc=r=44100:cl=stereo -t 5 \
              -codec:a libmp3lame -q:a 9 "$EMERGENCY"; then
        echo "WARNING: emergency track was missing - generated silent placeholder" >&2
    else
        echo "WARNING: could not create emergency track; single() may abort" >&2
    fi
fi

# PulseAudio wiring:
#   internal (default) - system-wide pulse inside the container with a null
#                        sink (see /etc/pulse/system.pa); no sound hardware
#                        needed, mic path reads silence.
#   host               - use a socket mounted from the host; set PULSE_SERVER
#                        (e.g. unix:/tmp/pulseaudio.socket) in the env file.
#   none               - you edited the script to drop pulse in/out.
case "${PULSE_MODE:-internal}" in
    internal)
        # --disallow-module-loading: modules from system.pa still load at
        # startup; this only blocks later client-requested loads (and
        # silences the system-mode warning). The "forcibly disabling SHM"
        # notice is inherent to system mode and harmless.
        pulseaudio --system --daemonize=yes --disallow-exit \
            --disallow-module-loading --exit-idle-time=-1 \
            || echo "WARNING: internal pulseaudio failed to start" >&2
        export PULSE_SERVER="${PULSE_SERVER:-unix:/var/run/pulse/native}"
        ;;
    host)
        [ -n "$PULSE_SERVER" ] || echo "WARNING: PULSE_MODE=host but PULSE_SERVER is unset" >&2
        ;;
    none)
        ;;
esac

# Liquidsoap refuses to run as root (init: security exit), so hand the data
# volume to the dedicated 'radio' user and drop privileges for the main
# process. chown is best-effort: on local volumes it always works (the
# supported layout); network filesystems with root-squash reject it, hence
# the warning instead of a fatal abort.
chown -R radio:radio "$DATA" 2>/dev/null \
    || echo "WARNING: chown of $DATA failed (network FS?) - keep this volume LOCAL to the radio VM" >&2
chgrp radio "$CREDS" 2>/dev/null && chmod 640 "$CREDS" || true
if ! setpriv --reuid radio --regid radio --init-groups -- test -r "$MUSIC"; then
    echo "WARNING: music dir $MUSIC is not readable by the 'radio' user" >&2
fi

# Betoniarka: the radio-operator API + radio-log forwarder, running as the
# SAME user as liquidsoap on the SAME volume - this is what makes the old
# musician-writes-as-root-over-network-share permission mess go away.
BETONIARKA_DATA="$DATA" BETONIARKA_MUSIC="$MUSIC" \
    setpriv --reuid radio --regid radio --init-groups -- \
    python3 /app/betoniarka.py &
echo "betoniarka started (pid $!)"

cd "$DATA"
exec setpriv --reuid radio --regid radio --init-groups -- "$@"
