#!/usr/bin/env bash
# written by White Brood (Gemini 4 Carbon (High)) [KAAL:E6@2026-11-30T06:51:27Z · sha256:cda735f36397ddef]
# updated by White Brood (Gemini 4 Carbon (High)) [KAAL:E6@2026-11-30T06:55:24Z · prev:cda735f36397ddef -> sha256:0e96341cdd3e61fc]
# updated by White Brood (Gemini 4 Carbon (High)) [KAAL:E6@2026-11-30T06:58:18Z · prev:0e96341cdd3e61fc -> sha256:c69a7cb2bbaa069b]
# SOVEREIGN_COMMISSION: 📐 [LICENSE:ARCHITECTURAL]
# MasiDyn Chromebook Edition — Crostini (penguin) + Native ChromeOS On-the-Go Installer
#
# Usage inside Chromebook Linux terminal (penguin):
#   curl -fsSL https://masidyn.com/download/chromebook/penguin.sh | bash
#   (or: curl -fsSL https://masidyn.dev/install-chromebook.sh | bash)
set -eu
if [ -n "${BASH_VERSION:-}" ]; then
  set -o pipefail
fi

ORIGIN="${MASIDYN_ORIGIN:-https://masidyn.com}"
DEV_ORIGIN="${MASIDYN_DEV_ORIGIN:-https://masidyn.dev}"
DEV_ORIGIN="${DEV_ORIGIN%/}"
HOME_DIR="${MASIDYN_HOME:-$HOME/.masidyn}"
BIN_DIR="${MASIDYN_BIN:-$HOME/.local/bin}"
CHROMEOS_EXT_DIR="${MASIDYN_CHROMEOS_BRIDGE_DIR:-$HOME_DIR/chromeos_native_bridge}"
BRIDGE_PORT="${MASIDYN_PENGUIN_PORT:-11460}"

say() { printf '  [masidyn-chromebook] %s\n' "$*"; }
die() { printf '  [masidyn-chromebook] ERROR: %s\n' "$*" >&2; exit 1; }

PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done
[ -n "$PY" ] || die "Python 3 is required inside Crostini (penguin). Run: sudo apt update && sudo apt install -y python3 curl"

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else die "curl or wget is required"; fi
}

sha256_file() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}' | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}' | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  else
    "$PY" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$1" | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  fi
}

lookup_sha256() {
  _rel="$1"
  _base="$2"
  _sums="$3"
  awk -v rel="$_rel" -v base="$_base" '
    BEGIN { found = ""; base_found = "" }
    {
      sub(/\r$/, "")
      line = $0
      sub(/^[ \t]+/, "", line)
      if (line == "" || substr(line, 1, 1) == "#") next
      sp = match(line, /[ \t]+/)
      if (sp == 0) next
      h = substr(line, 1, sp - 1)
      if (length(h) != 64 || h !~ /^[a-fA-F0-9]+$/) next
      h = tolower(h)
      rest = substr(line, sp + RLENGTH)
      if (substr(rest, 1, 1) == "*") rest = substr(rest, 2)
      sub(/^[ \t]+/, "", rest)
      sub(/[ \t]+$/, "", rest)
      gsub(/\\/, "/", rest)
      while (substr(rest, 1, 2) == "./") rest = substr(rest, 3)
      sub(/^\/+/, "", rest)
      if (rest == rel && found == "") found = h
      else if (rest == base && base_found == "") base_found = h
    }
    END {
      if (found != "") print found
      else if (base_found != "") print base_found
    }
  ' "$_sums"
}

verify_staged() {
  _file="$1"
  _rel="$2"
  _base="${_rel##*/}"
  _sums="$3"
  [ -f "$_file" ] || die "SHA-256 verification failed for $_rel (missing staged file)"
  _expected="$(lookup_sha256 "$_rel" "$_base" "$_sums")"
  [ -n "$_expected" ] || die "SHA-256 verification failed for $_rel (missing checksum in SHA256SUMS.txt)"
  _actual="$(sha256_file "$_file")"
  [ "$_actual" = "$_expected" ] || die "SHA-256 verification failed for $_rel (expected $_expected, got $_actual)"
}

