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

HACKURITY_ENDPOINT=${HACKURITY_ENDPOINT:-"https://inmap.hackurity.io"}
HACKURITY_STREAM_ENDPOINT=${HACKURITY_STREAM_ENDPOINT:-"stream.inmap.hackurity.io:443"}
AGENT_PACKAGE_URL=${AGENT_PACKAGE_URL:-"${HACKURITY_ENDPOINT}/downloads/hackurity-agent-latest.tar.gz"}
WEB_TEMPLATES_URL=${WEB_TEMPLATES_URL:-"${HACKURITY_ENDPOINT}/downloads/web-templates.tar.gz"}
BINARY_PATH="/usr/local/bin/hackurity-agent"
INSTALL_PREFIX="/opt/hackurity-agent"
CONFIG_DIR="/etc/hackurity-agent"
DATA_DIR="/var/lib/hackurity-agent"
LOG_DIR="/var/log/hackurity-agent"
LEGACY_CACHE_DIR="/var/cache/hackurity-agent"
SERVICE_FILE="/etc/systemd/system/hackurity-agent.service"
SERVICE_USER="hackurity-agent"
CONTROL_PID_FILE="/var/run/hackurity-agent.pid"
WEB_TEMPLATE_DIR="$CONFIG_DIR/web-templates"

SUBNETS=("10.0.0.0/24")
SCAN_INTERVAL_SECS=604800
SCAN_PROFILE="default"
ENABLE_EXEC=false
ARP_DISCOVERY=false
SCANNER_LOCATION=""
UPGRADE=false
BACKUP=""

# Pinned release signing key (production: the managed key's public PEM); every download must verify against it.
read -r -d '' AGENT_SIGNING_PUBKEY <<'PUBKEY' || true
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1WCPct7RPHmzutH5K+wK
LgAiOXRhsIw5dByJk3rzsLlAhGFfC8jkCIGa29y6LLSDOmtcsAOqhesB7KFlUTbE
EzFFWpdtiwmCtEPinKMcBqt8dsPzLgkCWmLvtFo+hVU6e/CbItWc9lgqvQBX4lBk
Txmc/xlPP7EydsKP2dDn2y75ucJXSJVOJYiBBaXFJZI8ZZXENJSloQTDbcyeXaGj
VUcXAKwRuhA2tkaz1J2rK/5F9JWWTJhurTVosYI8elKkTKLsOS2k7mDoHeMCv4XD
LDpzVZr90SiYJ8eouz0C7xOulEK/7dJ+EuZl73bahW2THa5B4vFNWFk4RBLWzsvc
TbOapBZfzhpFHvqT7tCSmKxtVzh9ZWJrPy729Bapoxi/9ZQhZuRyGtC20zDNHjbx
rmTAAn7TJouHhp01fy4adVn5x4x4ptU3OK25pQuOGICCq+ZAYFHSODbPo8TjsSFl
gKybLv8awx7X25r5qwk1CKclExgDTYSE4muDwsg1jkmGhh+K/ryjePulWJJmJmg1
CCPiMIS8/XlBZ0+vO5vmaR9dpppadkh+5o7zO8hIqsjVH4RS8G5vuNyumdE47r40
MM+1agyyCIQSl7HcrWVbNdIdVNh2KiCLUjCpunFGP8ftP4DgMgxei8zgFDT2pq++
Gddt+GnjHTP5he8BqLVjF8sCAwEAAQ==
-----END PUBLIC KEY-----
PUBKEY

PINNED_PUBKEY_FILE=""
# Private download dir: fixed /tmp paths would let a local user pre-plant symlinks for root to write through.
WORK_DIR=""

cleanup() {
  local rc=$?
  if [[ $rc -ne 0 && -n "$BACKUP" ]]; then
    restore_previous
  fi
  [[ -n "$PINNED_PUBKEY_FILE" && -f "$PINNED_PUBKEY_FILE" ]] && rm -f "$PINNED_PUBKEY_FILE"
  [[ -n "$WORK_DIR" && -d "$WORK_DIR" ]] && rm -rf "$WORK_DIR"
  return 0
}
trap cleanup EXIT

