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

# KINO Home Cinema Server — One-line macOS installer
# Usage: curl -fsSL https://kino.dendria.ca/install.sh | bash

BASE_URL="${KINO_DOWNLOAD_BASE:-https://kino.dendria.ca}"
TARBALL_URL="${BASE_URL}/downloads/kino-server-macos.tar.gz"
INSTALL_DIR="${KINO_INSTALL_DIR:-$HOME/.local/share/kino-server}"
BIN_DIR="${KINO_BIN_DIR:-$HOME/.local/bin}"

echo ""
echo "  KINO Home Cinema Server Installer"
echo "  ----------------------------------"

# 1. Verify Node.js 22+
find_node() {
  local candidates=(
    "$(command -v node 2>/dev/null || true)"
    "/opt/homebrew/bin/node"
    "/usr/local/bin/node"
  )
  if [ -d "$HOME/.nvm/versions/node" ]; then
    while IFS= read -r p; do
      candidates+=("$p")
    done < <(ls -1d "$HOME"/.nvm/versions/node/v*/bin/node 2>/dev/null | sort -Vr)
  fi
  for bin in "${candidates[@]}"; do
    [ -z "$bin" ] || [ ! -x "$bin" ] && continue
    local major
    major="$("$bin" -p "Number(process.versions.node.split('.')[0])" 2>/dev/null || echo 0)"
    if [ "$major" -ge 22 ]; then
      echo "$bin"
      return 0
    fi
  done
  return 1
}

if ! NODE_BIN="$(find_node)"; then
  echo "  Error: Node.js 22+ is required."
  echo "  Install with Homebrew: brew install node"
  echo "  Or download from: https://nodejs.org/"
  exit 1
fi
echo "  Found Node.js: $("$NODE_BIN" -v) ($NODE_BIN)"

# 2. Check FFmpeg (recommended for MKV/HEVC transcoding and thumbnails)
if command -v /opt/homebrew/bin/ffmpeg >/dev/null 2>&1 || command -v ffmpeg >/dev/null 2>&1; then
  echo "  Found FFmpeg: ready for HLS transcoding & thumbnails"
else
  echo "  Note: FFmpeg was not found. Direct MP4 play works, but install FFmpeg for MKV/HEVC:"
  echo "        brew install ffmpeg"
fi

# 3. Download and extract KINO Server bundle
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

echo "  Downloading KINO Server from ${TARBALL_URL}..."
curl -fsSL "$TARBALL_URL" -o "$TMP_DIR/kino-server.tar.gz"

mkdir -p "$(dirname "$INSTALL_DIR")" "$BIN_DIR"
rm -rf "$INSTALL_DIR"
tar -xzf "$TMP_DIR/kino-server.tar.gz" -C "$TMP_DIR"
mv "$TMP_DIR/kino-server" "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/bin/kino-server"
ln -sf "$INSTALL_DIR/bin/kino-server" "$BIN_DIR/kino-server"

# Ensure ~/.local/bin is in PATH notice
if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
  echo ""
  echo "  Tip: add ~/.local/bin to your shell PATH:"
  echo "       export PATH=\"\$HOME/.local/bin:\$PATH\""
fi

# 4. Start KINO Server background LaunchAgent (macOS)
echo ""
KINO_NODE_BIN="$NODE_BIN" "$BIN_DIR/kino-server" start

echo ""
echo "  Done! Open http://localhost:8096 in your browser to add your movie & TV folders."
echo ""
