#!/bin/sh

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

ARGS="-o default -M HiFiBerry"

# Create user-specific runtime directory for squeezelite if running as user service
if [ -n "${XDG_RUNTIME_DIR:-}" ] || [ -n "${XDG_SESSION_ID:-}" ]; then
  # Running as user service
  RUNTIME_DIR="${HOME}/.squeezelite"
  mkdir -p "$RUNTIME_DIR"
else
  # Fallback to system directory
  RUNTIME_DIR="/var/lib/squeezelite"
fi

# Get the ALSA parameters
ALSAPARAMS=$(config-db --get squeezelite.alsaparams 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$ALSAPARAMS" ]; then
  ARGS="$ARGS -a $ALSAPARAMS"
else
  ARGS="$ARGS -a 10240:10240:24_3:0"
fi

# Get the idle timeout
IDLETIMEOUT=$(config-db --get squeezelite.idletimeout 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$IDLETIMEOUT" ]; then
  ARGS="$ARGS -C $IDLETIMEOUT"
else
  ARGS="$ARGS -C 1"
fi

# Get the max sample rate
MAXSAMPLERATE=$(config-db --get squeezelite.maxsamplerate 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$MAXSAMPLERATE" ]; then
  ARGS="$ARGS -r $MAXSAMPLERATE"
else
  ARGS="$ARGS -r 192000"
fi

# Get the pretty hostname from hostnamectl and properly quote it
HOSTNAME=$(hostnamectl hostname --pretty 2>/dev/null)
if [ -z "$HOSTNAME" ] || [ "$HOSTNAME" = "localhost" ]; then
  # Try to get normal hostname if pretty hostname is not available
  HOSTNAME=$(hostname 2>/dev/null)
  # If still not available, use default
  if [ -z "$HOSTNAME" ] || [ "$HOSTNAME" = "localhost" ]; then
    HOSTNAME="HiFiBerry"
  fi
fi

# Get volume control from config-soundcard tool
VOLUME_CONTROL=$(config-soundcard --volume-control-softvol 2>/dev/null)

# Get mixer device from config-soundcard tool
MIXER_DEVICE=$(config-soundcard --hw 2>/dev/null)
if [ -z "$MIXER_DEVICE" ]; then
  MIXER_DEVICE="0"
fi

# Get server configuration using config-db
SERVER=$(config-db --get squeezelite.server 2>/dev/null)

# Build the command with proper quoting
CMD="/usr/bin/squeezelite $ARGS -n \"$HOSTNAME\""

if [ -n "$VOLUME_CONTROL" ]; then
  CMD="$CMD -V $VOLUME_CONTROL"
fi

CMD="$CMD -O hw:$MIXER_DEVICE"

if [ $? -eq 0 ] && [ -n "$SERVER" ]; then
  CMD="$CMD -s $SERVER"
fi

# Execute the command through the shell to maintain quoting
eval $CMD
