#!/bin/bash
# RootManage Security Audit installer (Linux). Installs ONE read-only script, a weekly timer, and a small check every 10 minutes
# that starts an audit only when you press "Run audit now" in your dashboard.
#   curl -fsSL https://rootmanage.com/agent/install-audit.sh | sudo bash -s -- --url https://rootmanage.com --key ANON --token TOKEN
# Other agents (Health, Backup, Metrics, LiteHouse, Guard, Site Clean) are not changed.
set -euo pipefail

URL=""; KEY=""; TOKEN=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --url) URL="$2"; shift 2 ;;
    --key) KEY="$2"; shift 2 ;;
    --token) TOKEN="$2"; shift 2 ;;
    *) echo "unknown argument $1" >&2; exit 1 ;;
  esac
done

if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root: sudo bash" >&2; exit 1; fi

if [[ -f /etc/rootmanage/agent.env ]]; then
  # shellcheck disable=SC1091
  . /etc/rootmanage/agent.env
  URL="${URL:-${API_URL:-}}"; KEY="${KEY:-${ANON_KEY:-}}"; TOKEN="${TOKEN:-${AGENT_TOKEN:-}}"
fi
if [[ -z "$URL" || -z "$KEY" || -z "$TOKEN" ]]; then
  echo "Need --url --key --token from RootManage, Security audit (or install Server Health first)." >&2; exit 1
fi
case "$URL" in https://*) ;; *) echo "The URL must start with https://" >&2; exit 1 ;; esac

mkdir -p /etc/rootmanage /var/lib/rootmanage /usr/local/bin
chmod 700 /var/lib/rootmanage
umask 077
if [[ ! -f /etc/rootmanage/agent.env ]]; then
  cat > /etc/rootmanage/agent.env <<EOF
API_URL=${URL}
ANON_KEY=${KEY}
AGENT_TOKEN=${TOKEN}
INTERVAL=60
UPDATE_URL=${URL%/}/agent/rootmanage-agent.sh
GITHUB_RAW=
EOF
  chmod 600 /etc/rootmanage/agent.env
fi

# Download, and check the file against its published SHA-256 before it is installed.
TMP="$(mktemp)"; SUM="$(mktemp)"
trap 'rm -f "$TMP" "$SUM"' EXIT
curl -fsSL --proto '=https' --tlsv1.2 -m 60 "${URL%/}/agent/rootmanage-audit.sh" -o "$TMP"
curl -fsSL --proto '=https' --tlsv1.2 -m 30 "${URL%/}/agent/rootmanage-audit.sh.sha256" -o "$SUM"
WANT="$(awk '{print $1; exit}' "$SUM")"
GOT="$(sha256sum "$TMP" | awk '{print $1}')"
if [[ -z "$WANT" || "$WANT" != "$GOT" ]]; then echo "The downloaded file does not match its published checksum. Nothing was installed." >&2; exit 1; fi
grep -q '^AUDIT_VERSION=' "$TMP" || { echo "The downloaded file is not the audit script. Nothing was installed." >&2; exit 1; }
install -m 755 -o root -g root "$TMP" /usr/local/bin/rootmanage-audit
ln -sf /usr/local/bin/rootmanage-audit /usr/bin/rootmanage-audit

if command -v systemctl >/dev/null 2>&1 && [[ -d /run/systemd/system ]]; then
  cat > /etc/systemd/system/rootmanage-audit.service <<'EOF'
[Unit]
Description=RootManage security audit (read-only, lowest priority)
After=network-online.target

[Service]
Type=oneshot
Nice=19
CPUQuota=10%
IOSchedulingClass=idle
MemoryMax=192M
TimeoutStartSec=240
NoNewPrivileges=yes
ProtectSystem=full
ProtectHome=read-only
ReadWritePaths=/var/lib/rootmanage
EnvironmentFile=/etc/rootmanage/agent.env
ExecStart=/usr/local/bin/rootmanage-audit --once
EOF
  cat > /etc/systemd/system/rootmanage-audit.timer <<'EOF'
[Unit]
Description=RootManage security audit once a week

[Timer]
OnCalendar=Sun *-*-* 03:30:00
RandomizedDelaySec=1h
Persistent=true
Unit=rootmanage-audit.service

[Install]
WantedBy=timers.target
EOF
  cat > /etc/systemd/system/rootmanage-audit-poll.service <<'EOF'
[Unit]
Description=RootManage security audit: has "Run audit now" been pressed? (one small request)
After=network-online.target

[Service]
Type=oneshot
Nice=19
CPUQuota=10%
IOSchedulingClass=idle
MemoryMax=192M
TimeoutStartSec=240
NoNewPrivileges=yes
ProtectSystem=full
ProtectHome=read-only
ReadWritePaths=/var/lib/rootmanage
EnvironmentFile=/etc/rootmanage/agent.env
ExecStart=/usr/local/bin/rootmanage-audit --poll
EOF
  cat > /etc/systemd/system/rootmanage-audit-poll.timer <<'EOF'
[Unit]
Description=RootManage security audit: check every 10 minutes for "Run audit now"

[Timer]
OnBootSec=5min
OnUnitActiveSec=10min
RandomizedDelaySec=60
Unit=rootmanage-audit-poll.service

[Install]
WantedBy=timers.target
EOF
  systemctl daemon-reload
  systemctl enable --now rootmanage-audit.timer
  systemctl enable --now rootmanage-audit-poll.timer
  SCHED="every Sunday at about 03:30 (systemd timer)"
else
  printf '30 3 * * 0 root /usr/local/bin/rootmanage-audit --once >/dev/null 2>&1\n*/10 * * * * root /usr/local/bin/rootmanage-audit --poll >/dev/null 2>&1\n' > /etc/cron.d/rootmanage-audit
  chmod 644 /etc/cron.d/rootmanage-audit
  SCHED="every Sunday at 03:30 (cron)"
fi

echo "RootManage Security Audit installed. It runs $SCHED."
echo "It only reads settings: it changes nothing, installs nothing and sends no passwords, keys or file contents."
echo "Running the first audit now (about a minute, lowest priority)..."
/usr/local/bin/rootmanage-audit --once || echo "The first audit could not be sent. Run it again later: sudo rootmanage-audit --once" >&2
echo
echo "Dashboard:  ${URL%/}/dashboard/audit"
echo "Run again:  press \"Run audit now\" in the dashboard (picked up within 10 minutes), or: sudo rootmanage-audit --once"
echo "Print only: sudo rootmanage-audit --print"
echo "Uninstall:  curl -fsSL ${URL%/}/agent/uninstall-audit.sh | sudo bash"