print_banner() {
cat <<'B'
╔══════════════════════════════════════════════════════════════════════════════╗
║                                                                              ║
║  ██╗  ██╗ █████╗  ██████╗██╗  ██╗██╗   ██╗██████╗ ██╗████████╗██╗   ██╗      ║
║  ██║  ██║██╔══██╗██╔════╝██║ ██╔╝██║   ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝      ║
║  ███████║███████║██║     █████╔╝ ██║   ██║██████╔╝██║   ██║    ╚████╔╝       ║
║  ██╔══██║██╔══██║██║     ██╔═██╗ ██║   ██║██╔══██╗██║   ██║     ╚██╔╝        ║
║  ██║  ██║██║  ██║╚██████╗██║  ██╗╚██████╔╝██║  ██║██║   ██║      ██║         ║
║  ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝   ╚═╝      ╚═╝         ║
║                                                                              ║
╚══════════════════════════════════════════════════════════════════════════════╝
B
}

usage() {
  cat <<'USAGE'
Usage: curl -fsSL https://get-inmap.hackurity.io | sudo bash -s <customer> <code> [--arp-discovery]
       install_agent.sh [--token-file FILE] [--agent-name NAME] [--subnets CIDR[,CIDR...]]
                        [--scan-interval SECONDS] [--scan-profile default|ot-safe]
                        [--location LABEL] [--enable-exec] [--arp-discovery]
       install_agent.sh --upgrade [--arp-discovery]

With <customer> <code> (from the console's Create agent), the settings the console
chose are fetched with the code, which the agent then enrols with. The code is single
use and expires.

Otherwise the bootstrap token is read from --token-file, or asked for on the terminal.
Passing it as the first argument still works, but any local user can read it
from the process list for as long as the install runs.

Options:
  --agent-name NAME        Agent name (default: hostname). [A-Za-z0-9._-], max 64.
  --subnets CIDR[,CIDR]    IPv4 subnets to scan (default: 10.0.0.0/24). Each one is
                           also written to scan_policy.allowed_cidrs, so private
                           (RFC1918) ranges listed here are scanned with
                           allow_private kept false.
  --scan-interval SECONDS  Seconds between scheduled scans, 300..31536000
                           (default: 604800, weekly).
  --scan-profile PROFILE   default: IT networks, up to 8 hosts at once.
                           ot-safe: fragile industrial devices; a short port
                           list, one host and one probe at a time, nothing but
                           identification requests to industrial protocols.
  --location LABEL         Scanner location stamped on findings (SCANNER_LOCATION).
                           [A-Za-z0-9._-], max 64.
  --enable-exec            Enable remote command execution (exec.enabled: true).
                           Each command still needs a signed, single-use,
                           audited grant minted by an admin.
  --arp-discovery          Find hosts on this host's own subnets by ARP, including
                           ones that drop every TCP probe. Grants the agent
                           CAP_NET_RAW and nothing else; off by default. With
                           --upgrade it turns ARP on for an installed agent.
  --upgrade                Replace the agent on a host where it is installed and
                           enrolled. Keeps its identity, certificates, agent.yaml,
                           scan profile and location, and needs no token. If the
                           new agent has not connected within a minute, the
                           previous install is put back.

The agent bundle and the web template pack are each downloaded together with a
detached RSA-4096 / SHA-256 signature (.sig) and verified against a public key
pinned in this installer before anything is unpacked. A signature mismatch aborts
the install. The scanner is part of the agent binary.

Environment overrides:
  HACKURITY_ENDPOINT   Enrolment, install settings and downloads (default: https://inmap.hackurity.io).
  HACKURITY_STREAM_ENDPOINT  Agent mTLS stream host:port.
  AGENT_PACKAGE_URL    Agent bundle (default: $HACKURITY_ENDPOINT/downloads/...).
  WEB_TEMPLATES_URL    Web template pack (default: $HACKURITY_ENDPOINT/downloads/...).

Example:
  sudo bash install_agent.sh --token-file /root/inmap.token --subnets 192.168.10.0/24,10.20.0.0/24 \
      --scan-profile ot-safe --scan-interval 86400 --location bess-site-01
USAGE
}

require_root() {
  if [[ $EUID -ne 0 ]]; then
    echo "[!] Please run this installer as root (sudo)." >&2
    exit 1
  fi
}

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "[!] Missing dependency: $1" >&2
    exit 1
  fi
}

setup_pinned_pubkey() {
  PINNED_PUBKEY_FILE="$(mktemp)"
  chmod 600 "$PINNED_PUBKEY_FILE"
  printf '%s\n' "$AGENT_SIGNING_PUBKEY" > "$PINNED_PUBKEY_FILE"
  if ! openssl pkey -pubin -in "$PINNED_PUBKEY_FILE" -noout >/dev/null 2>&1; then
    echo "[!] Pinned signing public key is invalid. Aborting." >&2
    exit 1
  fi
}

# A rolling deploy can serve the archive from one release and its signature from the next, so a pair
# that does not verify is fetched again a few times before the install gives up. It exits rather than return
# unverified, so the caller never unpacks or installs a file that failed.
fetch_verified() {
  local url="$1" file="$2" sig="$3" attempt
  for attempt in 1 2 3 4; do
    rm -f "$file" "$sig"
    if curl -fsSL "$url" -o "$file" && curl -fsSL "${url}.sig" -o "$sig" && [[ -s "$file" && -s "$sig" ]] \
      && openssl dgst -sha256 -verify "$PINNED_PUBKEY_FILE" -signature "$sig" "$file" >/dev/null 2>&1; then
      echo "[✓] Signature verified: $(basename "$file")"
      return 0
    fi
    if [[ $attempt -lt 4 ]]; then
      echo "[*] $(basename "$file") did not verify; fetching it again (${attempt}/3)..."
      sleep $((attempt * 5))
    fi
  done
  rm -f "$file" "$sig"
  echo "[!] Signature verification FAILED for $(basename "$file") after 4 attempts." >&2
  echo "    The download does not match Hackurity's pinned release key." >&2
  echo "    Refusing to install an unverified artifact. Aborting." >&2
  exit 1
}

install_packages() {
  apt-get update -qq
  DEBIAN_FRONTEND=noninteractive apt-get install -y curl ca-certificates openssl || true
}

create_user() {
  if ! id -u "$SERVICE_USER" >/dev/null 2>&1; then
    useradd --system --home "$DATA_DIR" --shell /usr/sbin/nologin "$SERVICE_USER"
  fi
  # The client key lives here: nobody else gets to list or watch it.
  install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 0700 "$DATA_DIR"
  install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 0700 "$DATA_DIR/pki"
  # Root-owned so the service account cannot drop files into /etc; the group lets it read agent.yaml.
  install -d -o root -g "$SERVICE_USER" -m 0750 "$CONFIG_DIR"
  # 0750 keeps the findings in the spool subdirs off world-readable paths.
  install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 0750 "$LOG_DIR"

  # An upgrade from a root-run agent leaves these root-owned, and the least-privilege service could not read them.
  chown -R "$SERVICE_USER:$SERVICE_USER" "$DATA_DIR" "$LOG_DIR"
}

deploy_bundle() {
  local tmp="$WORK_DIR/hackurity-agent.tar.gz"
  local sig="$WORK_DIR/hackurity-agent.tar.gz.sig"
  echo "[*] Downloading and verifying the agent bundle..."
  fetch_verified "$AGENT_PACKAGE_URL" "$tmp" "$sig"

  rm -rf "$INSTALL_PREFIX"
  mkdir -p "$INSTALL_PREFIX"
  tar -xzf "$tmp" -C "$INSTALL_PREFIX" --strip-components=1 --no-same-owner --no-same-permissions
  # Older bundles carry the build account's uid; the agent runs what is in here.
  chown -R root:root "$INSTALL_PREFIX"
  chmod -R go-w "$INSTALL_PREFIX"
  install -m0755 "$INSTALL_PREFIX/bin/hackurity-agent" "$BINARY_PATH"
  # A config path that cannot exist stops a binary without --version from starting an agent here.
  local reported
  reported="$(HACKURITY_AGENT_CONFIG=/nonexistent timeout 10 "$BINARY_PATH" --version 2>/dev/null || true)"
  [[ "$reported" =~ ^hackurity-agent\ [0-9] ]] || die "The agent binary in the bundle does not run on this host."
  echo "[*] Installed ${reported}"

  rm -f "$tmp" "$sig"
}

# python3 and nmap stay installed: other software on the host may use them.
remove_legacy_scanner() {
  rm -f "$CONFIG_DIR/scanner_config.json" "$LOG_DIR/scanner_report.ndjson"
  rm -rf "$LEGACY_CACHE_DIR"
}

# Replaced whole, so templates dropped from the pack do not linger.
deploy_web_templates() {
  local tgz="$WORK_DIR/web-templates.tar.gz"
  local sig="$WORK_DIR/web-templates.tar.gz.sig"
  local stage="$WORK_DIR/web-templates"
  echo "[*] Downloading and verifying the web templates..."
  fetch_verified "$WEB_TEMPLATES_URL" "$tgz" "$sig"

  local entry
  while IFS= read -r entry; do
    if [[ ! "$entry" =~ ^[A-Za-z0-9._-]+\.yaml$ ]]; then
      echo "[!] Unexpected entry in web template archive: ${entry}. Aborting." >&2
      exit 1
    fi
  done < <(tar -tzf "$tgz")
  # Capture the listing first: grep -q exiting early under pipefail could SIGPIPE tar and skip this check.
  local listing
  listing="$(tar -tvzf "$tgz")"
  if grep -qv '^-' <<< "$listing"; then
    echo "[!] Web template archive contains non-regular files. Aborting." >&2
    exit 1
  fi

  install -d -m 0700 "$stage"
  tar -xzf "$tgz" -C "$stage" --no-same-owner --no-same-permissions
  local new_dir="${WEB_TEMPLATE_DIR}.new"
  rm -rf "$new_dir"
  install -d -o root -g "$SERVICE_USER" -m 0750 "$new_dir"
  local count=0 f
  for f in "$stage"/*.yaml; do
    [[ -f "$f" ]] || continue
    install -o root -g "$SERVICE_USER" -m 0640 "$f" "$new_dir/"
    count=$((count + 1))
  done
  if [[ $count -eq 0 ]]; then
    echo "[!] Web template archive is empty. Aborting." >&2
    exit 1
  fi
  rm -rf "$WEB_TEMPLATE_DIR"
  mv "$new_dir" "$WEB_TEMPLATE_DIR"
  rm -rf "$stage" "$tgz" "$sig"
  echo "[*] Installed ${count} web templates to ${WEB_TEMPLATE_DIR}"
}

yaml_subnet_list() {
  local indent="$1" s
  for s in "${SUBNETS[@]}"; do
    printf '%s- %s\n' "$indent" "$s"
  done
}

write_agent_config() {
  cat > "$CONFIG_DIR/agent.yaml" <<CFG
agent_name: "${AGENT_NAME}"
bootstrap_token: "${BOOTSTRAP_TOKEN}"
bootstrap_url: ${HACKURITY_ENDPOINT}/api/v1/bootstrap
stream_endpoint: ${HACKURITY_STREAM_ENDPOINT}
data_dir: ${DATA_DIR}
scanner:
  enabled: true
  log_dir: ${LOG_DIR}
  # A scan the policy skips retries after scan_retry_secs, not a full interval.
  scan_interval_secs: ${SCAN_INTERVAL_SECS}
  scan_on_startup: true
  scan_retry_secs: 3600
  subnets:
$(yaml_subnet_list "    ")
  # Enforced before any probe; with allow_private false only allowlisted private ranges are scanned.
  scan_policy:
    allowed_cidrs:
$(yaml_subnet_list "      ")
    allow_private: false
    scan_windows: []
    max_targets: 4096
    max_hosts_per_second: 0
    inter_target_delay: 0.5
exec:
  enabled: ${ENABLE_EXEC}
CFG
  chmod 0640 "$CONFIG_DIR/agent.yaml"
  chown root:hackurity-agent "$CONFIG_DIR/agent.yaml"
}

write_init_scripts() {
  {
    printf '#!/bin/bash\n'
    printf 'export SCAN_PROFILE=%q\n' "$SCAN_PROFILE"
    if [[ -n "$SCANNER_LOCATION" ]]; then
      printf 'export SCANNER_LOCATION=%q\n' "$SCANNER_LOCATION"
    fi
    if [[ "$ARP_DISCOVERY" == true ]]; then
      printf 'export ARP_DISCOVERY=1\n'
    fi
    cat <<'CTRL'
BINARY_PATH="/usr/local/bin/hackurity-agent"
CONFIG_DIR="/etc/hackurity-agent"
PID_FILE="/var/run/hackurity-agent.pid"
LOG_FILE="/var/log/hackurity-agent/agent.log"

start() {
  if [ -f "$PID_FILE" ]; then
    echo "Agent already running (PID $(cat $PID_FILE))"
    return 1
  fi
  nohup $BINARY_PATH >> $LOG_FILE 2>&1 &
  echo $! > $PID_FILE
  echo "Agent started (PID $(cat $PID_FILE))"
}

stop() {
  if [ ! -f "$PID_FILE" ]; then
    echo "Agent not running"
    return 1
  fi
  kill $(cat $PID_FILE) 2>/dev/null
  rm -f $PID_FILE
  echo "Agent stopped"
}

status() {
  if [ -f "$PID_FILE" ] && kill -0 $(cat $PID_FILE) 2>/dev/null; then
    echo "Agent running (PID $(cat $PID_FILE))"
  else
    echo "Agent stopped"
    rm -f $PID_FILE
  fi
}

case "$1" in
  start) start ;;
  stop) stop ;;
  restart) stop; sleep 2; start ;;
  status) status ;;
  *) echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac
CTRL
  } > "$INSTALL_PREFIX/bin/hackurity-control"
  chmod +x "$INSTALL_PREFIX/bin/hackurity-control"
  ln -sf "$INSTALL_PREFIX/bin/hackurity-control" /usr/local/bin/hackurity-control
}

write_systemd_unit() {
  if [[ ! -d /run/systemd/system ]]; then
    return 0
  fi

  install -d -m 0755 "$(dirname "$SERVICE_FILE")"

  # No capabilities: the scan engine needs only ordinary TCP and UDP sockets. AF_NETLINK stays for
  # name resolution. ARP discovery, when asked for, adds CAP_NET_RAW and packet sockets, nothing more.
  local caps="" families="AF_UNIX AF_INET AF_INET6 AF_NETLINK" arp_env=""
  if [[ "$ARP_DISCOVERY" == true ]]; then
    caps="CAP_NET_RAW"
    families+=" AF_PACKET"
    arp_env="Environment=ARP_DISCOVERY=1"
  fi
  cat > "$SERVICE_FILE" <<UNIT
[Unit]
Description=Hackurity Security Agent
Documentation=https://hackurity.io/docs/agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_USER}
Environment=HACKURITY_AGENT_CONFIG=${CONFIG_DIR}/agent.yaml
Environment=SCAN_PROFILE=${SCAN_PROFILE}
${SCANNER_LOCATION:+Environment=SCANNER_LOCATION=${SCANNER_LOCATION}}
${arp_env}
ExecStart=${BINARY_PATH}
Restart=on-failure
RestartSec=5
UMask=0077

AmbientCapabilities=${caps}
CapabilityBoundingSet=${caps}
NoNewPrivileges=true

ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ProtectKernelTunables=true
ProtectControlGroups=true
ReadWritePaths=${LOG_DIR} ${DATA_DIR}

RestrictAddressFamilies=${families}

[Install]
WantedBy=multi-user.target
UNIT
  chmod 0644 "$SERVICE_FILE"
  echo "[*] Wrote least-privilege systemd unit to ${SERVICE_FILE}"
}

# Old and new agents must never run the same identity at once (double scans, racing spool writes).
stop_legacy_control_agent() {
  if [[ -f "$CONTROL_PID_FILE" ]]; then
    echo "[*] Stopping legacy control-script agent before systemd activation..."
    "$INSTALL_PREFIX/bin/hackurity-control" stop || true
    rm -f "$CONTROL_PID_FILE"
  fi
}

# A leftover cron would scan outside the agent's ScanCoordinator, overlapping its scans.
remove_legacy_cron() {
  if [[ -f /etc/cron.d/hackurity-scanner ]]; then
    echo "[*] Removing legacy scanner cron (/etc/cron.d/hackurity-scanner)..."
  fi
  rm -f /etc/cron.d/hackurity-scanner
}

die() {
  echo "[!] $*" >&2
  exit 1
}

check_location() {
  if [[ -n "$SCANNER_LOCATION" && ! "$SCANNER_LOCATION" =~ ^[A-Za-z0-9._-]{1,64}$ ]]; then
    die "Invalid location '$SCANNER_LOCATION' ([A-Za-z0-9._-], max 64)."
  fi
}

read_installed() {
  [[ -d /run/systemd/system ]] || die "--upgrade needs systemd."
  [[ -f "$CONFIG_DIR/agent.yaml" ]] || die "No agent is installed here ($CONFIG_DIR/agent.yaml is missing)."
  [[ -f "$DATA_DIR/state.json" ]] || die "The installed agent never enrolled; install it again with a token."
  local kv
  local -a envs
  read -r -a envs <<< "$(systemctl show -p Environment --value hackurity-agent 2>/dev/null || true)"
  for kv in "${envs[@]}"; do
    case "$kv" in
      SCAN_PROFILE=*) SCAN_PROFILE="${kv#*=}" ;;
      SCANNER_LOCATION=*) SCANNER_LOCATION="${kv#*=}" ;;
      ARP_DISCOVERY=1) ARP_DISCOVERY=true ;;
    esac
  done
  [[ "$SCAN_PROFILE" == "default" || "$SCAN_PROFILE" == "ot-safe" ]] || die "Unknown installed scan profile '$SCAN_PROFILE'."
  check_location
  echo "[*] Upgrading in place: scan profile ${SCAN_PROFILE}${SCANNER_LOCATION:+, location ${SCANNER_LOCATION}}$( [[ "$ARP_DISCOVERY" == true ]] && echo ", ARP discovery" )"
}

# Holds the client key; it lives in WORK_DIR, so it goes when the script ends.
backup_install() {
  local path
  local -a paths=()
  for path in "$BINARY_PATH" "$INSTALL_PREFIX" "$SERVICE_FILE" "$CONFIG_DIR" "$DATA_DIR" "$LEGACY_CACHE_DIR" /etc/cron.d/hackurity-scanner; do
    [[ -e "$path" ]] && paths+=("${path#/}")
  done
  tar -C / -czpf "$WORK_DIR/previous.tgz" "${paths[@]}"
  BACKUP="$WORK_DIR/previous.tgz"
}

restore_previous() {
  set +e
  echo "[!] Upgrade failed. Last lines from the new agent:" >&2
  journalctl -u hackurity-agent -n 15 --no-pager -o cat >&2
  echo "[!] Restoring the previous install..." >&2
  systemctl stop hackurity-agent
  rm -rf "$BINARY_PATH" "$INSTALL_PREFIX" "$SERVICE_FILE" "$CONFIG_DIR" "$DATA_DIR"
  tar -C / -xzpf "$BACKUP"
  systemctl daemon-reload
  systemctl restart hackurity-agent
  echo "[!] Previous install restored and restarted." >&2
}

# The registry sends a config snapshot only to an agent it has authenticated.
agent_connected() {
  local invocation
  for _ in $(seq 1 30); do
    sleep 2
    invocation="$(systemctl show -p InvocationID --value hackurity-agent)"
    [[ -n "$invocation" ]] || continue
    if journalctl --no-pager -o cat "_SYSTEMD_INVOCATION_ID=$invocation" 2>/dev/null | grep -q "config snapshot received"; then
      return 0
    fi
  done
  return 1
}

upgrade() {
  read_installed
  require_cmd openssl
  setup_pinned_pubkey
  WORK_DIR="$(mktemp -d)"
  backup_install
  create_user
  deploy_bundle
  deploy_web_templates
  remove_legacy_scanner
  write_init_scripts
  write_systemd_unit
  remove_legacy_cron
  systemctl daemon-reload
  systemctl enable hackurity-agent
  systemctl restart hackurity-agent
  echo "[*] Waiting for the agent to connect..."
  agent_connected || die "The new agent did not connect within a minute."
  BACKUP=""
  echo "[✓] Upgrade complete: $(HACKURITY_AGENT_CONFIG=/nonexistent "$BINARY_PATH" --version) is connected."
}

valid_ipv4_cidr() {
  local value="$1" addr prefix octet
  [[ "$value" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})?$ ]] || return 1
  addr="${value%%/*}"
  if [[ "$value" == */* ]]; then
    prefix="${value#*/}"
    [[ "$prefix" =~ ^(0|[1-9][0-9]?)$ ]] && (( prefix <= 32 )) || return 1
  fi
  local IFS=.
  for octet in $addr; do
    [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] && (( octet <= 255 )) || return 1
  done
  return 0
}

