#!/bin/bash
# Velotrak installer / upgrader (Linux, systemd). One command, whole stack:
#
#   curl -fsSL https://velotrak.app/install.sh | sudo bash
#   curl -fsSL https://velotrak.app/install.sh | sudo VELOTRAK_VERSION=v1.2.3 bash
#   curl -fsSL https://velotrak.app/install.sh | sudo VELOTRAK_EXTERNAL_DB=1 bash
#   sudo ./install.sh ./velotrak            # install a local binary
#   VELOTRAK_DOWNLOAD_BASE=https://mirror/x  # same asset names as a release
#
# A fresh install:
#   1. installs Docker (get.docker.com) when it is missing, and runs
#      PostgreSQL + ClickHouse with docker compose from /opt/velotrak/stack,
#      bound to 127.0.0.1 only, with generated passwords;
#   2. downloads the release binary for this machine from GitHub Releases
#      (github.com/velotrak/velotrak), verifies its SHA-256 against the
#      release's checksums.txt;
#   3. writes /opt/velotrak/velotrak.env (DSNs + a generated master key)
#      and a systemd unit, starts the service and waits until it answers.
# Velotrak itself runs as a native binary (not a container) so that its
# signed self-updates replace the binary in place.
#
# Re-running upgrades the binary (the previous one is kept as velotrak.old)
# and leaves the env file, the passwords and the data alone.
# VELOTRAK_EXTERNAL_DB=1 skips Docker: bring your own PostgreSQL and
# ClickHouse and set the DSNs in the env file. Migrations are built in.
set -euo pipefail

REPO="${VELOTRAK_REPO:-velotrak/velotrak}"
VERSION="${VELOTRAK_VERSION:-latest}"
EXTERNAL_DB="${VELOTRAK_EXTERNAL_DB:-0}"
PREFIX=/opt/velotrak
DATA=/var/lib/velotrak
STACK="$PREFIX/stack"
PORT=8080
LOCAL_BIN="${1:-}"

say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[33mWARN:\033[0m %s\n' "$*" >&2; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
secret() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; } # hex: DSN-safe

[ "$(id -u)" -eq 0 ] || die "run as root (e.g. curl -fsSL https://velotrak.app/install.sh | sudo bash)"
[ "$(uname -s)" = "Linux" ] || die "Velotrak servers run on Linux (this is $(uname -s))"
command -v systemctl >/dev/null || die "systemd is required"
command -v curl >/dev/null || die "curl is required (apt-get install -y curl / dnf install -y curl)"

case "$(uname -m)" in
  x86_64 | amd64) ARCH=amd64 ;;
  aarch64 | arm64) ARCH=arm64 ;;
  *) die "unsupported CPU architecture: $(uname -m) (supported: x86_64, arm64)" ;;
esac

UPGRADE=0
[ -f "$PREFIX/velotrak" ] && UPGRADE=1
# The bundled databases are used when this installer created them, or on
# a fresh install unless the operator brings their own.
USE_STACK=0
if [ -f "$STACK/docker-compose.yml" ]; then
  USE_STACK=1
elif [ ! -f "$PREFIX/velotrak.env" ] && [ "$EXTERNAL_DB" != 1 ]; then
  USE_STACK=1
fi

if [ "$UPGRADE" = 0 ]; then
  MEM_MB=$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo)
  [ "$MEM_MB" -ge 3500 ] || warn "this server has ${MEM_MB} MB RAM; Velotrak needs at least 4 GB (2 vCPU / 4 GB minimum)."
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# ---- 1. Binary (downloaded and verified before anything is changed) ----
if [ -n "$LOCAL_BIN" ]; then
  [ -f "$LOCAL_BIN" ] || die "no such file: $LOCAL_BIN"
  cp "$LOCAL_BIN" "$TMP/velotrak"
  say "Installing local binary $LOCAL_BIN"
