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

HOST=""
REMOTE_ROOT="/opt/lingniu-go-native"

usage() {
  cat <<'USAGE'
Usage:
  scripts/install-fields-projector-service.sh --host root@115.29.187.205 [--remote-root DIR]

Prepares the Kafka RAW-to-fields projector service. It does not disable the
legacy bridge projection; switch BRIDGE_DERIVE_FIELDS_FROM_RAW_ENABLED only
after the new consumer has started and its offsets are established.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --host)
      HOST="${2:-}"
      shift 2
      ;;
    --remote-root)
      REMOTE_ROOT="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [[ -z "$HOST" ]]; then
  echo "--host is required" >&2
  exit 2
fi

ssh "$HOST" "REMOTE_ROOT='$REMOTE_ROOT' bash -s" <<'REMOTE'
set -euo pipefail

env_dir="${REMOTE_ROOT}/env"
projector_env="${env_dir}/fields-projector.env"
unit="/etc/systemd/system/lingniu-go-fields-projector.service"
mkdir -p "${env_dir}"

cat >"${projector_env}" <<'ENV'
FIELDS_PROJECTOR_GROUP_PREFIX=vehicle-fields-projector-v1
KAFKA_START_OFFSET=last
FIELDS_PROJECTOR_WORKERS_PER_PROTOCOL=1
FIELDS_PROJECTOR_BATCH_SIZE=500
FIELDS_PROJECTOR_BATCH_WAIT_MS=20
FIELDS_PROJECTOR_OPERATION_TIMEOUT_MS=30000
FIELDS_PROJECTOR_RETRY_DELAY_MS=500
HEALTH_ADDR=127.0.0.1:20218
ENV
chmod 0640 "${projector_env}"

cat >"${unit}" <<UNIT
[Unit]
Description=Lingniu Go RAW Fields Projector
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=${REMOTE_ROOT}/current
EnvironmentFile=${env_dir}/base.env
EnvironmentFile=${projector_env}
Environment=GOMEMLIMIT=384MiB
ExecStart=${REMOTE_ROOT}/current/fields-projector
Restart=always
RestartSec=3
LimitNOFILE=1048576
MemoryLimit=512M
KillSignal=SIGTERM
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable lingniu-go-fields-projector.service
if [[ -x "${REMOTE_ROOT}/current/fields-projector" ]]; then
  systemd-analyze verify "${unit}"
  systemctl restart lingniu-go-fields-projector.service
  systemctl is-active lingniu-go-fields-projector.service
else
  echo "fields-projector binary is not in current release yet; service prepared for the next deploy"
fi
echo "fields projector service prepared; bridge projection remains unchanged"
REMOTE
