#!/usr/bin/env bash
# ==============================================================================
#  preflight.sh  ·  Website Management Agent installer
#
#  A read-only readiness check. It answers one question before you buy or install:
#  does this machine and this WordPress host support everything the installer needs?
#
#  It reads. It changes nothing. It never prints a key or a password.
#
#  Run it on the machine you will install the agent on:
#      bash preflight.sh
#  Run it again on your WordPress server (over SSH) to test the host side:
#      bash preflight.sh
#
#  Public copy:  curl -fsSL https://jamesjernigan.com/preflight.sh | bash
#  Exit codes:   0 = green or yellow, 1 = red (something will block the install)
# ==============================================================================
set -uo pipefail

VERSION="1.0.1"
PASS=0; FAIL=0; WARN=0; SKIP=0

if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  G=$'\033[38;5;47m'; R=$'\033[38;5;203m'; Y=$'\033[38;5;221m'
  D=$'\033[2m'; B=$'\033[1m'; N=$'\033[0m'
else
  G=""; R=""; Y=""; D=""; B=""; N=""
fi

ok()   { printf '  %sok%s   %s\n'   "$G" "$N" "$*"; PASS=$((PASS+1)); }
bad()  { printf '  %sfail%s %s\n'   "$R" "$N" "$*"; FAIL=$((FAIL+1)); }
warn() { printf '  %swarn%s %s\n'   "$Y" "$N" "$*"; WARN=$((WARN+1)); }
skip() { printf '  %sskip%s %s\n'   "$D" "$N" "$*"; SKIP=$((SKIP+1)); }
note() { printf '       %s%s%s\n'   "$D" "$*" "$N"; }
hdr()  { printf '\n%s%s%s\n' "$B" "$*" "$N"; }

have() { command -v "$1" >/dev/null 2>&1; }

# pick a python binary without failing under set -e style callers
PYBIN=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then PYBIN="$c"; break; fi
done

# Where are we? The same script runs on two different machines, and half the checks
# are only meaningful on one of them.
WP_CONFIG=""
_d="$PWD"
for _ in 1 2 3 4 5; do
  if [ -f "$_d/wp-config.php" ]; then WP_CONFIG="$_d/wp-config.php"; break; fi
  _nd="$(dirname "$_d")"
  [ "$_nd" = "$_d" ] && break
  _d="$_nd"
done
IS_WP=0
if [ -n "$WP_CONFIG" ] || have wp; then IS_WP=1; fi

printf '\n%sWebsite Management Agent - preflight check%s  %sv%s%s\n' "$B" "$N" "$D" "$VERSION" "$N"
printf 'Read-only. Nothing on this machine or site is changed.\n'
if [ "$IS_WP" = "1" ]; then
  printf 'Context: %sthe WordPress host%s\n' "$D" "$N"
else
  printf 'Context: %sthe machine that will run the agent%s\n' "$D" "$N"
fi

# ============================================================ 1. the machine
if [ "$IS_WP" = "1" ]; then
  hdr "1. This server's base system"
else
  hdr '1. The machine the agent installs on'
fi

OS="$(uname -s 2>/dev/null || echo unknown)"
ARCH="$(uname -m 2>/dev/null || echo unknown)"
IS_WSL=0
if [ -r /proc/version ] && grep -qi microsoft /proc/version 2>/dev/null; then IS_WSL=1; fi

case "$OS" in
  Linux)
    if [ "$IS_WSL" = "1" ]; then ok "Linux inside WSL2 ($ARCH)"; else ok "Linux ($ARCH)"; fi ;;
  Darwin)
    ok "macOS ($ARCH)" ;;
  *)
    bad "$OS is not supported. The installer runs on Linux or macOS. On Windows, use WSL2 (Ubuntu)." ;;
esac

case "$ARCH" in
  x86_64|amd64|aarch64|arm64|armv7l) ok "architecture $ARCH is supported" ;;
  *) warn "architecture $ARCH is unusual; the agent runtime may not have a build for it" ;;
esac

# bash 4 is everywhere the installer runs; 3.2 on stock macOS is fine for this script
BASHV="${BASH_VERSION%%[!0-9.]*}"
if [ -n "$BASHV" ]; then
  case "$BASHV" in
    3.*|4.*|5.*) ok "bash $BASHV" ;;
    *) warn "bash $BASHV is older than expected; use bash 4 or newer" ;;
  esac
else
  warn "could not read the bash version"
fi

