#!/bin/bash
#
# start-raat.sh - RAAT startup script with Avahi availability check
# This script handles startup of RAAT with Avahi daemon availability verification
#
# Version: 1.0.0
# Changelog:
# - v1.0.0: Initial version with Avahi daemon availability check
#           Waits up to 30 seconds for Avahi to become responsive
#           Ensures reliable mDNS functionality before starting RAAT
#

# MDNS backend - RAAT uses Avahi for mDNS discovery
MDNS_BACKEND="avahi"

# User validation check
# Allow running as root, or as the user specified in /etc/hifiberry.user
CURRENT_USER=$(whoami)
if [ "$CURRENT_USER" != "root" ]; then
    if [ -f "/etc/hifiberry.user" ]; then
        AUTHORIZED_USER=$(cat /etc/hifiberry.user 2>/dev/null | tr -d '\n\r ')
        if [ "$CURRENT_USER" != "$AUTHORIZED_USER" ]; then
            echo "Error: not starting raat, this should run as user $AUTHORIZED_USER"
            exit 0
        fi
    else
        echo "Error: not starting raat, /etc/hifiberry.user not found and not running as root"
        exit 0
    fi
fi

# Sound card detection check
echo "Checking for sound card..."
if ! /usr/bin/config-soundcard --detect >/dev/null 2>&1; then
    echo "No sound card detected, not starting raat"
    exit 0
fi
echo "Sound card detected successfully."

# Check if Avahi daemon is running when MDNS_BACKEND is set to avahi
# This ensures RAAT has functioning mDNS capabilities before starting
# We check both that the process exists and that it's actually responding to queries
if [ "$MDNS_BACKEND" = "avahi" ]; then
  echo "Checking if Avahi daemon is running..."
  ATTEMPTS=0
  MAX_ATTEMPTS=6  # 6 attempts x 5 seconds = 30 seconds max wait time
  
  while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
    # Check if avahi-daemon is running and listening
    if pgrep avahi-daemon >/dev/null && avahi-browse -a -t >/dev/null 2>&1; then
      echo "Avahi daemon is running and responding."
      break
    else
      ATTEMPTS=$((ATTEMPTS + 1))
      if [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; then
        echo "Avahi daemon is not ready. Waiting 5 seconds... (Attempt $ATTEMPTS/$MAX_ATTEMPTS)"
        sleep 5
      else
        echo "Warning: Avahi daemon is not running or not responding after 30 seconds."
        echo "RAAT may have limited mDNS functionality."
      fi
    fi
  done
fi

# Determine config path: per-user (~/.raat) for user service, fallback to /var/lib/raat
CONFIG_DIR="/var/lib/raat"
if [ -n "${XDG_RUNTIME_DIR:-}" ] || [ -n "${XDG_SESSION_ID:-}" ]; then
  # Likely running as a user service/session
  CONFIG_DIR="$HOME/.raat"
fi

# Check if /var/lib/raat is writable for metadata pipe functionality
if [ ! -w "/var/lib/raat" ] && [ ! -w "/var/lib" ]; then
  echo "Error: /var/lib/raat is not writable by the current user"
  echo "Error: metadata pipe won't be available"
fi

# Ensure config directory exists
mkdir -p "$CONFIG_DIR"

# Configure RAAT before starting (write explicit output under CONFIG_DIR)
echo "Configuring RAAT in $CONFIG_DIR ..."
CFG_ARG="$CONFIG_DIR/hifiberry.conf"
RAAT_CONFIG_DIR="$CONFIG_DIR" /usr/bin/configure-raat -o "$CFG_ARG"

# Start RAAT with the resolved config and trace logging enabled
echo "Starting RAAT with config: $CFG_ARG (trace logging enabled)"
exec /usr/bin/raat_app --trace "$CFG_ARG"
