#!/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
PAIR_CODE=""
case "$#" in
  0) ;;
  2)
    if [ "$1" != "--pair" ]; then echo "Usage: join.sh [--pair ONE_TIME_CODE]" >&2; exit 2; fi
    PAIR_CODE="$2"
    if ! "$PYTHON" -c 'import re,sys; raise SystemExit(0 if re.fullmatch(r"[A-Za-z0-9_-]{22}", sys.argv[1]) else 1)' "$PAIR_CODE"; then
      echo "Invalid or malformed pairing code. Generate a new code from your signed-in Darkoza account." >&2
      exit 2
    fi
    ;;
  *) echo "Usage: join.sh [--pair ONE_TIME_CODE]" >&2; exit 2 ;;
esac
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="7ebbd6bddaadad2f72c15da7fe773f111e0dec004b61970aa99b7807f1e1cd01"
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"
if [ -n "$PAIR_CODE" ]; then
  echo "Registering and linking this device in one step..."
  "$PYTHON" "$DIR/agent.py" --enroll-pair "$PAIR_CODE"
else
  echo "Registering this device with Darkoza..."
  "$PYTHON" "$DIR/agent.py" --enroll
fi
if [ -n "$PAIR_CODE" ]; then

  CURRENT_OPT_IN=0
  if "$PYTHON" "$DIR/agent.py" --status 2>/dev/null | grep -q '\"compute_opt_in\": true'; then
    CURRENT_OPT_IN=1
  fi
  if [ -r /dev/tty ]; then
    if [ "$CURRENT_OPT_IN" -eq 1 ]; then
      printf "Keep bounded compute enabled on this device? [Y/n]: " > /dev/tty
      if IFS= read -r ANSWER < /dev/tty; then
        case "$ANSWER" in
          n|N|no|NO) "$PYTHON" "$DIR/agent.py" --disable-compute ;;
          y|Y|yes|YES|'') "$PYTHON" "$DIR/agent.py" --enable-compute ;;
          *) echo "No change to the existing local compute consent." ;;
        esac
      fi
    else
      printf "Allow bounded Darkoza compute on this device? [y/N]: " > /dev/tty
      if IFS= read -r ANSWER < /dev/tty; then
        case "$ANSWER" in
          y|Y|yes|YES) "$PYTHON" "$DIR/agent.py" --enable-compute ;;
          *) echo "Local compute remains disabled. Registration and account linking are complete." ;;
        esac
      fi
    fi
  else
    echo "No interactive terminal detected; local compute consent was not changed."
  fi
fi
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.4 (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
if [ -n "$PAIR_CODE" ]; then
  echo "Darkoza node installed and linked to your account."
else
  echo "Darkoza node installed and registered. Link it from your signed-in account to manage it."
fi
"$PYTHON" "$DIR/agent.py" --status
echo "Active by default: resource telemetry and heartbeat only."
echo "Compute: local consent + one-request account pairing + automatic eligibility checks + fresh heartbeat."
echo "Disable local compute at any time: $PYTHON \"$DIR/agent.py\" --disable-compute"
echo "Current worker: bounded prime-count and Monte Carlo pi tasks; no remote shell or arbitrary code."