# disk: 2 GB is the documented minimum, 800 MB is where it actually breaks
FREE_MB=""
FREE_MB="$(df -Pm "${HOME:-/}" 2>/dev/null | awk 'NR==2{print $4}')"
case "$FREE_MB" in
  ''|*[!0-9]*) warn "could not measure free disk space" ;;
  *)
    if [ "$IS_WP" = "1" ]; then
      ok "${FREE_MB} MB free disk on the server"
    elif [ "$FREE_MB" -lt 800 ]; then
      bad "only ${FREE_MB} MB free in ${HOME:-/}. Free up at least 2 GB before installing"
    elif [ "$FREE_MB" -lt 2048 ]; then
      warn "${FREE_MB} MB free. It fits, but 2 GB is the comfortable minimum"
    else
      ok "${FREE_MB} MB free disk"
    fi ;;
esac

# memory: the agent runtime wants a real Linux box, not a 512 MB container
MEM_MB=""
if [ -r /proc/meminfo ]; then
  MEM_MB="$(awk '/^MemTotal:/{printf "%d", $2/1024}' /proc/meminfo 2>/dev/null)"
elif [ "$OS" = "Darwin" ]; then
  MEM_MB="$(( $(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1048576 ))"
fi
case "$MEM_MB" in
  ''|0|*[!0-9]*) warn "could not measure memory" ;;
  *)
    if [ "$IS_WP" = "1" ]; then
      ok "${MEM_MB} MB RAM on the server"
    elif [ "$MEM_MB" -lt 512 ]; then
      bad "only ${MEM_MB} MB RAM. The runtime and the browser tool need more"
    elif [ "$MEM_MB" -lt 1024 ]; then
      warn "${MEM_MB} MB RAM. It runs, but 1 GB or more is safer once the agent starts browsing"
    else
      ok "${MEM_MB} MB RAM"
    fi ;;
esac

# tools: curl, tar and ssh matter in both places; the rest only where the agent runs
have curl && ok "curl present" || bad "curl missing. Install it first (apt install curl / brew install curl)"
have tar  && ok "tar present"  || warn "tar missing: skill bundles may not unpack"
have ssh  && ok "ssh client present" || warn "ssh missing: the WordPress step cannot reach your site"
if [ "$IS_WP" = "1" ]; then
  skip "unzip, git and ssh-keygen are only needed on the machine that runs the agent"
else
  have unzip && ok "unzip present" || warn "unzip missing: the installer package is a zip"
  have git  && ok "git present"  || warn "git missing (only needed for repo based plugin installs)"
  have ssh-keygen && ok "ssh-keygen present" || warn "ssh-keygen missing: you would have to create the site key by hand"
fi

if [ -n "$PYBIN" ]; then
  PYV="$("$PYBIN" -c 'import sys;print("%d.%d"%sys.version_info[:2])' 2>/dev/null || echo "")"
  if [ "$IS_WP" = "1" ]; then
    skip "$PYBIN $PYV on the server (the agent's Python tooling runs on your own machine)"
  else
    case "$PYV" in
      3.1[0-9]|3.[89]|3.[2-9][0-9]) ok "$PYBIN $PYV" ;;
      3.*) warn "$PYBIN $PYV is old; 3.9 or newer is recommended" ;;
      2.*) bad "$PYBIN is Python $PYV. The site and book tooling needs Python 3" ;;
      *)   warn "could not read the Python version" ;;
    esac
    if "$PYBIN" -c 'import ssl,json,sqlite3' >/dev/null 2>&1; then
      ok "Python stdlib complete (ssl, json, sqlite3)"
    else
      bad "this Python is missing ssl, json or sqlite3. Install the full package (apt install python3 python3-pip)"
    fi
  fi
else
  if [ "$IS_WP" = "1" ]; then
    skip "no python3 on the server (not needed here)"
  else
    bad "no python3 found. Install it (apt install -y python3 python3-pip) and re-run"
  fi
fi

# ============================================================== 2. the network
hdr '2. Outbound network'

probe() {  # probe <url> <label>; any HTTP answer below 500 counts as reachable
  code="$(curl -s -o /dev/null --max-time 12 -w '%{http_code}' "$1" 2>/dev/null || echo 000)"
  case "$code" in
    000) return 1 ;;
    5*)  return 1 ;;
    *)   return 0 ;;
  esac
}

