#!/usr/bin/env bash
# installsystemdservice.sh — Installs filemanager as a systemd service.
# Must be run as root: sudo ./installsystemdservice.sh

set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Error: this script must be run as root (use sudo)." >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVICE_NAME="filemanager"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe vips)
KNOWN_PACKAGE_MANAGERS=(apt-get apt dnf yum pacman zypper apk)

# Base packages plus libvips + libheif for Sharp HEIF/HEIC thumbnails and previews.
# Names differ per distro; see required_packages_for().
REQUIRED_PACKAGES_HINT="nodejs npm git ffmpeg + libvips + libheif (package names vary by distro)"

# Resolve the user who owns the project directory (i.e. the user who cloned it,
# not root). Falls back to the SUDO_USER env var, then 'pi'.
RUN_AS="${SUDO_USER:-pi}"
SERVICE_RUN_AS_ROOT=""

bool_is_true() {
  case "${1,,}" in
    1|true|yes|on)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

confirm_root_service_mode() {
  if [[ ! -t 0 ]]; then
    echo "[install] Non-interactive shell detected; defaulting to non-root service mode." >&2
    return 1
  fi

  local reply
  read -r -p "[install] Run the filemanager service as root? [y/N] " reply
  case "${reply,,}" in
    y|yes)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

if [[ -n "${FILEMANAGER_SERVICE_RUN_AS_ROOT:-}" ]]; then
  SERVICE_RUN_AS_ROOT="${FILEMANAGER_SERVICE_RUN_AS_ROOT}"
elif confirm_root_service_mode; then
  SERVICE_RUN_AS_ROOT="1"
else
  SERVICE_RUN_AS_ROOT="0"
fi

SERVICE_USER_LINE="User=${RUN_AS}"
SERVICE_CAPABILITY_LINES=$'AmbientCapabilities=CAP_NET_BIND_SERVICE\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE'
SERVICE_ENV_LINE=""

if bool_is_true "$SERVICE_RUN_AS_ROOT"; then
  SERVICE_USER_LINE="# Running as root (User= omitted intentionally)"
  SERVICE_CAPABILITY_LINES="# Root mode selected: privileged-port capability lines not required"
  SERVICE_ENV_LINE="Environment=FILEMANAGER_LIST_ACCESS_CHMOD=1"
fi

echo "[install] Project directory : $SCRIPT_DIR"
if bool_is_true "$SERVICE_RUN_AS_ROOT"; then
  echo "[install] Service will run as root (FILEMANAGER_SERVICE_RUN_AS_ROOT=1)."
  echo "[install] Enabling chmod-on-folder-list via FILEMANAGER_LIST_ACCESS_CHMOD=1"
else
  echo "[install] Service will run as user: $RUN_AS"
fi

log_warn() {
  echo "[install][warn] $*" >&2
}

collect_missing_commands() {
  local missing=()
  local cmd
  for cmd in "${REQUIRED_COMMANDS[@]}"; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      missing+=("$cmd")
    fi
  done
  printf '%s\n' "${missing[@]}"
}

confirm_dependency_install() {
  if [[ ! -t 0 ]]; then
    log_warn "Non-interactive shell detected; skipping optional dependency installation prompt."
    return 1
  fi

  local reply
  read -r -p "[install] Install required system dependencies now? [Y/n] " reply
  case "${reply,,}" in
    ""|y|yes)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

required_packages_for() {
  local pm="$1"
  local packages=(nodejs npm git ffmpeg)

  case "$pm" in
    apt-get|apt)
      # libvips-tools provides the `vips` CLI; libheif1 enables HEIF in Sharp on Linux.
      packages+=(libvips42 libheif1 libvips-tools)
      ;;
    dnf|yum)
      packages+=(vips libheif)
      ;;
    pacman)
      packages+=(vips libheif)
      ;;
    zypper)
      packages+=(vips libheif)
      ;;
    apk)
      packages+=(vips libheif)
      ;;
    *)
      return 1
      ;;
  esac

  printf '%s\n' "${packages[@]}"
}

install_with_package_manager() {
  local pm="$1"
  local -a packages=()

  mapfile -t packages < <(required_packages_for "$pm")
  if [[ "${#packages[@]}" -eq 0 ]]; then
    log_warn "Unsupported package manager: $pm"
    return 1
  fi

  case "$pm" in
    apt-get)
      apt-get update && apt-get install -y "${packages[@]}"
      ;;
    apt)
      apt update && apt install -y "${packages[@]}"
      ;;
    dnf)
      dnf install -y "${packages[@]}"
      ;;
    yum)
      yum install -y "${packages[@]}"
      ;;
    pacman)
      pacman -Sy --noconfirm "${packages[@]}"
      ;;
    zypper)
      zypper --non-interactive install --no-confirm "${packages[@]}"
      ;;
    apk)
      apk add --no-cache "${packages[@]}"
      ;;
    *)
      log_warn "Unsupported package manager: $pm"
      return 1
      ;;
  esac
}

maybe_install_system_dependencies() {
  mapfile -t missing_commands < <(collect_missing_commands)

  if [[ "${#missing_commands[@]}" -eq 0 ]]; then
    echo "[install] Required system dependencies already available (${REQUIRED_COMMANDS[*]})."
    return 0
  fi

  echo "[install] Missing commands detected: ${missing_commands[*]}"
  if ! confirm_dependency_install; then
    echo "[install] Skipping system dependency installation by user choice."
    return 0
  fi

  local available_package_managers=()
  local pm
  for pm in "${KNOWN_PACKAGE_MANAGERS[@]}"; do
    if command -v "$pm" >/dev/null 2>&1; then
      available_package_managers+=("$pm")
    else
      log_warn "Known package manager '$pm' not found on this system."
    fi
  done

  if [[ "${#available_package_managers[@]}" -eq 0 ]]; then
    log_warn "Could not find a supported package manager. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
    return 0
  fi

  for pm in "${available_package_managers[@]}"; do
    echo "[install] Trying dependency installation via '$pm'..."
    if install_with_package_manager "$pm"; then
      echo "[install] Dependencies installed successfully via '$pm'."
      return 0
    fi
    log_warn "Dependency installation via '$pm' failed."
  done

  log_warn "All package manager installation attempts failed. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
}

maybe_install_system_dependencies

# Make sure start.sh is executable
chmod +x "$SCRIPT_DIR/start.sh"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=File Manager
After=network.target

[Service]
Type=simple
${SERVICE_USER_LINE}
WorkingDirectory=${SCRIPT_DIR}
ExecStart=/bin/sh ${SCRIPT_DIR}/start.sh
Restart=always
RestartSec=5
# Allow binding to privileged ports (< 1024) without running as root.
${SERVICE_CAPABILITY_LINES}
${SERVICE_ENV_LINE}

[Install]
WantedBy=multi-user.target
EOF

echo "[install] Service file written to $SERVICE_FILE"

systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
systemctl restart "${SERVICE_NAME}"

echo "[install] Done. Service status:"
systemctl status "${SERVICE_NAME}" --no-pager