# Values are interpolated into agent.yaml, JSON and the systemd unit, so each keeps to a charset needing no quoting.
# Trades the code for the settings the console attached to it. The code goes on stdin, never on curl's
# command line, and every value is checked with the same rules as the command-line options.
fetch_install_settings() {
  local response key value entry endpoint=""
  local -a entries
  echo "[*] Fetching the install settings for ${TENANT_SLUG}..."
  response=$(printf '{"tenant":"%s","code":"%s"}' "$TENANT_SLUG" "$BOOTSTRAP_TOKEN" \
    | curl -fsS --proto '=https' --tlsv1.2 --max-time 30 -H 'Content-Type: application/json' --data-binary @- \
        "${HACKURITY_ENDPOINT}/api/v1/install-config") \
    || die "The code was refused or ${HACKURITY_ENDPOINT} could not be reached. A code works once and expires; ask for a new one."
  while IFS='=' read -r key value; do
    case "$key" in
      endpoint) endpoint="$value" ;;
      stream_endpoint)
        [[ "$value" =~ ^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?:[0-9]{1,5}$ ]] || die "Invalid stream endpoint in the install settings."
        HACKURITY_STREAM_ENDPOINT="$value"
        ;;
      agent_name) AGENT_NAME="$value" ;;
      location) SCANNER_LOCATION="$value" ;;
      subnets)
        SUBNETS=()
        IFS=',' read -r -a entries <<< "$value"
        for entry in "${entries[@]}"; do
          valid_ipv4_cidr "$entry" || die "Invalid subnet '$entry' in the install settings."
          SUBNETS+=("$entry")
        done
        [[ ${#SUBNETS[@]} -gt 0 ]] || die "The install settings name no subnet."
        ;;
      scan_interval_secs)
        [[ "$value" =~ ^[1-9][0-9]{0,8}$ ]] && (( value >= 300 && value <= 31536000 )) \
          || die "Invalid scan interval in the install settings."
        SCAN_INTERVAL_SECS="$value"
        ;;
      scan_profile)
        [[ "$value" == "default" || "$value" == "ot-safe" ]] || die "Invalid scan profile in the install settings."
        SCAN_PROFILE="$value"
        ;;
      enable_exec)
        [[ "$value" == "true" || "$value" == "false" ]] || die "Invalid exec setting in the install settings."
        ENABLE_EXEC="$value"
        ;;
      "") ;;
      *) die "Unexpected install setting '$key'." ;;
    esac
  done <<< "$response"
  # The settings must come from the server this installer enrols with and downloads from.
  [[ "$endpoint" == "$HACKURITY_ENDPOINT" ]] || die "The install settings name another server ('$endpoint')."
}

