#!/usr/bin/env bash
set -euo pipefail

# === Navidrome Installer for Debian-based Systems ===

if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root."
    exit 1
fi

# --- Prompt for user and group ---
read -rp "Enter the Linux user to run Navidrome as: " ND_USER
read -rp "Enter the Linux group to run Navidrome as: " ND_GROUP

# Create group if it doesn't exist
if ! getent group "$ND_GROUP" > /dev/null 2>&1; then
    echo "Group '$ND_GROUP' does not exist. Creating..."
    groupadd "$ND_GROUP"
fi

# Create user if it doesn't exist
if ! id -u "$ND_USER" > /dev/null 2>&1; then
    echo "User '$ND_USER' does not exist. Creating..."
    useradd -r -g "$ND_GROUP" -s /usr/sbin/nologin -M "$ND_USER"
fi

# --- Install dependencies ---
apt update
apt upgrade -y
apt install -y ffmpeg jq curl wget

# --- Create directories ---
install -d -o "$ND_USER" -g "$ND_GROUP" /opt/navidrome
install -d -o "$ND_USER" -g "$ND_GROUP" /var/lib/navidrome

# --- Download latest Navidrome ---
LATEST_VERSION=$(curl -s https://api.github.com/repos/navidrome/navidrome/releases/latest | jq -r '.tag_name' | sed 's/^v//')
echo "Downloading Navidrome v${LATEST_VERSION}..."
wget "https://github.com/navidrome/navidrome/releases/download/v${LATEST_VERSION}/navidrome_${LATEST_VERSION}_linux_amd64.tar.gz" -O /tmp/navidrome.tar.gz

tar -xzf /tmp/navidrome.tar.gz -C /opt/navidrome/
chown -R "$ND_USER":"$ND_GROUP" /opt/navidrome
rm /tmp/navidrome.tar.gz

# --- Write navidrome.toml ---
cat > /var/lib/navidrome/navidrome.toml << 'TOML'
MusicFolder = "/shares/media/Music"

Scanner.Schedule = "0"
Scanner.WatcherWait = "1s"
Scanner.ScanOnStartup = true
Scanner.FollowSymlinks = true
Scanner.PurgeMissing = "always"

DevExternalScanner = true
# NFS share is configured with multithreading
# Otherwise, beware this setting.
DevScannerThreads = 8
DevSelectiveWatcher = true
DevOptimizeDB = true

EnableArtworkPrecache = true
ImageCacheSize = "8GB"
TranscodingCacheSize = "8GB"
RecentlyAddedByModTime = true

#LastFM.ApiKey = ""
#LastFM.Secret = ""
#Spotify.ID = ""
#Spotify.Secret = ""

# === SHARING & AUTH ===
# EnableSharing = true
# AuthWindowLength = "0s"
# AuthRequestLimit = 11111
TOML

chown "$ND_USER":"$ND_GROUP" /var/lib/navidrome/navidrome.toml

# --- Write systemd service ---
cat > /etc/systemd/system/navidrome.service << EOF
[Unit]
Description=Navidrome Music Server and Streamer compatible with Subsonic/Airsonic
After=remote-fs.target network.target
AssertPathExists=/var/lib/navidrome

[Install]
WantedBy=multi-user.target

[Service]
User=${ND_USER}
Group=${ND_GROUP}
Type=simple
ExecStart=/opt/navidrome/navidrome --configfile "/var/lib/navidrome/navidrome.toml"
WorkingDirectory=/var/lib/navidrome
TimeoutStopSec=20
KillMode=process
Restart=on-failure

DevicePolicy=closed
NoNewPrivileges=yes
PrivateTmp=yes
PrivateUsers=yes
ProtectControlGroups=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
RestrictRealtime=yes
SystemCallFilter=~@clock @debug @module @mount @obsolete @reboot @setuid @swap
ReadWritePaths=/var/lib/navidrome

ProtectSystem=full
EOF

# --- Enable and start ---
systemctl daemon-reload
systemctl enable navidrome.service
systemctl start navidrome.service

echo ""
echo "Navidrome v${LATEST_VERSION} installed and running."
echo "  User/Group: ${ND_USER}:${ND_GROUP}"
echo "  Config:     /var/lib/navidrome/navidrome.toml"
echo "  Service:    systemctl status navidrome"
echo "  Web UI:     http://<your-ip>:4533"
