#!/usr/bin/env bash
# =============================================================================
# Arr-Suite Installer — Atlantis (192.168.0.200)
# =============================================================================
# One-line install:
#   bash <(curl -fsSL https://git.vish.gg/Vish/homelab/raw/branch/main/hosts/synology/atlantis/arr-suite/install.sh)
#
# What this installs:
#   Sonarr, Radarr, Lidarr, Bazarr, Prowlarr, Jackett, FlaresolverR
#   SABnzbd, Deluge (via gluetun VPN), Tdarr, LazyLibrarian
#   Audiobookshelf, Whisparr, Plex, Jellyseerr, Tautulli, Wizarr
#
# Prerequisites:
#   - Synology DSM with Container Manager (Docker)
#   - /volume1/data, /volume2/metadata/docker2, /volume3/usenet, /volume2/torrents
#   - PUID=1029, PGID=100 (DSM user: vish)
#   - WireGuard credentials for gluetun (must be set in compose or env)
# =============================================================================

set -euo pipefail

REPO_URL="https://git.vish.gg/Vish/homelab"
COMPOSE_URL="${REPO_URL}/raw/branch/main/hosts/synology/atlantis/arr-suite/docker-compose.yml"
DOCKER="${DOCKER_BIN:-/usr/local/bin/docker}"
STACK_DIR="/volume2/metadata/docker2/arr-suite"
COMPOSE_FILE="${STACK_DIR}/docker-compose.yml"

# Colours
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()    { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ── Preflight ─────────────────────────────────────────────────────────────────

info "Arr-Suite installer starting"

[[ $(id -u) -eq 0 ]] || error "Run as root (sudo bash install.sh)"
command -v "$DOCKER" &>/dev/null || error "Docker not found at $DOCKER — set DOCKER_BIN env var"

for vol in /volume1/data /volume2/metadata/docker2 /volume3/usenet /volume2/torrents; do
    [[ -d "$vol" ]] || warn "Volume $vol does not exist — create it before starting services"
done

# ── Required directories ───────────────────────────────────────────────────────

info "Creating config directories..."
SERVICES=(
    sonarr radarr lidarr bazarr prowlarr jackett sabnzbd
    deluge gluetun tdarr/server tdarr/configs tdarr/logs
    lazylibrarian audiobookshelf whisparr plex jellyseerr
    tautulli wizarr
)
for svc in "${SERVICES[@]}"; do
    mkdir -p "/volume2/metadata/docker2/${svc}"
done

# Download directories
mkdir -p \
    /volume3/usenet/complete \
    /volume3/usenet/incomplete \
    /volume3/usenet/tdarr_cache \
    /volume2/torrents/complete \
    /volume2/torrents/incomplete

# Media library
mkdir -p \
    /volume1/data/media/tv \
    /volume1/data/media/movies \
    /volume1/data/media/music \
    /volume1/data/media/audiobooks \
    /volume1/data/media/podcasts \
    /volume1/data/media/ebooks \
    /volume1/data/media/misc

# Lidarr arr-scripts directories
mkdir -p \
    /volume2/metadata/docker2/lidarr-scripts/custom-cont-init.d \
    /volume2/metadata/docker2/lidarr-scripts/custom-services.d

# ── Lidarr arr-scripts bootstrap ──────────────────────────────────────────────

INIT_SCRIPT="/volume2/metadata/docker2/lidarr-scripts/custom-cont-init.d/scripts_init.bash"
if [[ ! -f "$INIT_SCRIPT" ]]; then
    info "Downloading arr-scripts init script..."
    curl -fsSL "https://raw.githubusercontent.com/RandomNinjaAtk/arr-scripts/main/lidarr/scripts_init.bash" \
        -o "$INIT_SCRIPT" || warn "Failed to download arr-scripts init — download manually from RandomNinjaAtk/arr-scripts"
    chmod +x "$INIT_SCRIPT"
fi

# ── Download compose file ──────────────────────────────────────────────────────

info "Downloading docker-compose.yml..."
mkdir -p "$STACK_DIR"
curl -fsSL "$COMPOSE_URL" -o "$COMPOSE_FILE" || error "Failed to download compose file from $COMPOSE_URL"

# ── Warn about secrets ────────────────────────────────────────────────────────

warn "==================================================================="
warn "ACTION REQUIRED before starting:"
warn ""
warn "1. Set gluetun WireGuard credentials in:"
warn "   $COMPOSE_FILE"
warn "   - WIREGUARD_PRIVATE_KEY"
warn "   - WIREGUARD_PUBLIC_KEY"
warn "   - WIREGUARD_ENDPOINT_IP"
warn ""
warn "2. Set Lidarr Deezer ARL token:"
warn "   /volume2/metadata/docker2/lidarr/extended.conf"
warn "   arlToken=\"<your-arl-token>\""
warn "   Get from: deezer.com -> DevTools -> Cookies -> arl"
warn ""
warn "3. Set Plex claim token (optional, for initial setup):"
warn "   https://www.plex.tv/claim"
warn "   Add to compose: PLEX_CLAIM=<token>"
warn "==================================================================="

# ── Pull images ───────────────────────────────────────────────────────────────

read -rp "Pull all images now? (y/N): " pull_images
if [[ "${pull_images,,}" == "y" ]]; then
    info "Pulling images (this may take a while)..."
    "$DOCKER" compose -f "$COMPOSE_FILE" pull
fi

# ── Start stack ───────────────────────────────────────────────────────────────

read -rp "Start all services now? (y/N): " start_services
if [[ "${start_services,,}" == "y" ]]; then
    info "Starting arr-suite..."
    "$DOCKER" compose -f "$COMPOSE_FILE" up -d
    info "Done! Services starting..."
    echo ""
    echo "Service URLs:"
    echo "  Sonarr:        http://192.168.0.200:8989"
    echo "  Radarr:        http://192.168.0.200:7878"
    echo "  Lidarr:        http://192.168.0.200:8686"
    echo "  Prowlarr:      http://192.168.0.200:9696"
    echo "  SABnzbd:       http://192.168.0.200:8080"
    echo "  Deluge:        http://192.168.0.200:8112  (password: "REDACTED_PASSWORD"
    echo "  Bazarr:        http://192.168.0.200:6767"
    echo "  Tdarr:         http://192.168.0.200:8265"
    echo "  Whisparr:      http://192.168.0.200:6969"
    echo "  Plex:          http://192.168.0.200:32400/web"
    echo "  Jellyseerr:    http://192.168.0.200:5055"
    echo "  Audiobookshelf:http://192.168.0.200:13378"
    echo "  LazyLibrarian: http://192.168.0.200:5299"
    echo "  Tautulli:      http://192.168.0.200:8181"
    echo "  Wizarr:        http://192.168.0.200:5690"
    echo "  Jackett:       http://192.168.0.200:9117"
fi

info "Install complete."
info "Docs: https://git.vish.gg/Vish/homelab/src/branch/main/docs/services/individual/"
