#!/bin/bash
# Haraka Support - one-click macOS installer (self-contained)
cd "$(dirname "$0")" || true
clear
echo ""
echo " Haraka Support - one-click Mac installer"
echo " ======================================="
echo " This single file will:"
echo "   - install Node.js if needed"
echo "   - install agent + display + mouse/keyboard"
echo "   - write config to http://162.0.225.39:8443"
echo "   - enable auto-start and start the agent"
echo " Server: http://162.0.225.39:8443"
echo ""
echo " Gatekeeper: if macOS blocks this file, Finder right-click -> Open"
echo ""
echo "Running - please wait..."
SELF="$0"
PAYLOAD_START="$(awk '/^#:::PAYLOAD:::/{print NR+1; exit}' "$SELF")"
if [[ -z "$PAYLOAD_START" ]]; then
  echo "ERROR: installer payload missing"
  read -r -p "Press Enter to close..."
  exit 1
fi
TMP="$(mktemp /tmp/haraka-setup.XXXXXX.sh)"
tail -n +"$PAYLOAD_START" "$SELF" > "$TMP"
chmod +x "$TMP"
bash "$TMP"
EC=$?
rm -f "$TMP"
echo ""
if [[ $EC -eq 0 ]]; then
  echo "SUCCESS. Open http://162.0.225.39:8443 - agent should show Online. Click Connect."
  echo "Allow Accessibility + Screen Recording for Node when macOS asks."
else
  echo "Install failed (exit $EC)."
  echo "Re-download from http://162.0.225.39:8443/downloads"
fi
echo ""
read -r -p "Press Enter to close..."
exit $EC
#:::PAYLOAD:::
#!/usr/bin/env bash
# Haraka Support - macOS / Linux one-click installer (self-contained)
set -euo pipefail
export PATH="/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH:-}"
BASE='http://162.0.225.39:8443'
TOKEN='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiaW5zdGFsbCIsInN1YiI6ImFnZW50LWluc3RhbGwiLCJtYWNoaW5lSWQiOiJocy1iY2QzODY0NSIsImluc3RhbGxDb2RlIjoiUDhHNVQtOVBNMksiLCJpYXQiOjE3ODYxODc4ODUsImV4cCI6MTc4NjIxNjY4NX0.LRs6PKVfSs2hb1NmVFEfIrA5Og_JiP1y_6J4ff1nGeQ'
ROOT="${HOME}/Haraka-Support"
AGENT="${ROOT}/agent"
ZIP="/tmp/haraka-support-agent.zip"
EXTRACT="/tmp/Haraka-Support-extract"
ENROLL="/tmp/haraka-enroll.json"
OS="$(uname -s)"

echo "==> Haraka Support one-click install"
echo "    OS: ${OS}"
echo "    Server: ${BASE}"

install_node() {
  echo "==> Installing Node.js 18+ ..."
  if [[ "${OS}" == "Darwin" ]]; then
    if command -v brew >/dev/null 2>&1; then
      brew install node || true
    fi
  else
    if command -v apt-get >/dev/null 2>&1; then
      sudo apt-get update -qq
      sudo apt-get install -y ca-certificates curl gnupg
      if ! command -v node >/dev/null 2>&1; then
        curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
        sudo apt-get install -y nodejs || sudo apt-get install -y nodejs npm || true
      fi
    elif command -v dnf >/dev/null 2>&1; then
      sudo dnf install -y nodejs npm || true
    elif command -v pacman >/dev/null 2>&1; then
      sudo pacman -Sy --noconfirm nodejs npm || true
    elif command -v zypper >/dev/null 2>&1; then
      sudo zypper --non-interactive install nodejs20 npm || sudo zypper --non-interactive install nodejs npm || true
    elif command -v brew >/dev/null 2>&1; then
      brew install node || true
    fi
  fi
}

if ! command -v node >/dev/null 2>&1; then
  install_node
fi
if ! command -v node >/dev/null 2>&1; then
  echo "ERROR: Node.js 18+ required. Install from https://nodejs.org then re-run this installer. (exit 2)"
  exit 2
fi
NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]" 2>/dev/null || echo 0)"
if [[ "${NODE_MAJOR}" -lt 18 ]]; then
  echo "Node $(node -v) is too old — upgrading..."
  install_node
  NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]" 2>/dev/null || echo 0)"
fi
if [[ "${NODE_MAJOR}" -lt 18 ]]; then
  echo "ERROR: Node.js 18+ required (found $(node -v)). Exit 2."
  exit 2
fi
echo "    Node: $(command -v node) ($(node -v))"

if [[ "${OS}" == "Linux" ]] && [[ -n "${WAYLAND_DISPLAY:-}" && -z "${DISPLAY:-}" ]]; then
  echo "ERROR: Wayland-only session - X11 required. Switch session or set DISPLAY=:0. (exit 3)"
  exit 3