if have curl; then
  if probe "https://hermes-agent.nousresearch.com/install.sh"; then
    ok "reachable: hermes-agent.nousresearch.com (the agent runtime)"
  else
    bad "cannot reach hermes-agent.nousresearch.com. Check DNS, proxy or firewall before installing"
  fi
  if probe "https://api.telegram.org"; then
    ok "reachable: api.telegram.org (the phone control channel)"
  else
    warn "cannot reach api.telegram.org. Telegram control will not work from this network"
  fi
  if probe "https://api.stripe.com/v1/charges"; then
    ok "reachable: api.stripe.com (checkout, only if you sell)"
  else
    warn "cannot reach api.stripe.com. Stripe steps will fail if you enable payments"
  fi
else
  skip "network checks need curl"
fi

# ========================================================= 3. the WordPress host
hdr '3. The WordPress host'

if [ "$IS_WP" = "1" ]; then
  ok "this looks like a WordPress server${WP_CONFIG:+ ($WP_CONFIG)}"

  if have wp; then
    ok "WP-CLI present ($(wp --version 2>/dev/null | head -1))"
  else
    bad "WP-CLI missing. Most cPanel hosts have it; if not, the WordPress step cannot run here"
    note "ask your host for WP-CLI, or move the agent to a host that provides shell + WP-CLI"
    wp=0
  fi

  if have php; then
    PHPV="$(php -r 'echo PHP_VERSION;' 2>/dev/null || echo "")"
    case "$PHPV" in
      8.*|7.4*) ok "PHP $PHPV" ;;
      "")       warn "could not read the PHP version" ;;
      *)        warn "PHP $PHPV is older than WordPress officially supports (7.4+ needed, 8.1+ recommended)" ;;
    esac
  else
    warn "php not on PATH. WP-CLI may still work through your host's PHP binary"
  fi

  if [ "${wp:-1}" != "0" ]; then
    if wp core is-installed >/dev/null 2>&1; then
      ok "WordPress is installed here ($(wp core version 2>/dev/null | head -1))"
      SITEURL="$(wp option get siteurl 2>/dev/null | head -1 || true)"
      [ -n "$SITEURL" ] && ok "site URL readable: $SITEURL" \
                        || warn "could not read the site URL. Check file ownership or run as the account user"
      POSTS="$(wp post list --post_type=post --post_status=publish --format=count 2>/dev/null | head -1 || true)"
      case "$POSTS" in
        ''|*[!0-9]*) warn "could not count posts (the database user may lack permissions)" ;;
        *) ok "database reachable ($POSTS published posts)" ;;
      esac
    else
      bad "WP-CLI cannot see an installed WordPress from here. Run this from the WordPress root"
    fi
  fi

  if [ -d wp-content ]; then
    if [ -w wp-content ]; then ok "wp-content is writable by this user"
    else bad "wp-content is not writable by this user. The site plugin cannot be deployed"; fi
  fi

  if [ -d /usr/local/cpanel ] || have cpanel; then
    ok "cPanel host detected (the SSH key step has a known path here)"
  fi

  if [ -f .htaccess ] && grep -qi litespeed .htaccess 2>/dev/null; then
    ok "LiteSpeed cache in use (the installer knows to purge it)"
  fi
else
  skip "not a WordPress server, so the host checks did not run"
  note "Run this same command again on your site's server (SSH in first) to test the host side."
  note "That is where the two common blocks show up: no WP-CLI, and no permission to write wp-content."
fi

# ==================================================================== verdict
printf '\n'
printf '  %d passed  ·  %d warnings  ·  %d failed  ·  %d skipped\n' "$PASS" "$WARN" "$FAIL" "$SKIP"
printf '\n'

if [ "$FAIL" -eq 0 ]; then
  if [ "$IS_WP" = "1" ]; then
    WHAT="this host supports everything the installer needs"
  else
    WHAT="this machine meets every requirement"
  fi
  if [ "$WARN" -eq 0 ]; then
    printf '  %sGREEN%s  %s. The installer will run here.\n' "$G" "$N" "$WHAT"
  else
    printf '  %sGREEN (with notes)%s  %s. Nothing blocking. Read the warnings above.\n' "$G" "$N" "$WHAT"
  fi
  printf '\n%sWhat this does not check:%s your API keys, your Google or Stripe access, DNS,\n' "$D" "$N"
  printf 'your card, or whether you have 30 spare minutes. The installer tests each of those\n'
  printf 'as it reaches them, and stops with a named fix instead of a stack trace.\n\n'
  exit 0
else
  printf '  %sRED%s  %d check(s) will block the install. Fix those first.\n' "$R" "$N" "$FAIL"
  printf '\n%sCopy the output above to whoever manages this machine or host.%s\n' "$D" "$N"
  printf 'The failures name the missing piece, and none of them need a purchase to fix.\n\n'
  exit 1
fi