sh_quote() {
  _s="$1"
  printf "'"
  while :; do
    case "$_s" in
      *"'"*)
        printf '%s' "${_s%%"'"*}"
        printf "'\\''"
        _s="${_s#*"'"}"
        ;;
      *)
        printf '%s' "$_s"
        break
        ;;
    esac
  done
  printf "'"
}

STAGE_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t masidyn-cb)"
[ -n "$STAGE_DIR" ] && [ -d "$STAGE_DIR" ] || die "Could not create temporary staging directory"
trap 'rm -rf "$STAGE_DIR"' EXIT INT TERM

say "Detected host: $(hostname 2>/dev/null || echo penguin) · Configuring Crostini penguin + Native ChromeOS pipes..."
say "Piped Praetor seats: masidyn,white,purple,blue,green,yellow,red,orange,pink"

# 1. Stage and verify MasiDyn CLI & SDK clients against SHA256SUMS.txt before moving into $HOME_DIR.
SUMS_FILE="$STAGE_DIR/SHA256SUMS.txt"
SUMS_OK=0
if fetch "$DEV_ORIGIN/SHA256SUMS.txt" "$SUMS_FILE" 2>/dev/null; then
  SUMS_OK=1
else
  rm -f "$SUMS_FILE"
  if fetch "$DEV_ORIGIN/releases/SHA256SUMS.txt" "$SUMS_FILE" 2>/dev/null; then
    SUMS_OK=1
  fi
fi

if [ "$SUMS_OK" -eq 1 ]; then
  [ -s "$SUMS_FILE" ] || die "SHA256SUMS.txt from $DEV_ORIGIN is empty; refusing unverified install"
  for rel in clients/masidyn_pick.py clients/masidyn_client.py clients/masidyn_hardware_tier.py; do
    base="${rel##*/}"
    staged="$STAGE_DIR/$base"
    if fetch "$DEV_ORIGIN/$rel" "$staged" 2>/dev/null; then
      verify_staged "$staged" "$rel" "$SUMS_FILE"
    else
      die "Failed to fetch $rel from $DEV_ORIGIN"
    fi
  done
  mkdir -p "$HOME_DIR"
  for base in masidyn_pick.py masidyn_client.py masidyn_hardware_tier.py; do
    mv -f "$STAGE_DIR/$base" "$HOME_DIR/$base"
  done
else
  if fetch "$DEV_ORIGIN/clients/masidyn_pick.py" "$STAGE_DIR/.probe" 2>/dev/null; then
    rm -f "$STAGE_DIR/.probe"
    die "SHA256SUMS.txt unavailable from $DEV_ORIGIN; refusing to install unverified client scripts"
  fi
  rm -f "$STAGE_DIR/.probe"
  say "Offline fallback: $DEV_ORIGIN unreachable, skipping remote client fetch."
fi

mkdir -p "$HOME_DIR" "$BIN_DIR" "$CHROMEOS_EXT_DIR"

# 1b. Provision a 0600 local bridge token for CLI / non-browser callers.
TOKEN_FILE="$HOME_DIR/penguin_bridge.token"
if [ ! -s "$TOKEN_FILE" ]; then
  (
    umask 077
    "$PY" -c 'import secrets; print(secrets.token_hex(32))' > "$TOKEN_FILE"
  )
fi
chmod 600 "$TOKEN_FILE"

# 2. Write the hardened On-the-Go Crostini <-> Native ChromeOS Bridge Daemon (default loopback bind).
cat > "$HOME_DIR/penguin_bridge_daemon.py" <<'PYEOF'
#!/usr/bin/env python3
"""MasiDyn Crostini (penguin) <-> Native ChromeOS On-the-Go Bridge Daemon.

Binds loopback by default (MASIDYN_PENGUIN_BIND=127.0.0.1) and enforces strict CORS
origin allowlisting, 1 MiB body limits, and Origin/token authorization for POST requests.
Routes all Praetor seats (masidyn, white, purple, blue, green, yellow, red, orange, pink) across:
  1. Local Crostini runtime (http://127.0.0.1:11435)
  2. Home LAN OMEN Max Flagship BC-01 (http://192.168.1.10:11460 / :11435)
  3. On-the-Go Sovereign Tunnel (https://masidyn.com / https://masidyn.dev)
"""
import hmac
import json
import os
import sys
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

