#!/bin/sh
set -eu
BASE="https://darkoza.com"
LABEL="com.darkoza.node"
PYTHON="$(command -v python3 || true)"
if [ -z "$PYTHON" ]; then echo "Darkoza Node requires Python 3.8 or newer." >&2; exit 1; fi
if ! "$PYTHON" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3,8) else 1)'; then echo "Python 3.8 or newer is required." >&2; exit 1; fi
if ! command -v curl >/dev/null 2>&1; then echo "curl is required." >&2; exit 1; fi
OS="$(uname -s 2>/dev/null || echo unknown)"
case "$OS" in Darwin|Linux) ;; *) echo "This installer currently supports macOS and Linux. Detected: $OS" >&2; exit 2 ;; esac
umask 077
DIR="$HOME/.local/share/darkoza-node"
mkdir -p "$DIR"; chmod 700 "$DIR"
TMP="$DIR/agent.py.tmp.$$"
trap 'rm -f "$TMP"' EXIT HUP INT TERM
curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 "$BASE/node/agent.py" -o "$TMP"
EXPECTED_AGENT_SHA256="52b904d3991da520816c2bd46d6f2a8debe199556f733417b76e940dab6680a5"
ACTUAL_AGENT_SHA256="$("$PYTHON" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$TMP")"
if [ "$ACTUAL_AGENT_SHA256" != "$EXPECTED_AGENT_SHA256" ]; then
  echo "Darkoza Node agent integrity check failed. Installation aborted." >&2
  exit 1
fi
"$PYTHON" -m py_compile "$TMP"
mv "$TMP" "$DIR/agent.py"; chmod 600 "$DIR/agent.py"
echo "Registering this device with Darkoza..."
"$PYTHON" "$DIR/agent.py" --enroll
"$PYTHON" "$DIR/agent.py" --once
if [ "$OS" = "Darwin" ]; then
  PLIST_DIR="$HOME/Library/LaunchAgents"; PLIST="$PLIST_DIR/$LABEL.plist"; LOG_DIR="$HOME/Library/Logs"
  mkdir -p "$PLIST_DIR" "$LOG_DIR"
  "$PYTHON" - "$PYTHON" "$DIR/agent.py" "$LOG_DIR/darkoza-node.log" "$LABEL" "$PLIST" <<'PY'
import plistlib,sys
python,agent,log_path,label,plist_path=sys.argv[1:]
with open(plist_path,"wb") as f:
    plistlib.dump({"Label":label,"ProgramArguments":[python,agent,"--daemon"],"RunAtLoad":True,"KeepAlive":True,
        "StandardOutPath":log_path,"StandardErrorPath":log_path,"ProcessType":"Background"},f)
PY
  chmod 600 "$PLIST"
  # Clear a prior disabled override before loading this per-user LaunchAgent.
  launchctl enable "gui/$(id -u)/$LABEL"
  launchctl bootout "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true
  launchctl bootstrap "gui/$(id -u)" "$PLIST"
  launchctl kickstart -k "gui/$(id -u)/$LABEL"
else
  UNIT_DIR="$HOME/.config/systemd/user"; mkdir -p "$UNIT_DIR"
  cat > "$UNIT_DIR/darkoza-node.service" <<EOF
[Unit]
Description=Darkoza Node Agent 2.4.1 (explicit enrollment, account ownership pairing, allowlisted worker, self-service revocation)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=$PYTHON $DIR/agent.py --daemon
Restart=on-failure
RestartSec=15
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=$DIR
[Install]
WantedBy=default.target
EOF
  if ! systemctl --user daemon-reload >/dev/null 2>&1 || ! systemctl --user enable --now darkoza-node.service >/dev/null 2>&1; then
    echo "Node registered, but no usable systemd user manager. Start manually: $PYTHON $DIR/agent.py --daemon" >&2
    exit 3
  fi
fi
echo
echo "Darkoza node connected."
"$PYTHON" "$DIR/agent.py" --status
echo "Permission: resource telemetry and heartbeat."
echo "Optional local opt-in: $PYTHON \"$DIR/agent.py\" --enable-compute"
echo "Compute requires local opt-in AND Darkoza admin approval."
echo "Disable local compute: $PYTHON \"$DIR/agent.py\" --disable-compute"
echo "Node worker 2.4.1 supports max-5-segment batches for bounded Monte Carlo pi plus prime-count; no remote shell or arbitrary code."