parse_args() {
  if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
    usage
    exit 0
  fi
  if [[ "${1:-}" == "--upgrade" ]]; then
    [[ $# -eq 1 || ( $# -eq 2 && "$2" == "--arp-discovery" ) ]] \
      || die "--upgrade keeps the installed settings and takes no other option than --arp-discovery."
    [[ $# -eq 2 ]] && ARP_DISCOVERY=true
    UPGRADE=true
    return 0
  fi

  # One-line install: <customer> <code>. The settings come from the console through the registry.
  if [[ ( $# -eq 2 || ( $# -eq 3 && "${3:-}" == "--arp-discovery" ) ) && "$1" =~ ^[a-z0-9-]{1,50}$ && "$2" =~ ^[A-Za-z0-9_-]{20,128}$ ]]; then
    [[ $# -eq 3 ]] && ARP_DISCOVERY=true
    TENANT_SLUG="$1"
    BOOTSTRAP_TOKEN="$2"
    AGENT_NAME="$(hostname)"
    fetch_install_settings
    [[ "$AGENT_NAME" =~ ^[A-Za-z0-9._-]{1,64}$ ]] || die "Invalid agent name '$AGENT_NAME' ([A-Za-z0-9._-], max 64)."
    check_location
    return 0
  fi

  local token_file=""
  BOOTSTRAP_TOKEN="${BOOTSTRAP_TOKEN:-}"
  if [[ $# -gt 0 && "$1" != --* ]]; then
    BOOTSTRAP_TOKEN="$1"; shift
  fi
  AGENT_NAME="${AGENT_NAME:-$(hostname)}"

  local opt value entry
  local -a entries
  while [[ $# -gt 0 ]]; do
    opt="$1"
    case "$opt" in
      --agent-name|--subnets|--scan-interval|--scan-profile|--location|--token-file)
        [[ $# -ge 2 && -n "$2" && "$2" != --* ]] || die "Option $opt requires a value."
        value="$2"
        shift 2
        ;;
      --enable-exec)
        ENABLE_EXEC=true
        shift
        continue
        ;;
      --arp-discovery)
        ARP_DISCOVERY=true
        shift
        continue
        ;;
      --help|-h)
        usage
        exit 0
        ;;
      *)
        die "Unknown option: $opt"
        ;;
    esac
    case "$opt" in
      --token-file)
        token_file="$value"
        ;;
      --agent-name)
        AGENT_NAME="$value"
        ;;
      --subnets)
        SUBNETS=()
        IFS=',' read -r -a entries <<< "$value"
        for entry in "${entries[@]}"; do
          entry="${entry//[[:space:]]/}"
          [[ -z "$entry" ]] && continue
          valid_ipv4_cidr "$entry" || die "Invalid subnet '$entry' (expected IPv4 CIDR, e.g. 192.168.10.0/24)."
          SUBNETS+=("$entry")
        done
        [[ ${#SUBNETS[@]} -gt 0 ]] || die "--subnets needs at least one CIDR."
        ;;
      --scan-interval)
        [[ "$value" =~ ^[1-9][0-9]{0,8}$ ]] && (( value >= 300 && value <= 31536000 )) \
          || die "--scan-interval must be an integer between 300 and 31536000 seconds."
        SCAN_INTERVAL_SECS="$value"
        ;;
      --scan-profile)
        [[ "$value" == "default" || "$value" == "ot-safe" ]] || die "--scan-profile must be 'default' or 'ot-safe'."
        SCAN_PROFILE="$value"
        ;;
      --location)
        SCANNER_LOCATION="$value"
        ;;
    esac
  done

  if [[ -n "$token_file" ]]; then
    [[ -r "$token_file" ]] || die "Cannot read token file '$token_file'."
    BOOTSTRAP_TOKEN="$(tr -d '[:space:]' < "$token_file")"
  elif [[ -z "$BOOTSTRAP_TOKEN" ]]; then
    # The script itself may be arriving on stdin (wget | bash), so ask the terminal.
    { : < /dev/tty; } 2>/dev/null || die "No bootstrap token given. Use --token-file FILE."
    read -r -s -p "Bootstrap token: " BOOTSTRAP_TOKEN < /dev/tty
    echo > /dev/tty
  fi
  [[ "$BOOTSTRAP_TOKEN" =~ ^[A-Za-z0-9._~+/=-]+$ && ${#BOOTSTRAP_TOKEN} -le 512 ]] || die "Invalid bootstrap token."
  [[ "$AGENT_NAME" =~ ^[A-Za-z0-9._-]{1,64}$ ]] || die "Invalid agent name '$AGENT_NAME' ([A-Za-z0-9._-], max 64)."
  check_location
}

main() {
  parse_args "$@"

  print_banner
  require_root
  require_cmd curl
  if [[ "$UPGRADE" == true ]]; then
    upgrade
    return 0
  fi

  install_packages
  require_cmd openssl
  setup_pinned_pubkey
  WORK_DIR="$(mktemp -d)"
  create_user
  deploy_bundle
  deploy_web_templates
  write_agent_config
  remove_legacy_scanner
  write_init_scripts
  write_systemd_unit
  remove_legacy_cron

  # Gate on /run/systemd/system, not systemctl, so a container without live systemd uses the control script.
  if [[ -d /run/systemd/system ]]; then
    stop_legacy_control_agent
    systemctl daemon-reload
    systemctl enable hackurity-agent
    # restart, not start: start is a no-op on an active unit and would leave the old binary running.
    systemctl restart hackurity-agent
    echo "[*] Agent (re)started via systemd"
  else
    $INSTALL_PREFIX/bin/hackurity-control restart
    echo "[*] Agent (re)started via control script"
  fi

  echo "[✓] Installation complete."

  if [[ -d /run/systemd/system ]]; then
    systemctl status hackurity-agent --no-pager
  else
    $INSTALL_PREFIX/bin/hackurity-control status
  fi
}

main "$@"