else
  if [ -n "${VELOTRAK_DOWNLOAD_BASE:-}" ]; then
    BASE="$VELOTRAK_DOWNLOAD_BASE" # mirror (same asset names as a GitHub release)
  elif [ "$VERSION" = "latest" ]; then
    BASE="https://github.com/$REPO/releases/latest/download"
  else
    BASE="https://github.com/$REPO/releases/download/$VERSION"
  fi
  ASSET="velotrak-linux-$ARCH"
  say "Downloading $ASSET ($VERSION)"
  curl -fsSL --retry 3 -o "$TMP/velotrak" "$BASE/$ASSET" || die "download failed: $BASE/$ASSET"
  curl -fsSL --retry 3 -o "$TMP/checksums.txt" "$BASE/checksums.txt" || die "download failed: $BASE/checksums.txt"
  WANT="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1 }' "$TMP/checksums.txt")"
  [ -n "$WANT" ] || die "$ASSET is not listed in checksums.txt"
  GOT="$(sha256sum "$TMP/velotrak" | awk '{ print $1 }')"
  [ "$GOT" = "$WANT" ] || die "checksum mismatch for $ASSET (got $GOT, want $WANT)"
  say "Checksum OK"
fi
chmod 0755 "$TMP/velotrak"
NEW_VERSION="$("$TMP/velotrak" version 2>/dev/null || echo "velotrak (unknown version)")"

# ---- 2. Databases (Docker) ----
if [ "$USE_STACK" = 1 ]; then
  if ! command -v docker >/dev/null; then
    say "Installing Docker (get.docker.com)"
    curl -fsSL https://get.docker.com | sh || die "Docker installation failed; install Docker, then re-run this command"
  fi
  systemctl enable --now docker >/dev/null 2>&1 || true
  docker compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (install docker-compose-plugin, then re-run)"

  mkdir -p "$STACK"
  if [ ! -f "$STACK/.env" ]; then
    umask 077
    cat > "$STACK/.env" <<ENV
PG_PASSWORD=$(secret)
CH_PASSWORD=$(secret)
ENV
    umask 022
  fi
  cat > "$STACK/docker-compose.yml" <<'YAML'
# PostgreSQL + ClickHouse for Velotrak, written by install.sh (re-running
# the installer rewrites this file; passwords live in .env next to it).
# Both listen on 127.0.0.1 only; Velotrak runs as the systemd service
# "velotrak". Memory caps fit the 2 vCPU / 4 GB minimum tier.
name: velotrak
services:
  postgres:
    image: postgres:18-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: velotrak
      POSTGRES_PASSWORD: ${PG_PASSWORD}
      POSTGRES_DB: velotrak
    command: ["postgres", "-c", "shared_buffers=256MB", "-c", "max_connections=50"]
    ports: ["127.0.0.1:15432:5432"]
    volumes:
      # PG 18 keeps the cluster in a versioned subdir; mount the parent.
      - pg_data:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U velotrak"]
      interval: 5s
      timeout: 3s
      retries: 24
    mem_limit: 512m
  clickhouse:
    image: clickhouse/clickhouse-server:24.8-alpine
    restart: unless-stopped
    environment:
      CLICKHOUSE_DB: velotrak
      CLICKHOUSE_PASSWORD: ${CH_PASSWORD}
    ports: ["127.0.0.1:19000:9000"]
    ulimits: { nofile: { soft: 262144, hard: 262144 } }
    volumes:
      - ch_data:/var/lib/clickhouse
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:8123/ping"]
      interval: 5s
      timeout: 3s
      retries: 36
      start_period: 40s
    mem_limit: 1536m
volumes:
  pg_data:
  ch_data:
YAML
  say "Starting PostgreSQL + ClickHouse (first run pulls the images)"
  (cd "$STACK" && docker compose up -d --wait --quiet-pull) || die "the databases did not become healthy — see: cd $STACK && docker compose logs"
fi

