#!/usr/bin/env bash
# Common helpers for RSPC management scripts. Sourced, not executed.
set -Eeuo pipefail

RSPC_HOME=/opt/rspc
RSPC_ETC=/etc/rspc
RSPC_DATA=/var/lib/rspc
RSPC_USER=rspc
RSPC_SERVICE=rspc
RSPC_CONFIG="$RSPC_ETC/config.yaml"
RSPC_BIN="$RSPC_HOME/bin/rspc"
RSPC_UNIT="/etc/systemd/system/$RSPC_SERVICE.service"
RSPC_BACKUPS="$RSPC_DATA/backups"

# Directory of the unpacked archive (or /opt/rspc when run from the installed copy).
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

if [[ -t 1 ]]; then
  C_RESET=$'\e[0m'; C_BOLD=$'\e[1m'; C_RED=$'\e[31m'; C_GREEN=$'\e[32m'; C_YELLOW=$'\e[33m'; C_BLUE=$'\e[34m'
else
  C_RESET=""; C_BOLD=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_BLUE=""
fi

info() { echo "${C_BLUE}==>${C_RESET} $*"; }
ok()   { echo "${C_GREEN}✔${C_RESET} $*"; }
warn() { echo "${C_YELLOW}!${C_RESET} $*" >&2; }
die()  { echo "${C_RED}✘ $*${C_RESET}" >&2; exit 1; }

trap 'die "command failed (line $LINENO): $BASH_COMMAND"' ERR

require_root() {
  [[ $EUID -eq 0 ]] || die "run this script as root: sudo $0 $*"
}

require_ubuntu() {
  [[ -r /etc/os-release ]] || die "/etc/os-release not found"
  # shellcheck disable=SC1091
  . /etc/os-release
  if [[ "${ID:-}" != "ubuntu" || "${VERSION_ID:-}" != "24.04" ]]; then
    if [[ "${RSPC_SKIP_OS_CHECK:-0}" == "1" ]]; then
      warn "unsupported OS ${PRETTY_NAME:-unknown}, continuing because RSPC_SKIP_OS_CHECK=1"
    else
      die "RSPC supports only Ubuntu 24.04 (found: ${PRETTY_NAME:-unknown}). Set RSPC_SKIP_OS_CHECK=1 to try anyway."
    fi
  fi
  [[ "$(uname -m)" == "x86_64" ]] || die "RSPC is built for x86_64 (amd64), this machine is $(uname -m)"
  command -v systemctl >/dev/null || die "systemd is required"
}

is_installed() { [[ -f "$RSPC_CONFIG" && -x "$RSPC_BIN" ]]; }

require_installed() {
  is_installed || die "RSPC is not installed (run install.sh first)"
}

# Run the rspc CLI as the service user so files in $RSPC_DATA keep the right owner.
rspc_cli() {
  runuser -u "$RSPC_USER" -- "$RSPC_BIN" "$@" --config "$RSPC_CONFIG"
}

# rspc_cli_from <binary> ... : same, but with a specific binary (used by update).
rspc_cli_from() {
  local bin=$1; shift
  runuser -u "$RSPC_USER" -- "$bin" "$@" --config "$RSPC_CONFIG"
}

verify_checksums() {
  [[ -f "$SRC_DIR/CHECKSUMS" ]] || die "CHECKSUMS file is missing in $SRC_DIR (archive damaged?)"
  (cd "$SRC_DIR" && sha256sum --quiet -c CHECKSUMS) || die "archive checksum verification failed — download the archive again"
  ok "archive integrity verified"
}

# port_owner <proto> <port>: prints the process listening on the port, empty if free.
port_owner() {
  local proto=$1 port=$2 flag=-Hltnp
  [[ $proto == udp ]] && flag=-Hlunp
  ss $flag "( sport = :$port )" 2>/dev/null | head -n1 | sed -E 's/.*users:\(\("([^"]+)".*/\1/'
}

valid_domain() {
  [[ $1 =~ ^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$ ]]
}

valid_email() {
  [[ $1 =~ ^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$ ]]
}

# ask <var> <prompt> [default]
ask() {
  local __var=$1 prompt=$2 def=${3:-} reply
  if [[ -n $def ]]; then
    read -r -p "$prompt [$def]: " reply </dev/tty || true
    reply=${reply:-$def}
  else
    read -r -p "$prompt: " reply </dev/tty || true
  fi
  printf -v "$__var" '%s' "$reply"
}

confirm() {
  local reply
  read -r -p "$1 [y/N]: " reply </dev/tty || true
  [[ $reply =~ ^[YyДд] ]]
}

install_files() {
  local src=$1
  install -d -m 0755 "$RSPC_HOME" "$RSPC_HOME/bin" "$RSPC_HOME/scripts"
  install -m 0755 "$src/bin/rspc" "$RSPC_BIN.new"
  mv -f "$RSPC_BIN.new" "$RSPC_BIN"
  for f in "$src"/scripts/*.sh; do
    install -m 0755 "$f" "$RSPC_HOME/scripts/$(basename "$f")"
  done
  install -m 0644 "$src/VERSION" "$RSPC_HOME/VERSION"
  [[ -f "$src/README.md" ]] && install -m 0644 "$src/README.md" "$RSPC_HOME/README.md"
  return 0
}

write_unit() {
  cat >"$RSPC_UNIT" <<EOF
[Unit]
Description=RSPC - ReveServerProx-Controling reverse proxy
Documentation=file://$RSPC_HOME/README.md
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$RSPC_USER
Group=$RSPC_USER
ExecStart=$RSPC_BIN serve --config $RSPC_CONFIG
Restart=always
RestartSec=3
TimeoutStopSec=20
LimitNOFILE=1048576

# Least privilege: only the right to bind ports < 1024.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$RSPC_DATA
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictSUIDSGID=true
RestrictNamespaces=true
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
SystemCallArchitectures=native

[Install]
WantedBy=multi-user.target
EOF
  chmod 0644 "$RSPC_UNIT"
  systemctl daemon-reload
}

wait_healthy() {
  local secs=${1:-30}
  rspc_cli healthcheck --wait "$secs" >/dev/null 2>&1
}

show_recent_logs() {
  echo "----- last log lines -----"
  journalctl -u "$RSPC_SERVICE" -n "${1:-25}" --no-pager 2>/dev/null || true
  echo "--------------------------"
}

installed_version() { cat "$RSPC_HOME/VERSION" 2>/dev/null || echo "unknown"; }

ufw_active() { command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "^Status: active"; }
