#!/usr/bin/env bash
# ArcIn Connector Agent - Linux installer
#
# Installs the agent as a systemd service.
#
# Standard usage (from inside the extracted bundle, either at its root
# or from within the scripts/ directory):
#   sudo ./install-agent-linux.sh
#
# The installer auto-locates the right Linux binary at ../bin/ relative
# to itself (picking amd64 or arm64 by `uname -m`) and the example
# config at ../configs/agent.example.yaml.
#
# Override either with explicit positional arguments if needed:
#   sudo ./install-agent-linux.sh /path/to/arcin-agent /path/to/agent.example.yaml

set -euo pipefail

# --- Resolve bundle-relative defaults from the script's own location ---
# Bundle layout when extracted from arcin-connector.zip:
#   arcin-connector/
#     bin/arcin-agent-linux-amd64
#     bin/arcin-agent-linux-arm64
#     configs/agent.example.yaml
#     scripts/install-agent-linux.sh   <-- $SCRIPT_DIR
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUNDLE_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Auto-pick architecture
case "$(uname -m)" in
  x86_64|amd64)         ARCH="amd64" ;;
  aarch64|arm64)        ARCH="arm64" ;;
  *)                    ARCH="" ;;
esac

DEFAULT_BINARY=""
if [[ -n "$ARCH" && -f "$BUNDLE_ROOT/bin/arcin-agent-linux-$ARCH" ]]; then
  DEFAULT_BINARY="$BUNDLE_ROOT/bin/arcin-agent-linux-$ARCH"
fi

BINARY_SRC="${1:-$DEFAULT_BINARY}"
BINARY_DST="/usr/local/bin/arcin-agent"
CONFIG_DIR="/etc/arcin-agent"
CONFIG_FILE="${CONFIG_DIR}/agent.yaml"
EXAMPLE_CONFIG="${2:-$BUNDLE_ROOT/configs/agent.example.yaml}"
SERVICE_USER="arcin-agent"
SERVICE_FILE="/etc/systemd/system/arcin-agent.service"
LOG_DIR="/var/log/arcin-agent"

need_root() {
  if [[ $EUID -ne 0 ]]; then
    echo "error: must run as root (try: sudo $0)" >&2
    exit 1
  fi
}

need_binary() {
  if [[ -z "$BINARY_SRC" ]]; then
    echo "error: could not auto-detect binary for architecture '$(uname -m)'" >&2
    echo "       pass an explicit path as the first argument" >&2
    exit 1
  fi
  if [[ ! -f "$BINARY_SRC" ]]; then
    echo "error: binary not found at $BINARY_SRC" >&2
    echo "       run from inside the extracted arcin-connector bundle, or pass an explicit path" >&2
    exit 1
  fi
  echo "using binary: $BINARY_SRC"
  echo "using example config: $EXAMPLE_CONFIG"
}

create_user() {
  if ! id -u "$SERVICE_USER" >/dev/null 2>&1; then
    echo "creating service user: $SERVICE_USER"
    useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"
  else
    echo "service user $SERVICE_USER already exists"
  fi
}

install_binary() {
  echo "installing binary to $BINARY_DST"
  install -m 0755 -o root -g root "$BINARY_SRC" "$BINARY_DST"
}

install_config() {
  mkdir -p "$CONFIG_DIR"
  chown root:"$SERVICE_USER" "$CONFIG_DIR"
  chmod 0750 "$CONFIG_DIR"

  if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "installing config to $CONFIG_FILE (edit before starting)"
    cat > "$CONFIG_FILE" <<'YAML'
agent:
  customer_id: "REPLACE_ME"
  agent_id: ""
  sources:
    - id: "mysql-prod"
      type: "mysql"
      dsn_env_var: "ARCIN_SOURCE_MYSQL_PROD_DSN"
      role: "readonly"

control_plane:
  url: "wss://REPLACE_ME:8443/connect"
  token: "REPLACE_ME"
  heartbeat_interval: 30s
  handshake_timeout: 10s
  reconnect_min_wait: 1s
  reconnect_max_wait: 60s

log:
  level: info
  format: json
YAML
    chown root:"$SERVICE_USER" "$CONFIG_FILE"
    chmod 0640 "$CONFIG_FILE"
  else
    echo "$CONFIG_FILE already exists, not overwriting"
  fi
}

install_logdir() {
  mkdir -p "$LOG_DIR"
  chown "$SERVICE_USER":"$SERVICE_USER" "$LOG_DIR"
  chmod 0750 "$LOG_DIR"
}

install_unit() {
  echo "writing systemd unit: $SERVICE_FILE"
  cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=ArcIn Connector Agent
Documentation=https://arcin.io/docs/agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_USER}
ExecStart=${BINARY_DST} --config ${CONFIG_FILE}
Restart=always
RestartSec=5s
StandardOutput=append:${LOG_DIR}/agent.log
StandardError=append:${LOG_DIR}/agent.log

# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=${LOG_DIR}
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictNamespaces=true
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallArchitectures=native

[Install]
WantedBy=multi-user.target
EOF
  chmod 0644 "$SERVICE_FILE"
}

enable_service() {
  echo "reloading systemd and enabling service"
  systemctl daemon-reload
  systemctl enable arcin-agent.service
  echo
  echo "install complete."
  echo "next steps:"
  echo "  1. edit ${CONFIG_FILE} with your customer_id, token, control_plane.url"
  echo "  2. sudo systemctl start arcin-agent"
  echo "  3. sudo journalctl -u arcin-agent -f    # or: tail -f ${LOG_DIR}/agent.log"
}

main() {
  need_root
  need_binary
  create_user
  install_binary
  install_config
  install_logdir
  install_unit
  enable_service
}

main "$@"
