#!/usr/bin/env bash
# Marktplaats Sniper — self-managed installer for a fresh Ubuntu 22.04/24.04 server.
#
# Usage (as root):
#   bash install.sh https://your-app-url your-access-key
#
# Or with environment variables:
#   SNIPER_URL="https://your-app-url" SNIPER_TOKEN="your-access-key" bash install.sh
#
# What it does:
#   1. installs Node.js 20, Chromium dependencies and a light desktop + VNC
#   2. installs the helper in /opt/marktplaats-sniper
#   3. creates a systemd service that starts on boot and restarts on failure
#   4. leaves you with one command to sign in to Marktplaats by hand, once
set -euo pipefail

APP_DIR="/opt/marktplaats-sniper"
SERVICE="marktplaats-sniper"
RUN_USER="${SUDO_USER:-root}"

say() { printf "\n\033[1;33m==>\033[0m %s\n" "$1"; }

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run this with sudo: sudo bash install.sh https://... your-token" >&2
  exit 1
fi

# Support positional args OR env vars, so it works on mobile SSH clients.
SNIPER_URL="${1:-${SNIPER_URL:-}}"
SNIPER_TOKEN="${2:-${SNIPER_TOKEN:-}}"

if [[ -z "${SNIPER_URL}" || -z "${SNIPER_TOKEN}" ]]; then
  cat <<'USAGE' >&2

Marktplaats Sniper installer — missing URL or access key.

Run one of these (as root):

  bash install.sh https://marktplaatssniper.nl your-access-key

or with environment variables:

  SNIPER_URL=https://marktplaatssniper.nl SNIPER_TOKEN=your-access-key bash install.sh

The access key is shown in the app under Settings → Your own always-on machine.
USAGE
  exit 1
fi

say "Installing system packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y curl ca-certificates xvfb x11vnc xfce4 xfce4-terminal dbus-x11 fonts-liberation

if ! command -v node >/dev/null 2>&1 || [[ "$(node -v | cut -c2- | cut -d. -f1)" -lt 18 ]]; then
  say "Installing Node.js 20"
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
fi

say "Installing the helper in ${APP_DIR}"
mkdir -p "${APP_DIR}"
cd "${APP_DIR}"
[[ -f package.json ]] || npm init -y >/dev/null
npm install playwright >/dev/null
npx playwright install --with-deps chromium
curl -fsSL "${SNIPER_URL%/}/agent/marktplaats-agent.mjs" -o "${APP_DIR}/marktplaats-agent.mjs"

cat > "${APP_DIR}/.env" <<ENV
SNIPER_URL=${SNIPER_URL%/}
SNIPER_TOKEN=${SNIPER_TOKEN}
SNIPER_PROFILE=${APP_DIR}/mp-profile
SNIPER_POLL_MS=15000
ENV
chmod 600 "${APP_DIR}/.env"
chown -R "${RUN_USER}":"${RUN_USER}" "${APP_DIR}"

say "Creating the systemd service"
cat > "/etc/systemd/system/${SERVICE}.service" <<UNIT
[Unit]
Description=Marktplaats Sniper helper
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${RUN_USER}
WorkingDirectory=${APP_DIR}
EnvironmentFile=${APP_DIR}/.env
Environment=SNIPER_HEADLESS=1
ExecStart=/usr/bin/xvfb-run -a /usr/bin/node ${APP_DIR}/marktplaats-agent.mjs run
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable "${SERVICE}" >/dev/null

say "Creating the sign-in helper (mp-login)"
cat > /usr/local/bin/mp-login <<'LOGIN'
#!/usr/bin/env bash
# Opens a real browser on a hidden desktop you can reach with VNC, so you can
# sign in to Marktplaats by hand once. Connect to localhost:5900 over an SSH
# tunnel:  ssh -L 5900:localhost:5900 user@your-server
set -euo pipefail
APP_DIR="/opt/marktplaats-sniper"
set -a; . "${APP_DIR}/.env"; set +a
systemctl stop marktplaats-sniper || true
Xvfb :99 -screen 0 1280x900x24 &
XVFB_PID=$!
sleep 2
DISPLAY=:99 x11vnc -display :99 -localhost -nopw -forever -quiet &
VNC_PID=$!
echo "VNC is ready on localhost:5900 — connect, sign in, then close the browser."
DISPLAY=:99 node "${APP_DIR}/marktplaats-agent.mjs" login || true
kill "${VNC_PID}" "${XVFB_PID}" 2>/dev/null || true
systemctl start marktplaats-sniper
echo "Helper restarted. Check it with: systemctl status marktplaats-sniper"
LOGIN
chmod +x /usr/local/bin/mp-login

say "Done"
cat <<DONE

Next, sign in to Marktplaats once:

  1. From your own computer:  ssh -L 5900:localhost:5900 ${RUN_USER}@this-server
  2. On the server:           sudo mp-login
  3. Open a VNC viewer at     localhost:5900  and sign in to Marktplaats
  4. Close the browser window when you are signed in

After that the helper runs on its own:

  systemctl status ${SERVICE}      # is it running?
  journalctl -u ${SERVICE} -f      # live log

DONE
