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

REPO_NAME="nsys-packages"
REPO_URL="https://packages.nodsoft.net"
KEY_URL="${REPO_URL}/keyrings/nsys-packages.asc"
KEYRING_PATH="/etc/apt/keyrings/${REPO_NAME}.gpg"
SOURCES_PATH="/etc/apt/sources.list.d/${REPO_NAME}.sources"
SUITE="stable"
COMPONENTS="main"

echo "[+] Installing NSYS package repository"

# ---- sanity checks ---------------------------------------------------------
if [[ $EUID -ne 0 ]]; then
  echo "[!] This script must be run as root (use sudo)" >&2
  exit 1
fi

# ---- dependencies ----------------------------------------------------------
echo "[+] Ensuring required packages are installed"
apt-get update -qq
apt-get install -y -qq curl ca-certificates gnupg

# ---- key installation ------------------------------------------------------
echo "[+] Installing repository signing key"
install -d -m 0755 /etc/apt/keyrings

curl -fsSL "$KEY_URL" \
  | gpg --dearmor \
  | tee "$KEYRING_PATH" > /dev/null

chmod 0644 "$KEYRING_PATH"

# ---- sources file ----------------------------------------------------------
echo "[+] Writing APT source definition"

cat > "$SOURCES_PATH" <<EOF
Types: deb
URIs: $REPO_URL
Suites: $SUITE
Components: $COMPONENTS
Signed-By: $KEYRING_PATH
EOF

chmod 0644 "$SOURCES_PATH"

# ---- update ---------------------------------------------------------------
echo "[+] Updating package lists"
apt-get update

echo "[✓] NSYS repository successfully installed"