fi

if ! command -v unzip >/dev/null 2>&1; then
  echo "==> Installing unzip..."
  if command -v apt-get >/dev/null 2>&1; then sudo apt-get update -qq && sudo apt-get install -y unzip
  elif command -v dnf >/dev/null 2>&1; then sudo dnf install -y unzip
  elif command -v brew >/dev/null 2>&1; then brew install unzip
  elif command -v pacman >/dev/null 2>&1; then sudo pacman -Sy --noconfirm unzip
  else echo "ERROR: install unzip and re-run"; exit 1
  fi
fi
if ! command -v curl >/dev/null 2>&1; then
  echo "ERROR: curl is required"; exit 1
fi

echo "==> Stopping any old agent..."
if [[ "${OS}" == "Darwin" ]]; then
  launchctl bootout "gui/$(id -u)/com.haraka.support.agent" 2>/dev/null || true
fi
if [[ "${OS}" == "Linux" ]]; then
  systemctl --user stop haraka-support-agent.service 2>/dev/null || true
fi
pkill -f "${HOME}/Haraka-Support/agent" 2>/dev/null || true
sleep 1

echo "==> Downloading agent package..."
curl -fsSL "${BASE}/api/agent/download.zip?t=${TOKEN}" -o "${ZIP}"
if [[ ! -s "${ZIP}" ]]; then
  echo "ERROR: agent download failed"; exit 1
fi

echo "==> Extracting to ${ROOT} ..."
rm -rf "${EXTRACT}"
mkdir -p "${EXTRACT}" "${ROOT}/logs" "${ROOT}/config"
unzip -qo "${ZIP}" -d "${EXTRACT}"
SRC="${EXTRACT}/Haraka-Support"
if [[ ! -d "${SRC}" ]]; then
  SRC="$(find "${EXTRACT}" -maxdepth 2 -type d -name 'agent' -print 2>/dev/null | head -1 | xargs dirname 2>/dev/null || true)"
fi
if [[ -z "${SRC:-}" || ! -d "${SRC}" ]]; then
  echo "ERROR: unexpected zip layout"; exit 1
fi
if command -v rsync >/dev/null 2>&1; then
  rsync -a "${SRC}/" "${ROOT}/"
else
  cp -R "${SRC}/." "${ROOT}/"
fi

echo "==> Writing config (server + credentials)..."
curl -fsSL "${BASE}/api/agent/enroll?t=${TOKEN}" -o "${ENROLL}"
node -e '
const fs=require("fs");
const c=JSON.parse(fs.readFileSync(process.argv[1],"utf8"));
const root=process.argv[2];
const connect=c.serverUrl || process.argv[3];
const lines=[
  "SERVER_URL="+connect,
  "AGENT_SERVER_URL="+connect,
  "PUBLIC_URL="+connect,
  "ADMIN_USERNAME="+c.username,
  "ADMIN_PASSWORD="+c.password,
  "AGENT_USERNAME="+c.username,
  "AGENT_PASSWORD="+c.password,
  "JWT_SECRET=agent-local-unused",
];
if (c.machineId) lines.push("AGENT_MACHINE_ID="+c.machineId);
lines.push("");
fs.writeFileSync(root+"/.env", lines.join("\n"));
if (c.machineId) {
  fs.mkdirSync(root+"/config", {recursive:true});
  fs.writeFileSync(root+"/config/machine-id.txt", c.machineId);
}
console.log(connect);
' "${ENROLL}" "${ROOT}" "${BASE}" >/tmp/haraka-connect-url.txt
CONNECT="$(tr -d '[:space:]' </tmp/haraka-connect-url.txt)"
export SERVER_URL="${CONNECT}"
export AGENT_SERVER_URL="${CONNECT}"
MACHINE_ID="$(grep -E '^AGENT_MACHINE_ID=' "${ROOT}/.env" | head -1 | cut -d= -f2- | tr -d '"' || true)"
MACHINE_ID="${MACHINE_ID:-$(hostname)}"
echo "${MACHINE_ID}" > "${ROOT}/config/machine-id.txt"

chmod +x "${ROOT}/agent/run-agent.sh" 2>/dev/null || true
chmod +x "${ROOT}/scripts/"*.sh 2>/dev/null || true

