#!/usr/bin/env bash
# IT4Y_SOC_AGENT_INSTALLER_2026_06_20 — IT-4You SOC one-line client installer.
#
#   curl -fsSL https://get.it-4you.com | sudo bash -s -- --key soc_XXXXXXXX
#
# Installs the SOC telemetry agents (sshd / nginx / heartbeat) on this Linux
# server, points them at the central SOC, and launches them as systemd units.
# Unattended. Re-running is idempotent (it re-installs cleanly).
set -euo pipefail

GET_BASE="${IT4Y_SOC_GET_BASE:-https://get.it-4you.com}"
ENDPOINT="https://get.it-4you.com"
DASH_URL="https://panel.it-4you.com/#/security"
API_KEY=""
HOSTNAME_OVR=""
DO_UNINSTALL=0

AGENT_DIR="/opt/it4you-soc"
CONF_DIR="/etc/it4you-soc"
CONF="${CONF_DIR}/agent.conf"
AGENT="${AGENT_DIR}/it4y-soc-agent.py"
UNITS=(it4y-soc-agent-sshd it4y-soc-agent-nginx it4y-soc-agent-heartbeat)

c_g(){ printf '\033[32m%s\033[0m\n' "$*"; }
c_y(){ printf '\033[33m%s\033[0m\n' "$*"; }
c_r(){ printf '\033[31m%s\033[0m\n' "$*" >&2; }
die(){ c_r "ERROR: $*"; exit 1; }

while [ $# -gt 0 ]; do
  case "$1" in
    --key)      API_KEY="${2:-}"; shift 2;;
    --key=*)    API_KEY="${1#*=}"; shift;;
    --endpoint) ENDPOINT="${2:-}"; shift 2;;
    --endpoint=*) ENDPOINT="${1#*=}"; shift;;
    --name)     HOSTNAME_OVR="${2:-}"; shift 2;;
    --name=*)   HOSTNAME_OVR="${1#*=}"; shift;;
    --uninstall) DO_UNINSTALL=1; shift;;
    -h|--help)  echo "usage: soc-install.sh --key soc_XXXX [--endpoint URL] [--name HOST] [--uninstall]"; exit 0;;
    *) die "unknown arg: $1";;
  esac
done

[ "$(id -u)" = "0" ] || die "must run as root (use sudo)."
command -v systemctl >/dev/null 2>&1 || die "systemd is required (systemctl not found)."

if [ "$DO_UNINSTALL" = "1" ]; then
  c_y "Uninstalling IT-4You SOC agent..."
  for u in "${UNITS[@]}"; do
    systemctl disable --now "${u}.service" >/dev/null 2>&1 || true
    rm -f "/etc/systemd/system/${u}.service"
  done
  systemctl daemon-reload || true
  rm -rf "$AGENT_DIR" "$CONF_DIR"
  c_g "Uninstalled. (audit history on the SOC dashboard is retained.)"
  exit 0
fi

[ -n "$API_KEY" ] || die "missing --key. Create a SOC API key (scope: ingest) in your Security Center, then re-run with --key soc_XXXX"
case "$API_KEY" in soc_*) :;; *) die "--key must be a SOC API key starting with 'soc_'";; esac

# --- dependencies -----------------------------------------------------------
ensure_pkg(){
  command -v "$1" >/dev/null 2>&1 && return 0
  c_y "Installing dependency: $2"
  if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 || true; apt-get install -y -qq "$2" >/dev/null 2>&1 || true
  elif command -v dnf >/dev/null 2>&1; then dnf install -y -q "$2" >/dev/null 2>&1 || true
  elif command -v yum >/dev/null 2>&1; then yum install -y -q "$2" >/dev/null 2>&1 || true
  elif command -v apk >/dev/null 2>&1; then apk add --no-cache "$2" >/dev/null 2>&1 || true
  fi
}
ensure_pkg curl curl
ensure_pkg python3 python3
command -v python3 >/dev/null 2>&1 || die "python3 is required and could not be auto-installed."
command -v curl   >/dev/null 2>&1 || die "curl is required and could not be auto-installed."

HOSTN="${HOSTNAME_OVR:-$(hostname -f 2>/dev/null || hostname)}"

# --- preflight: validate the key against the live ingest endpoint -----------
c_y "Validating SOC API key against ${ENDPOINT} ..."
PRE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST \
        -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" \
        --data "{\"host\":\"${HOSTN}\",\"event\":\"agent.install\",\"severity\":\"info\",\"kind\":\"preflight\"}" \
        "${ENDPOINT}/v1/agent/ingest" || echo "000")
