#!/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_PACKAGES=(nodejs npm git ffmpeg)
REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe)
KNOWN_PACKAGE_MANAGERS=(apt-get apt dnf yum pacman zypper apk)

# 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}"

echo "[install] Project directory : $SCRIPT_DIR"
echo "[install] Service will run as user: $RUN_AS"

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
}

install_with_package_manager() {
  local pm="$1"

  case "$pm" in
    apt-get)
      apt-get update && apt-get install -y "${REQUIRED_PACKAGES[@]}"
      ;;
    apt)
      apt update && apt install -y "${REQUIRED_PACKAGES[@]}"
      ;;
    dnf)
      dnf install -y "${REQUIRED_PACKAGES[@]}"
      ;;
    yum)
      yum install -y "${REQUIRED_PACKAGES[@]}"
      ;;
    pacman)
      pacman -Sy --noconfirm "${REQUIRED_PACKAGES[@]}"
      ;;
    zypper)
      zypper --non-interactive install --no-confirm "${REQUIRED_PACKAGES[@]}"
      ;;
    apk)
      apk add --no-cache "${REQUIRED_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[*]} (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[*]} (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
User=${RUN_AS}
WorkingDirectory=${SCRIPT_DIR}
ExecStart=/bin/sh ${SCRIPT_DIR}/start.sh
Restart=always
RestartSec=5
# Allow binding to privileged ports (< 1024) without running as root.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

[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
