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

# ReferShare Ubuntu/Debian installer. Run: sudo bash install_refershare.sh /path/to/refershare.zip
ARCHIVE="${1:-}"
APP_DIR="/opt/refershare"
APP_USER="refershare"
PB_VERSION="0.40.6"

if [[ $EUID -ne 0 ]]; then echo 'Run with sudo.' >&2; exit 1; fi
if [[ ! -f "$ARCHIVE" ]]; then echo 'Usage: sudo bash install_refershare.sh /path/to/refershare.zip' >&2; exit 1; fi
if ! command -v apt-get >/dev/null; then echo 'Requires Ubuntu/Debian with apt.' >&2; exit 1; fi
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y ca-certificates curl unzip git openssl python3 build-essential

# Node.js 24 LTS from NodeSource
if ! command -v node >/dev/null || [[ $(node -p 'Number(process.versions.node.split(".")[0])') -lt 24 ]]; then
  curl -fsSL https://deb.nodesource.com/setup_24.x -o /tmp/refershare-nodesource.sh
  bash /tmp/refershare-nodesource.sh
  apt-get install -y nodejs
fi

if ! id "$APP_USER" >/dev/null 2>&1; then
  useradd --system --home-dir "$APP_DIR" --shell /usr/sbin/nologin "$APP_USER"
fi
mkdir -p "$APP_DIR"
if [[ -e "$APP_DIR/package.json" ]]; then
  echo "Existing installation detected at $APP_DIR; refusing to overwrite. Back up and move it first." >&2
  exit 1
fi
unzip -q "$ARCHIVE" -d "$APP_DIR"
if [[ ! -f "$APP_DIR/package.json" ]]; then
  echo 'package.json not found at archive root.' >&2
  exit 1
fi

case "$(uname -m)" in
  x86_64) PB_ARCH=amd64 ;;
  aarch64|arm64) PB_ARCH=arm64 ;;
  *) echo "Unsupported CPU architecture: $(uname -m)" >&2; exit 1 ;;
esac
mkdir -p "$APP_DIR/pocketbase/pb_data" "$APP_DIR/pocketbase/pb_migrations"
PB_URL="https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_${PB_ARCH}.zip"
curl -fL --retry 3 "$PB_URL" -o /tmp/refershare-pocketbase.zip
unzip -jo /tmp/refershare-pocketbase.zip pocketbase -d "$APP_DIR/pocketbase"
chmod 755 "$APP_DIR/pocketbase/pocketbase"
rm -f /tmp/refershare-pocketbase.zip

if [[ ! -f "$APP_DIR/.env" ]]; then
  if [[ -f "$APP_DIR/.env.example" ]]; then cp "$APP_DIR/.env.example" "$APP_DIR/.env"; else touch "$APP_DIR/.env"; fi
  cat >> "$APP_DIR/.env" <<'ENV'

# ReferShare server configuration
PORT=3000
PB_PORT=8090
NODE_ENV=production
# Set APP_URL to your HTTPS domain before public deployment.
ENV
fi
chmod 600 "$APP_DIR/.env"
cd "$APP_DIR"
npm install --no-audit --no-fund
npm run build
chown -R "$APP_USER:$APP_USER" "$APP_DIR"

cat >/etc/systemd/system/refershare.service <<'UNIT'
[Unit]
Description=ReferShare Node.js and embedded PocketBase
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=refershare
Group=refershare
WorkingDirectory=/opt/refershare
EnvironmentFile=/opt/refershare/.env
ExecStart=/usr/bin/npm start
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
ReadWritePaths=/opt/refershare

[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now refershare
printf '\nInstallation completed.\n'
echo 'Service: sudo systemctl status refershare'
echo 'Logs: sudo journalctl -u refershare -f'
echo 'Local website: http://127.0.0.1:3000'
echo 'Local PocketBase dashboard: http://127.0.0.1:3000/_/'
echo 'IMPORTANT: Edit /opt/refershare/.env to configure APP_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD, GEMINI_API_KEY.'
echo 'Then: sudo systemctl restart refershare'
echo 'For public deployment, configure a domain, HTTPS reverse proxy, and firewall rules separately.'