case "$PRE" in
  200) c_g "Key accepted by SOC ingest endpoint.";;
  401) die "API key rejected (401). Generate a valid key in your Security Center.";;
  403) die "API key lacks 'ingest' scope (403). Create a key with scope=ingest (Security Pro+).";;
  000) die "Cannot reach ${ENDPOINT} (network/DNS/TLS). Check egress to ${ENDPOINT}.";;
  *)   die "Unexpected response (${PRE}) from ${ENDPOINT}/v1/agent/ingest.";;
esac

# --- fetch + install the agent ---------------------------------------------
install -d -m 0755 "$AGENT_DIR"
install -d -m 0750 "$CONF_DIR"
c_y "Downloading agent ..."
curl -fsSL --max-time 30 "${GET_BASE}/it4y-soc-agent.py" -o "${AGENT}.tmp" || die "failed to download agent from ${GET_BASE}/it4y-soc-agent.py"
python3 -m py_compile "${AGENT}.tmp" || die "downloaded agent failed syntax check (corrupt download?)."
mv -f "${AGENT}.tmp" "$AGENT"; chmod 0755 "$AGENT"

# detect log sources
SSHD_LOG=""; for p in /var/log/auth.log /var/log/secure; do [ -f "$p" ] && SSHD_LOG="$p" && break; done
NGINX_LOG=""; for p in /var/log/nginx/access.log; do [ -f "$p" ] && NGINX_LOG="$p" && break; done

umask 077
cat > "$CONF" <<CONF_EOF
# IT-4You SOC agent config — generated $(date -u +%Y-%m-%dT%H:%M:%SZ)
IT4Y_SOC_ENDPOINT=${ENDPOINT}
IT4Y_SOC_API_KEY=${API_KEY}
IT4Y_SOC_HOSTNAME=${HOSTN}
${SSHD_LOG:+IT4Y_SOC_SSHD_LOG=$SSHD_LOG}
${NGINX_LOG:+IT4Y_SOC_NGINX_LOG=$NGINX_LOG}
CONF_EOF
chmod 0600 "$CONF"

# --- systemd units ----------------------------------------------------------
write_unit(){  # $1=role $2=desc
  cat > "/etc/systemd/system/it4y-soc-agent-$1.service" <<UNIT_EOF
[Unit]
Description=IT-4You SOC agent ($2)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/bin/env python3 ${AGENT} $1
Restart=always
RestartSec=10
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadOnlyPaths=/
PrivateTmp=true

[Install]
WantedBy=multi-user.target
UNIT_EOF
}
write_unit sshd "SSH auth telemetry"
write_unit nginx "nginx HTTP telemetry"
write_unit heartbeat "agent heartbeat"

systemctl daemon-reload
systemctl enable --now it4y-soc-agent-sshd.service       >/dev/null 2>&1 || true
systemctl enable --now it4y-soc-agent-heartbeat.service  >/dev/null 2>&1 || true
if [ -n "$NGINX_LOG" ]; then
  systemctl enable --now it4y-soc-agent-nginx.service    >/dev/null 2>&1 || true
else
  c_y "No nginx access log found -> nginx telemetry unit installed but left stopped."
fi

sleep 2
ACTIVE=0
for u in it4y-soc-agent-sshd it4y-soc-agent-heartbeat; do
  systemctl is-active --quiet "${u}.service" && ACTIVE=$((ACTIVE+1)) || c_r "WARN: ${u} not active (journalctl -u ${u})"
done

echo
c_g "==================================================================="
c_g " IT-4You SOC agent installed."
c_g "==================================================================="
echo "  host        : ${HOSTN}"
echo "  endpoint    : ${ENDPOINT}"
echo "  sshd log    : ${SSHD_LOG:-<none detected>}"
echo "  nginx log   : ${NGINX_LOG:-<none detected>}"
echo "  active units: ${ACTIVE}/2 core"
echo "  config      : ${CONF} (0600)"
echo "  manage      : systemctl status it4y-soc-agent-sshd"
echo "  uninstall   : curl -fsSL ${GET_BASE} | sudo bash -s -- --uninstall"
echo
c_g "Live security events from this server now appear in your SOC dashboard:"
echo "  ${DASH_URL}"
