#!/usr/bin/env bash
# ── Pi Multi-FX Pedal — mDNS (Avahi) setup ─────────────────────────
# Enables pedal.local or multifx.local resolution on the LAN.
# Run once after first install: sudo bash scripts/setup-mdns.sh
#
# What it does:
# 1. Installs avahi-daemon if missing
# 2. Sets hostname to 'pedal' in /etc/hostname
# 3. Configures avahi-daemon to publish the hostname
# 4. Installs the service advertisement file for the web UI
# 5. Restarts avahi-daemon
#
# After this, http://pedal.local:8080 works from any machine on the LAN.
# ───────────────────────────────────────────────────────────────────────

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

HOSTNAME="pedal"
AVAHI_SERVICE_SRC="${PROJECT_DIR}/etc/avahi/pi-multifx-pedal.service"
AVAHI_SERVICE_DST="/etc/avahi/services/pi-multifx-pedal.service"

echo "═══ Pi Multi-FX Pedal — mDNS Setup ═══"

# 1. Install avahi-daemon
if ! command -v avahi-daemon &>/dev/null; then
    echo "Installing avahi-daemon..."
    sudo apt-get update -qq
    sudo apt-get install -y -qq avahi-daemon avahi-utils
else
    echo "avahi-daemon already installed"
fi

# 2. Set hostname
CURRENT_HOSTNAME="$(hostname)"
if [ "$CURRENT_HOSTNAME" != "$HOSTNAME" ]; then
    echo "Setting hostname to '$HOSTNAME'..."
    echo "$HOSTNAME" | sudo tee /etc/hostname > /dev/null
    sudo hostnamectl set-hostname "$HOSTNAME"
else
    echo "Hostname already set to '$HOSTNAME'"
fi

# 3. Configure avahi to publish hostname
AVAHI_CONF="/etc/avahi/avahi-daemon.conf"
if grep -q "^#host-name=" "$AVAHI_CONF" 2>/dev/null; then
    echo "Uncommenting host-name in avahi-daemon.conf..."
    sudo sed -i "s/^#host-name=/host-name=/g" "$AVAHI_CONF"
fi

# Make sure publish-workstation is on (publishes _http._tcp for pedal.local)
if grep -q "^#publish-workstation=" "$AVAHI_CONF" 2>/dev/null; then
    sudo sed -i "s/^#publish-workstation=/publish-workstation=/g" "$AVAHI_CONF"
fi

# 4. Install the custom service advertisement
if [ -f "$AVAHI_SERVICE_SRC" ]; then
    echo "Installing Avahi service advertisement..."
    sudo cp "$AVAHI_SERVICE_SRC" "$AVAHI_SERVICE_DST"
else
    echo "WARNING: Service file not found at $AVAHI_SERVICE_SRC — skipping"
fi

# 5. Restart avahi-daemon
echo "Restarting avahi-daemon..."
sudo systemctl enable avahi-daemon
sudo systemctl restart avahi-daemon

echo ""
echo "═══ mDNS setup complete ═══"
echo "The pedal should now be reachable at:"
echo "  http://${HOSTNAME}.local:8080"
echo ""
echo "From any device on the same LAN, try:"
echo "  ping ${HOSTNAME}.local"
echo "  curl http://${HOSTNAME}.local:8080/api/state"
echo ""
echo "NOTE: If resolution doesn't work immediately, wait ~10 seconds"
echo "for mDNS propagation, or check: sudo systemctl status avahi-daemon"