#!/usr/bin/env bash
# Install the SearchAI Index Server as a systemd service (Linux) from an
# unpacked bundle (run from the bundle root) or a source checkout after
# `zig build -Doptimize=ReleaseFast && deploy/fetch-zvec.sh`.
#
# Usage: sudo deploy/install-searchai-index.sh [--prefix /opt/searchai-index] [--port 9200] [--user searchai]
set -euo pipefail

PREFIX=/opt/searchai-index
PORT=9200
RUNUSER=searchai
while [ $# -gt 0 ]; do
  case "$1" in
    --prefix) PREFIX="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    --user) RUNUSER="$2"; shift 2 ;;
    *) echo "unknown flag $1"; exit 1 ;;
  esac
done
[ "$(uname -s)" = "Linux" ] || { echo "systemd install is Linux-only; on macOS use run.sh"; exit 1; }
[ "$(id -u)" = 0 ] || { echo "run with sudo"; exit 1; }

SRC="$(cd "$(dirname "$0")/.." && pwd)"
BIN="$SRC/bin/searchai-index-server"
[ -x "$BIN" ] || BIN="$SRC/zig-out/bin/searchai-index-server"
[ -x "$BIN" ] || { echo "server binary not found under $SRC"; exit 1; }

id -u "$RUNUSER" >/dev/null 2>&1 || useradd --system --home "$PREFIX" --shell /usr/sbin/nologin "$RUNUSER"

mkdir -p "$PREFIX/bin" "$PREFIX/lib" "$PREFIX/conf" "$PREFIX/data"
install -m 0755 "$BIN" "$PREFIX/bin/searchai-index-server"
for lib in "$SRC"/lib/libzvec*.so "$SRC"/vendor/zvec/lib/*/libzvec*.so; do
  [ -e "$lib" ] && install -m 0644 "$lib" "$PREFIX/lib/"
done
if [ ! -f "$PREFIX/conf/server.properties" ]; then
  sed "s/^server.port=.*/server.port=$PORT/" "$SRC/conf/server.properties" > "$PREFIX/conf/server.properties"
fi
chown -R "$RUNUSER:$RUNUSER" "$PREFIX/data"

sed -e "s|__PREFIX__|$PREFIX|g" -e "s|__USER__|$RUNUSER|g" \
  "$SRC/deploy/searchai-index.service" > /etc/systemd/system/searchai-index.service
systemctl daemon-reload
systemctl enable searchai-index
systemctl restart searchai-index

echo -n "waiting for /health "
for _ in $(seq 1 60); do
  if curl -fsS "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
    echo; echo "SearchAI Index Server is up: http://127.0.0.1:$PORT"
    exit 0
  fi
  echo -n "."; sleep 1
done
echo; echo "server did not become healthy — check: journalctl -u searchai-index"; exit 1