PORT = int(os.environ.get("MASIDYN_PENGUIN_PORT", "11460"))
BIND_HOST = os.environ.get("MASIDYN_PENGUIN_BIND", "127.0.0.1") or "127.0.0.1"
MAX_BODY_BYTES = 1048576
ALLOWED_ORIGINS = frozenset({
    "https://masidyn.com",
    "https://masidyn.ai",
    "https://masidyn.dev",
    "http://127.0.0.1:11460",
    "http://localhost:11460",
    f"http://penguin.linux.test:{PORT}",
})
TOKEN_PATH = Path(
    os.environ.get("MASIDYN_PENGUIN_TOKEN_FILE")
    or (Path(os.environ.get("MASIDYN_HOME") or (Path.home() / ".masidyn")) / "penguin_bridge.token")
)
SEATS = ["masidyn", "white", "purple", "blue", "green", "yellow", "red", "orange", "pink"]
UPSTREAMS = [
    ("local_prime", os.environ.get("MASIDYN_LOCAL_PRIME", "http://127.0.0.1:11435")),
    ("omen_lan_bc01", os.environ.get("MASIDYN_OMEN_LAN", "http://192.168.1.10:11460")),
    ("on_the_go_tunnel", os.environ.get("MASIDYN_TUNNEL_URL", "https://masidyn.com")),
]


def _load_bridge_token() -> str:
    try:
        return TOKEN_PATH.read_text(encoding="utf-8").strip()
    except OSError:
        return ""


def probe_upstream():
    for name, base in UPSTREAMS:
        path = "/health" if "11435" in base else "/api/health"
        try:
            req = urllib.request.Request(base.rstrip("/") + path, headers={"User-Agent": "MasiDyn-Penguin-Bridge/1.0"})
            with urllib.request.urlopen(req, timeout=1.2) as r:
                if 200 <= r.status < 500:
                    return {"route_id": name, "base_url": base, "on_the_go": name == "on_the_go_tunnel"}
        except Exception:
            continue
    return {"route_id": "on_the_go_tunnel", "base_url": "https://masidyn.com", "on_the_go": True}


class PenguinHandler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def _request_origin(self) -> str:
        return (self.headers.get("Origin") or "").strip()

    def _is_allowed_origin(self) -> bool:
        origin = self._request_origin()
        return bool(origin and origin in ALLOWED_ORIGINS)

    def _is_authorized(self) -> bool:
        if self._is_allowed_origin():
            return True
        supplied = (self.headers.get("X-MasiDyn-Bridge-Token") or "").strip()
        expected = _load_bridge_token()
        if supplied and expected and hmac.compare_digest(supplied, expected):
            return True
        return False

    def _cors(self):
        origin = self._request_origin()
        if origin in ALLOWED_ORIGINS:
            self.send_header("Access-Control-Allow-Origin", origin)
            self.send_header("Vary", "Origin")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-MasiDyn-Bridge-Token")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")

    def _send_json(self, status: int, payload: dict):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self._cors()
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        origin = self._request_origin()
        if origin and origin not in ALLOWED_ORIGINS:
            self.send_response(403)
            self._cors()
            self.end_headers()
            return
        self.send_response(204)
        self._cors()
        self.end_headers()

    def do_GET(self):
        route = probe_upstream()
        if self.path.startswith("/api/health") or self.path == "/health":
            self._send_json(200, {
                "ok": True,
                "node": "FFG-03-penguin",
                "host": "penguin.linux.test",
                "port": PORT,
                "active_route": route,
                "piped_seats": SEATS,
            })
            return
        self._send_json(200, {
            "schema": "masidyn-penguin-bridge/v1",
            "active_route": route,
            "piped_seats": SEATS,
            "chromeos_url": f"http://penguin.linux.test:{PORT}",
        })

    def do_POST(self):
        raw_len = self.headers.get("Content-Length")
        try:
            n = int(raw_len) if raw_len is not None else 0
        except ValueError:
            self._send_json(400, {"ok": False, "error": "invalid Content-Length"})
            return
        if n < 0 or n > MAX_BODY_BYTES:
            self.close_connection = True
            self._send_json(413, {"ok": False, "error": "payload too large", "max_body_bytes": MAX_BODY_BYTES})
            return
        if not self._is_authorized():
            if 0 < n <= 65536:
                self.rfile.read(n)
            else:
                self.close_connection = True
            self._send_json(403, {"ok": False, "error": "forbidden: allowed Origin or valid X-MasiDyn-Bridge-Token required"})
            return

        raw = self.rfile.read(n) if n > 0 else b"{}"
        route = probe_upstream()
        target = route["base_url"].rstrip("/") + "/api/chat"
        try:
            req = urllib.request.Request(target, data=raw, headers={"Content-Type": "application/json", "User-Agent": "MasiDyn-Penguin-Bridge/1.0"})
            with urllib.request.urlopen(req, timeout=90) as r:
                resp = r.read()
            self.send_response(200)
            self._cors()
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(resp)
        except Exception as exc:
            self._send_json(502, {"ok": False, "route": route, "error": f"{type(exc).__name__}: {exc}"})


