#!/bin/bash
#
# start-shairport.sh - Shairport Sync startup script
# This script handles startup of Shairport Sync with the system's pretty hostname
# as the AirPlay device name
#

# 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 shairport-sync, this should run as user $AUTHORIZED_USER"
            exit 0
        fi
    else
        echo "Error: not starting shairport-sync, /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 shairport-sync"
    exit 0
fi
echo "Sound card detected successfully."

# Default values
CONFIG_FILE="/etc/shairport-sync.conf"
# Use user-specific runtime directory for user service
if [ -n "${XDG_RUNTIME_DIR:-}" ] || [ -n "${XDG_SESSION_ID:-}" ]; then
  # Running as user service
  RUNTIME_DIR="${HOME}/.shairport"
else
  # Fallback to system directory
  RUNTIME_DIR="/var/lib/shairport"
fi
RUNTIME_CONFIG="${RUNTIME_DIR}/shairport-sync.conf"

# Function to extract version from config file
get_airplay_version() {
  local config_file="$1"
  
  if [ -f "$config_file" ] && grep -q 'version = "1"' "$config_file"; then
    echo "1"
  else
    echo "2"  # Default to AirPlay 2
  fi
}

# Get the pretty hostname first, then try normal hostname, and finally use HiFiBerry as fallback
PRETTY_HOSTNAME=$(hostnamectl hostname --pretty 2>/dev/null)
if [ $? -ne 0 ] || [ -z "$PRETTY_HOSTNAME" ]; then
  # Try to get normal hostname
  PRETTY_HOSTNAME=$(hostname 2>/dev/null)
  if [ $? -ne 0 ] || [ -z "$PRETTY_HOSTNAME" ]; then
    PRETTY_HOSTNAME="HiFiBerry"
  fi
fi

# Create runtime directory if it doesn't exist
if [ ! -d "$RUNTIME_DIR" ]; then
  mkdir -p "$RUNTIME_DIR"
  # Set appropriate permissions
  chmod 755 "$RUNTIME_DIR"
fi

# Update mixer control settings in a copy of the config file
if [ -f "$CONFIG_FILE" ] && [ -x /usr/bin/config-soundcard ]; then
  echo "Creating runtime configuration in $RUNTIME_CONFIG"
  
  # Copy the original config file to runtime location
  cp "$CONFIG_FILE" "$RUNTIME_CONFIG"
  
  # Add comment explaining the mechanism
  sed -i '1i// This is a runtime copy of shairport-sync.conf generated by start-shairport.sh\n// Do NOT edit this file directly as changes will be lost\n// Edit the original file at /etc/shairport-sync.conf instead\n' "$RUNTIME_CONFIG"
  
  # Get mixer control index (hardware card number)
  MIXER_INDEX=$(config-soundcard --hw i--no-eeprom 2>/dev/null || echo "0")
  
  # Get mixer control name
  # Mixer name might be empty, in this case, it is set as empty and shairport won't use it
  MIXER_NAME=$(config-soundcard --volume-control --no-eeprom 2>/dev/null)

  # Escape any special characters in mixer name for sed
  MIXER_NAME_SED=$(echo "$MIXER_NAME" | sed 's/[\/&]/\\&/g')
  
  # Update mixer_control_name in runtime config file
  sed -i "s/mixer_control_name.*=.*;/mixer_control_name = \"$MIXER_NAME_SED\";/" "$RUNTIME_CONFIG"
  
  # Update mixer_device to use the hardware card number
  if grep -q "mixer_device" "$RUNTIME_CONFIG"; then
    # Update existing mixer_device value
    sed -i "s/mixer_device.*=.*;/mixer_device = \"hw:$MIXER_INDEX\";/" "$RUNTIME_CONFIG"
  else
    # Add mixer_device after mixer_control_name
    sed -i "/mixer_control_name/a\\  mixer_device = \"hw:$MIXER_INDEX\";" "$RUNTIME_CONFIG"
  fi
  
  echo "Updated mixer settings in runtime config: name=$MIXER_NAME, device=hw:$MIXER_INDEX"
else
  # If the original config exists but config-soundcard isn't available, just copy the file
  if [ -f "$CONFIG_FILE" ]; then
    cp "$CONFIG_FILE" "$RUNTIME_CONFIG"
    echo "Copied original config to runtime location"
  else
    echo "Error: Configuration file not found at $CONFIG_FILE"
    exit 1
  fi
fi

# Determine which binary to use based on version setting
# Check runtime config first, then fall back to original config
if [ -f "$RUNTIME_CONFIG" ]; then
  AIRPLAY_VERSION=$(get_airplay_version "$RUNTIME_CONFIG")
else
  AIRPLAY_VERSION=$(get_airplay_version "$CONFIG_FILE")
fi

if [ "$AIRPLAY_VERSION" = "1" ]; then
  SHAIRPORT_CMD="/usr/bin/shairport"
  echo "Using AirPlay 1 (legacy) version"
else
  SHAIRPORT_CMD="/usr/bin/shairport-airplay2"
  echo "Using AirPlay 2 version"
fi

# Build shairport-sync command with options
SHAIRPORT_OPTS=(
  "--name=${PRETTY_HOSTNAME}"
  "--configfile=${RUNTIME_CONFIG}" 
  "-g"
)


# Debug: print the command to be executed
echo "Starting Shairport Sync with device name: $PRETTY_HOSTNAME"
echo "AirPlay version: $AIRPLAY_VERSION"
echo "Command: $SHAIRPORT_CMD ${SHAIRPORT_OPTS[@]}"

# Run shairport-sync with the configured options
exec $SHAIRPORT_CMD "${SHAIRPORT_OPTS[@]}"