# ---- 3. Velotrak ----
id velotrak >/dev/null 2>&1 || useradd --system --home "$DATA" --shell /usr/sbin/nologin velotrak
mkdir -p "$PREFIX" "$DATA"

if [ "$UPGRADE" = 1 ]; then
  cp -p "$PREFIX/velotrak" "$PREFIX/velotrak.old"
fi
install -m 0755 "$TMP/velotrak" "$PREFIX/velotrak.new"
mv -f "$PREFIX/velotrak.new" "$PREFIX/velotrak"

ENV_WRITTEN=0
if [ ! -f "$PREFIX/velotrak.env" ]; then
  MASTER=$(head -c 32 /dev/urandom | base64 | tr -d '\n')
  if [ "$USE_STACK" = 1 ]; then
    # shellcheck disable=SC1091
    . "$STACK/.env"
    PG_DSN="postgres://velotrak:${PG_PASSWORD}@127.0.0.1:15432/velotrak?sslmode=disable"
    CH_DSN="clickhouse://default:${CH_PASSWORD}@127.0.0.1:19000/velotrak"
  else
    PG_DSN="postgres://velotrak:CHANGE-ME@127.0.0.1:5432/velotrak"
    CH_DSN="clickhouse://127.0.0.1:9000/velotrak"
  fi
  umask 077
  cat > "$PREFIX/velotrak.env" <<ENV
VELOTRAK_HTTP_PORT=$PORT
VELOTRAK_ADMIN_PATH=admin
VELOTRAK_DATA_DIR=$DATA
VELOTRAK_PG_DSN=$PG_DSN
VELOTRAK_CH_DSN=$CH_DSN
VELOTRAK_MASTER_KEY=$MASTER
# TLS (pick one): ACME domain, or cert files (Cloudflare Origin CA / DNS-01)
#VELOTRAK_TLS_DOMAIN=track.example.com
# Admin on its own host (recommended): the admin answers only there,
# so hosted landers on tracking domains can never share its origin.
#VELOTRAK_ADMIN_HOST=admin.example.com
#VELOTRAK_TLS_CERT_FILE=$DATA/certs/origin.pem
#VELOTRAK_TLS_KEY_FILE=$DATA/certs/origin.key
ENV
  umask 022
  ENV_WRITTEN=1
else
  # Migrations are built into the binary now; an old override would
  # pin the previous release's files.
  sed -i '/^VELOTRAK_MIGRATIONS_DIR=/d' "$PREFIX/velotrak.env"
  PORT="$(awk -F= '$1 == "VELOTRAK_HTTP_PORT" { print $2 }' "$PREFIX/velotrak.env")"
  PORT="${PORT:-8080}"
fi

# GeoIP city database (free DB-IP city-lite, refreshed monthly). The
# country-only fallback keeps working offline; a licensed install also
# receives full databases through the datapack channel.
GEODIR="$DATA/geoip"
mkdir -p "$GEODIR"
if [ ! -f "$GEODIR/dbip-city.mmdb" ]; then
  YM=$(date +%Y-%m)
  PREV=$(date -d "1 month ago" +%Y-%m 2>/dev/null || echo "$YM")
  for ym in "$YM" "$PREV"; do
    if curl -fsSL --max-time 300 -o "$GEODIR/dbip-city.mmdb.gz" \
      "https://download.db-ip.com/free/dbip-city-lite-$ym.mmdb.gz" 2>/dev/null; then
      gunzip -f "$GEODIR/dbip-city.mmdb.gz" && say "GeoIP city database installed ($ym)" && break
    fi
  done
  [ -f "$GEODIR/dbip-city.mmdb" ] || warn "GeoIP download failed; country/region/city stay empty until a database is placed in $GEODIR."
fi

cat > /etc/systemd/system/velotrak.service <<'UNIT'
[Unit]
Description=Velotrak ad tracker
After=network-online.target docker.service postgresql.service clickhouse-server.service
Wants=network-online.target
# Keep retrying while the databases come up after a reboot.
StartLimitIntervalSec=0