echo "==> OS tools (display + mouse/keyboard)..."
case "${OS}" in
  Darwin)
    if [[ -f "${ROOT}/scripts/install-cliclick-mac.sh" ]]; then
      bash "${ROOT}/scripts/install-cliclick-mac.sh" || true
    fi
    if [[ -f "${ROOT}/scripts/build-mac-input.sh" ]]; then
      bash "${ROOT}/scripts/build-mac-input.sh" || true
    fi
    export PATH="${ROOT}/agent/tools:${PATH}"
    ;;
  Linux)
    export DISPLAY="${DISPLAY:-:0}"
    need=0
    command -v xdotool >/dev/null 2>&1 || need=1
    command -v scrot >/dev/null 2>&1 || command -v import >/dev/null 2>&1 || need=1
    if [[ "${need}" -eq 1 ]]; then
      if command -v apt-get >/dev/null 2>&1; then sudo apt-get update -qq && sudo apt-get install -y xdotool scrot imagemagick
      elif command -v dnf >/dev/null 2>&1; then sudo dnf install -y xdotool scrot ImageMagick
      elif command -v pacman >/dev/null 2>&1; then sudo pacman -Sy --noconfirm xdotool scrot imagemagick
      elif command -v zypper >/dev/null 2>&1; then sudo zypper --non-interactive install xdotool scrot ImageMagick
      else echo "WARNING: install xdotool + scrot manually for control"; fi
    fi
    ;;
esac

echo "==> Installing agent dependencies..."
npm install --prefix "${AGENT}" --no-fund --no-audit
(cd "${AGENT}" && node -e "require('ws'); require('screenshot-desktop'); console.log('deps-ok')")

echo "==> Registering auto-start + starting agent..."
mkdir -p "${ROOT}/logs"
case "${OS}" in
  Darwin)
    LABEL="com.haraka.support.agent"
    PLIST="${HOME}/Library/LaunchAgents/${LABEL}.plist"
    AGENT_PATH="/usr/sbin:/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin:${ROOT}/agent/tools:${ROOT}/tools"
    mkdir -p "${HOME}/Library/LaunchAgents"
    cat > "${PLIST}" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>${AGENT}/run-agent.sh</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${AGENT}</string>
  <key>ProcessType</key>
  <string>Interactive</string>
  <key>ThrottleInterval</key>
  <integer>5</integer>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>${AGENT_PATH}</string>
    <key>AGENT_SERVER_URL</key>
    <string>${CONNECT}</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${ROOT}/logs/agent.out.log</string>
  <key>StandardErrorPath</key>
  <string>${ROOT}/logs/agent.err.log</string>
</dict>
</plist>
PLIST
    launchctl bootout "gui/$(id -u)/${LABEL}" 2>/dev/null || true
    launchctl bootstrap "gui/$(id -u)" "${PLIST}"
    launchctl kickstart -k "gui/$(id -u)/${LABEL}"
    echo "    macOS LaunchAgent installed"
    echo "    Grant Accessibility + Screen Recording to: $(command -v node)"
    ;;
  Linux)
    UNIT="${HOME}/.config/systemd/user/haraka-support-agent.service"
    mkdir -p "$(dirname "${UNIT}")"
    cat > "${UNIT}" <<UNIT
[Unit]
Description=Haraka Support Agent
After=network-online.target graphical-session.target
Wants=graphical-session.target

[Service]
Type=simple
WorkingDirectory=${AGENT}
ExecStart=/bin/bash ${AGENT}/run-agent.sh
Restart=always
RestartSec=5
Environment=DISPLAY=${DISPLAY:-:0}
Environment=AGENT_SERVER_URL=${CONNECT}
Environment=PATH=/usr/sbin:/usr/bin:/bin:/usr/local/bin:/usr/bin

[Install]
WantedBy=default.target
UNIT
    systemctl --user daemon-reload
    systemctl --user enable --now haraka-support-agent.service
    loginctl enable-linger "$USER" 2>/dev/null || true
    echo "    Linux systemd user service installed"
    ;;
esac

echo "==> Waiting for agent..."
ONLINE=0
for i in 1 2 3 4 5 6 7 8 9 10 11 12; do
  sleep 2
  if pgrep -f "${ROOT}/agent/src/index.js" >/dev/null 2>&1; then ONLINE=1; break; fi
  if [[ -f "${ROOT}/logs/agent.log" ]] && grep -Eiq 'Connected|WebSocket|registered|hello' "${ROOT}/logs/agent.log" 2>/dev/null; then ONLINE=1; break; fi
  if [[ -f "${ROOT}/logs/agent.out.log" ]] && grep -Eiq 'Connected|WebSocket|registered|hello' "${ROOT}/logs/agent.out.log" 2>/dev/null; then ONLINE=1; break; fi
done

echo ""
echo "=============================================="
echo " ONE-CLICK INSTALL COMPLETE"
echo " Machine ID:  ${MACHINE_ID}"
echo " Server:      ${CONNECT}"
if [[ "${ONLINE}" -eq 1 ]]; then
  echo " Agent:       running - open console and Connect"
else
  echo " Agent:       started (may take a few more seconds)"
fi
echo " Display + mouse + keyboard included in this install."
echo "=============================================="