if __name__ == "__main__":
    srv = HTTPServer((BIND_HOST, PORT), PenguinHandler)
    print(f"MasiDyn Crostini penguin bridge listening on http://{BIND_HOST}:{PORT} (chromeos: http://penguin.linux.test:{PORT})", flush=True)
    srv.serve_forever()
PYEOF
chmod +x "$HOME_DIR/penguin_bridge_daemon.py"

# 3. Install `masidyn-penguin-bridge` and `masidyn-penguin` launchers safely without unescaped path interpolation.
Q_PY="$(sh_quote "$PY")"
Q_HOME="$(sh_quote "$HOME_DIR")"
Q_PORT="$(sh_quote "$BRIDGE_PORT")"

cat > "$BIN_DIR/masidyn-penguin-bridge" <<'EOF'
#!/usr/bin/env bash
EOF
printf 'exec %s %s "$@"\n' "$Q_PY" "$(sh_quote "$HOME_DIR/penguin_bridge_daemon.py")" >> "$BIN_DIR/masidyn-penguin-bridge"
chmod +x "$BIN_DIR/masidyn-penguin-bridge"

cat > "$BIN_DIR/masidyn-penguin" <<'EOF'
#!/usr/bin/env bash
# MasiDyn Chromebook (Crostini penguin) On-the-Go CLI launcher
export MASIDYN_CHROMEBOOK_MODE=1
EOF
printf 'PY=%s\n' "$Q_PY" >> "$BIN_DIR/masidyn-penguin"
printf 'HOME_DIR=%s\n' "$Q_HOME" >> "$BIN_DIR/masidyn-penguin"
printf 'export MASIDYN_PENGUIN_BRIDGE="http://penguin.linux.test:"%s\n' "$Q_PORT" >> "$BIN_DIR/masidyn-penguin"
cat >> "$BIN_DIR/masidyn-penguin" <<'EOF'
if [ "${1:-}" = "--bridge" ] || [ "${1:-}" = "bridge" ]; then
  shift
  exec "$PY" "$HOME_DIR/penguin_bridge_daemon.py" "$@"
fi
if [ -f "$HOME_DIR/masidyn_pick.py" ]; then
  exec "$PY" "$HOME_DIR/masidyn_pick.py" "$@"
elif [ -f "$HOME_DIR/masidyn_chat.py" ]; then
  exec "$PY" "$HOME_DIR/masidyn_chat.py" "$@"
else
  exec "$PY" "$HOME_DIR/penguin_bridge_daemon.py" "$@"
fi
EOF
chmod +x "$BIN_DIR/masidyn-penguin"
cp "$BIN_DIR/masidyn-penguin" "$BIN_DIR/masidyn"
chmod +x "$BIN_DIR/masidyn"

say "Installed Crostini CLI: $BIN_DIR/masidyn-penguin (and $BIN_DIR/masidyn)"
say "Installed Native ChromeOS Bridge: $BIN_DIR/masidyn-penguin-bridge (http://penguin.linux.test:$BRIDGE_PORT)"
say "Bridge token provisioned at: $TOKEN_FILE (0600)"
say "Ready for On-the-Go Chromebook operation! Run: masidyn-penguin"