[Service]
Type=simple
User=velotrak
Group=velotrak
WorkingDirectory=/opt/velotrak
EnvironmentFile=/opt/velotrak/velotrak.env
ExecStart=/opt/velotrak/velotrak
Restart=always
RestartSec=3
LimitNOFILE=65536
# The binary binds 80/443 for ACME mode when configured.
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ProtectSystem=full
ReadWritePaths=/opt/velotrak /var/lib/velotrak

[Install]
WantedBy=multi-user.target
UNIT

# The service user owns the binary (self-update replaces it) and the
# data; the database passwords stay root-only.
chown velotrak:velotrak "$PREFIX" "$PREFIX/velotrak" "$PREFIX/velotrak.env"
[ -f "$PREFIX/velotrak.old" ] && chown velotrak:velotrak "$PREFIX/velotrak.old"
chown -R velotrak:velotrak "$DATA"
systemctl daemon-reload
systemctl enable velotrak >/dev/null 2>&1

# A fresh install with external databases needs the DSNs first.
if [ "$ENV_WRITTEN" = 1 ] && [ "$USE_STACK" = 0 ]; then
  say "Installed $NEW_VERSION"
  echo "    1. Set the PostgreSQL / ClickHouse DSNs in $PREFIX/velotrak.env"
  echo "    2. systemctl start velotrak"
  echo "    3. Open http://<this-server>:$PORT/admin/#setup=<token> and create the admin account"
  echo "       (the one-time token: sudo cat $DATA/setup.token — written when the service starts)"
  exit 0
fi
if [ "$UPGRADE" = 1 ] && ! systemctl is-active --quiet velotrak && [ "$USE_STACK" = 0 ]; then
  say "Upgraded: $NEW_VERSION — start with: systemctl start velotrak"
  exit 0
fi

systemctl restart velotrak
say "Waiting for Velotrak to answer on port $PORT"
ok=0
for _ in $(seq 1 60); do
  if curl -fs --max-time 2 -o /dev/null "http://127.0.0.1:$PORT/healthz"; then ok=1; break; fi
  sleep 2
done
[ "$ok" = 1 ] || die "Velotrak did not start — see: journalctl -u velotrak -n 50 --no-pager"

# First-run setup needs the one-time token the service wrote before
# listening; only whoever ran this script sees it (SEC-011).
SETUP_TOKEN=""
[ -f "$DATA/setup.token" ] && SETUP_TOKEN="$(tr -d '[:space:]' < "$DATA/setup.token")"
HOST="$(hostname -I 2>/dev/null | awk '{ print $1 }')"
if [ "$UPGRADE" = 1 ]; then
  say "Upgraded and running: $NEW_VERSION (previous binary: $PREFIX/velotrak.old)"
  if [ -n "$SETUP_TOKEN" ]; then
    echo "    Not set up yet — open  http://${HOST:-<this-server>}:$PORT/admin/#setup=$SETUP_TOKEN"
  fi
  exit 0
fi
say "Velotrak is running: $NEW_VERSION"
echo
if [ -n "$SETUP_TOKEN" ]; then
  echo "    Open  http://${HOST:-<this-server>}:$PORT/admin/#setup=$SETUP_TOKEN  and create the admin account."
  echo "    (The link carries a one-time setup token: keep it to yourself until the account exists.)"
else
  echo "    Open  http://${HOST:-<this-server>}:$PORT/admin/  and sign in."
fi
echo "    (Open TCP port $PORT in your firewall / cloud security group if it does not load.)"
echo
echo "    Config:    $PREFIX/velotrak.env   (then: systemctl restart velotrak)"
echo "    Logs:      journalctl -u velotrak -f"
echo "    Databases: cd $STACK && docker compose ps"
echo "    Upgrade:   re-run this command"
