#!/bin/sh
# Octo installer — run via `curl -fsSL https://get.<your-domain> | sh`.
#
# Backend pointing — two ways, in priority order:
#   1. CLI args:    sh install.sh --api https://x.ngrok.app --app https://y.ngrok.app
#   2. Env vars:    OCTO_API_BASE_URL=... OCTO_APP_BASE_URL=... sh install.sh
# No default URL is baked into source. The published installer gets its base
# URL injected from env at release/publish time; running this script without a
# URL from either source fails the guard below.
#
# CLI args via curl|sh:
#   curl -fsSL https://get.<your-domain> | sh -s -- --api https://x.ngrok.app
#
# Supported platforms (slice 11):
#   macOS arm64 / x86_64
#   Linux arm64 / x86_64 (glibc — Ubuntu, Debian, RHEL, Fedora, Amazon Linux 2)
#
# What gets written:
#   macOS: ~/Library/Application Support/Octo/{bin,state}/...
#   Linux: ~/.local/share/octo/{bin,state}/...      (mirrors macOS layout)
#          + ~/.local/bin/octo symlink for PATH convenience
#
# The installed binary reads endpoints.json on every invocation, so the
# same binary can target any orchestrator without rebuilding.
set -eu

# No default/brand URL lives in source. The base URLs come from the environment
# (OCTO_API_BASE_URL / OCTO_APP_BASE_URL) or the --api/--app flags; the published
# installer has them injected from env at release/publish time. If neither is
# supplied the guard below fails loudly rather than fetching from a bad host.
OCTO_API_BASE_URL="${OCTO_API_BASE_URL:-https://prototype.brands.qa.begenuin.com}"
OCTO_APP_BASE_URL="${OCTO_APP_BASE_URL:-https://prototype.brands.qa.begenuin.com}"
OCTO_UPDATE_BASE_URL="${OCTO_UPDATE_BASE_URL:-}"
OCTO_ORCHESTRATOR_WS="${OCTO_ORCHESTRATOR_WS:-}"
PREVIEW_TUNNEL_WS_URL="${PREVIEW_TUNNEL_WS_URL:-wss://preview.qa.begenuin.com/__octo/tunnel/runner/{runner_id}}"
OCTO_PREVIEW_TUNNEL_WS_URL="${OCTO_PREVIEW_TUNNEL_WS_URL:-}"
# ed25519 public key (64 hex). Substituted at deploy time; baseline
# pinned here for the test release. Reject runs with the placeholder
# unless OCTO_DEV=1 is set.
# Begenuin Public key
OCTO_PUBKEY_HEX="f65772e518bc732a502084ee5dede1a6003dcdd31fdc85aa36b5c32979cf5ffb"

# Styled output. Suppressed when stderr isn't a TTY or NO_COLOR is set,
# matching the cliui Go package's rules so logs piped to a file stay
# clean.
if [ -t 2 ] && [ -z "${NO_COLOR:-}" ]; then
  # POSIX sh has no $'...' escape syntax, so we materialize ANSI
  # codes via printf and capture them once at startup.
  C_RESET=$(printf '\033[0m')
  C_BOLD=$(printf '\033[1m')
  C_DIM=$(printf '\033[2m')
  C_CYAN=$(printf '\033[36m')
  C_GREEN=$(printf '\033[32m')
  C_YELLOW=$(printf '\033[33m')
  C_RED=$(printf '\033[31m')
  GLYPH_CHECK="✓"
  GLYPH_CROSS="✗"
  GLYPH_ARROW="→"
  GLYPH_BULLET="•"
else
  C_RESET=""; C_BOLD=""; C_DIM=""; C_CYAN=""; C_GREEN=""; C_YELLOW=""; C_RED=""
  GLYPH_CHECK="OK"; GLYPH_CROSS="x"; GLYPH_ARROW="->"; GLYPH_BULLET="*"
fi

section() { printf '\n%s%s%s%s\n' "$C_BOLD$C_CYAN" "$1" "$C_RESET" ""; }
kv()      { printf '  %s%-9s%s %s\n' "$C_DIM" "$1" "$C_RESET" "$2"; }
# step() prints an in-progress line WITHOUT a trailing newline so the
# matching done() / done_with() can overwrite it via \r — a single
# logical step renders as one line that flips from arrow→check.
step()    { printf '  %s%s%s %s'    "$C_CYAN" "$GLYPH_ARROW" "$C_RESET" "$1"; }
done_()   { printf '\r\033[2K  %s%s%s %s\n' "$C_GREEN" "$GLYPH_CHECK" "$C_RESET" "$1"; }
ok()      { printf '  %s%s%s %s\n'  "$C_GREEN" "$GLYPH_CHECK" "$C_RESET" "$1"; }
warn()    { printf '  %s%s%s %s\n'  "$C_YELLOW" "!" "$C_RESET" "$1"; }
hint()    { printf '    %s%s%s\n'   "$C_DIM" "$1" "$C_RESET"; }

# In non-TTY mode, \r is meaningless (logs to a file), so step()
# becomes ok() and done_() becomes a no-op so we don't double-print.
if [ ! -t 2 ]; then
  step()  { printf '  %s %s\n' "$GLYPH_ARROW" "$1"; }
  done_() { printf '  %s %s\n' "$GLYPH_CHECK" "$1"; }
fi

# Legacy log/die shims so existing call sites continue to work; logs
# without a leading section get treated as plain info lines.
log() { printf '%s%s%s %s\n' "$C_DIM" "$GLYPH_BULLET" "$C_RESET" "$*"; }
die() { printf '\n  %s%s%s %s%s\n' "$C_RED" "$GLYPH_CROSS" "$C_RESET" "$*" "$C_RESET" >&2; exit 1; }

# Parse `--api / --app / --update / --ws / --preview-tunnel` flags.
while [ $# -gt 0 ]; do
  case "$1" in
    --api)        OCTO_API_BASE_URL="$2"; shift 2 ;;
    --api=*)      OCTO_API_BASE_URL="${1#*=}"; shift ;;
    --app)        OCTO_APP_BASE_URL="$2"; shift 2 ;;
    --app=*)      OCTO_APP_BASE_URL="${1#*=}"; shift ;;
    --update)     OCTO_UPDATE_BASE_URL="$2"; shift 2 ;;
    --update=*)   OCTO_UPDATE_BASE_URL="${1#*=}"; shift ;;
    --ws)         OCTO_ORCHESTRATOR_WS="$2"; shift 2 ;;
    --ws=*)       OCTO_ORCHESTRATOR_WS="${1#*=}"; shift ;;
    --preview-tunnel)   PREVIEW_TUNNEL_WS_URL="$2"; shift 2 ;;
    --preview-tunnel=*) PREVIEW_TUNNEL_WS_URL="${1#*=}"; shift ;;
    -h|--help)
      cat <<USAGE
Usage: install.sh [--api URL] [--app URL] [--update URL] [--ws URL] [--preview-tunnel URL]
  --api      Orchestrator API base (required: env OCTO_API_BASE_URL or this flag)
  --app      Web app base (required: env OCTO_APP_BASE_URL or this flag)
  --update   Override URL the CLI polls for new releases
             (default: \$OCTO_API_BASE_URL/api)
  --ws       Override orchestrator WS base (default derived from --api)
  --preview-tunnel
             Preview tunnel WS template/base, e.g.
             wss://preview.example.com/__octo/tunnel/runner/{runner_id}

Targets macOS (arm64/x86_64) and Linux (arm64/x86_64, glibc).
USAGE
      exit 0
      ;;
    *) die "unknown arg: $1" ;;
  esac
done

# No default URL is baked into source. The base URLs must come from the
# environment (OCTO_API_BASE_URL / OCTO_APP_BASE_URL), the --api/--app flags, or
# be injected into the published copy at release time. If either is still empty,
# fail loudly rather than fetch from a bad host.
if [ -z "$OCTO_API_BASE_URL" ] || [ -z "$OCTO_APP_BASE_URL" ]; then
  die "no base URL configured — pass --api/--app or set OCTO_API_BASE_URL/OCTO_APP_BASE_URL"
fi

# Default the update + ws URLs from --api if the user didn't override
# them. Convert https://api.x.com → wss://api.x.com for the WS side.
if [ -z "$OCTO_UPDATE_BASE_URL" ]; then
  OCTO_UPDATE_BASE_URL="${OCTO_API_BASE_URL%/}/api"
fi
if [ -z "$OCTO_ORCHESTRATOR_WS" ]; then
  case "$OCTO_API_BASE_URL" in
    https://*)  OCTO_ORCHESTRATOR_WS="wss://${OCTO_API_BASE_URL#https://}" ;;
    http://*)   OCTO_ORCHESTRATOR_WS="ws://${OCTO_API_BASE_URL#http://}" ;;
    *)          OCTO_ORCHESTRATOR_WS="$OCTO_API_BASE_URL" ;;
  esac
fi

# Detect (os, arch) and pick the per-OS data dir. macOS keeps the
# Library path; Linux uses the XDG ~/.local/share/octo equivalent.
case "$(uname -s)-$(uname -m)" in
  Darwin-arm64)               OS=darwin; ARCH=arm64 ;;
  Darwin-x86_64)              OS=darwin; ARCH=x86_64 ;;
  Linux-aarch64|Linux-arm64)  OS=linux;  ARCH=arm64 ;;
  Linux-x86_64)               OS=linux;  ARCH=x86_64 ;;
  *) die "unsupported platform: $(uname -s)-$(uname -m)" ;;
esac

section "Octo Installer"
kv "api"    "$OCTO_API_BASE_URL"
kv "app"    "$OCTO_APP_BASE_URL"
kv "update" "$OCTO_UPDATE_BASE_URL"
kv "ws"     "$OCTO_ORCHESTRATOR_WS"
if [ -n "$PREVIEW_TUNNEL_WS_URL" ]; then
  kv "preview" "$PREVIEW_TUNNEL_WS_URL"
fi
kv "target" "$OS / $ARCH"

case "$OS" in
  darwin) OCTO_DATA_DIR="${HOME}/Library/Application Support/Octo" ;;
  linux)  OCTO_DATA_DIR="${HOME}/.local/share/octo" ;;
esac
OCTO_BIN="$OCTO_DATA_DIR/bin/octo"

# sha256: BSD `shasum -a 256` is everywhere on macOS; Linux uses
# `sha256sum`. xxd + openssl + python3 are present on Ubuntu by default.
sha256_of() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  else
    sha256sum "$1" | awk '{print $1}'
  fi
}

command -v curl    >/dev/null 2>&1 || die "missing dep: curl"
command -v xxd     >/dev/null 2>&1 || die "missing dep: xxd"
command -v openssl >/dev/null 2>&1 || die "missing dep: openssl"
command -v python3 >/dev/null 2>&1 || die "missing dep: python3"
command -v shasum  >/dev/null 2>&1 || command -v sha256sum >/dev/null 2>&1 \
  || die "missing dep: shasum or sha256sum"

section "Installing"
step "Fetching manifest"
MANIFEST_JSON="$(curl -fsSL "${OCTO_UPDATE_BASE_URL%/}/cli/latest?os=${OS}&arch=${ARCH}")"
done_ "Manifest fetched"

# Read fields without jq.
json_field() {
  python3 - "$1" "$2" <<'PY'
import json, sys
path, doc = sys.argv[1], sys.argv[2]
obj = json.loads(doc)
for part in [p for p in path.strip(".").split(".") if p]:
    obj = obj[part]
print(obj)
PY
}

VERSION="$(json_field .version    "$MANIFEST_JSON")"
BIN_URL="$(json_field .url        "$MANIFEST_JSON")"
BIN_SHA="$(json_field .sha256     "$MANIFEST_JSON")"
SIG_HEX="$(json_field .signature  "$MANIFEST_JSON")"

# Manifest may return a relative URL (when API proxies the binary
# through to a private GitHub repo). Resolve against the API base.
case "$BIN_URL" in
  /*) BIN_URL="${OCTO_API_BASE_URL%/}${BIN_URL}" ;;
esac

step "Downloading Octo $VERSION"
TMP_BIN="$(mktemp -t octo.XXXXXX)"
PUBKEY_PEM="$(mktemp -t octo-pub.XXXXXX)"
SIG_BIN="$(mktemp -t octo-sig.XXXXXX)"
trap 'rm -f "$TMP_BIN" "$PUBKEY_PEM" "$SIG_BIN"' EXIT
# Silent download — the in-place step→done line replaces the bar so
# the curl `#####` chrome doesn't clash with our prefix layout. The
# binary is only ~9 MB on broadband; sub-second on typical links.
curl -fsSL "$BIN_URL" -o "$TMP_BIN"
SIZE_MB="$(wc -c < "$TMP_BIN" | awk '{printf "%.1f MB", $1/1024/1024}')"
done_ "Downloaded Octo $VERSION ($SIZE_MB)"

step "Verifying sha256"
GOT_SHA="$(sha256_of "$TMP_BIN")"
[ "$GOT_SHA" = "$BIN_SHA" ] || die "sha256 mismatch: got $GOT_SHA want $BIN_SHA"
done_ "Verified sha256"

step "Verifying ed25519 signature"
if [ -n "${OCTO_DEV:-}" ]; then
  done_ "Skipped (OCTO_DEV=1)"
else
if [ "$OCTO_PUBKEY_HEX" = "@OCTO_PUBKEY_HEX@" ]; then
  die "installer was not finalized with a real public key (set OCTO_DEV=1 to bypass)"
fi
# Resolve an OpenSSL 3.x binary. macOS ships LibreSSL as /usr/bin/openssl,
# which doesn't support `pkeyutl -rawin` — we fall back to Homebrew's
# openssl@3 in that case. Linux distros (Ubuntu 22.04+, Debian 12+,
# RHEL/Fedora) ship OpenSSL 3 as the default.
resolve_openssl3() {
  if [ -n "${OPENSSL_BIN:-}" ] && [ -x "$OPENSSL_BIN" ]; then
    echo "$OPENSSL_BIN"; return
  fi
  if command -v openssl >/dev/null 2>&1; then
    if openssl version 2>/dev/null | grep -qE '^OpenSSL 3\.'; then
      echo "openssl"; return
    fi
  fi
  for cand in \
    /opt/homebrew/opt/openssl@3/bin/openssl \
    /usr/local/opt/openssl@3/bin/openssl; do
    if [ -x "$cand" ]; then echo "$cand"; return; fi
  done
  die "need OpenSSL 3.x for ed25519 -rawin verification (macOS: 'brew install openssl@3', or set OPENSSL_BIN)"
}
OPENSSL="$(resolve_openssl3)"

# ed25519 SubjectPublicKeyInfo prefix: 302a300506032b6570032100
printf '%s' "302a300506032b6570032100${OCTO_PUBKEY_HEX}" \
  | xxd -r -p \
  | "$OPENSSL" pkey -inform DER -pubin -out "$PUBKEY_PEM" 2>/dev/null
printf '%s' "$SIG_HEX" | xxd -r -p > "$SIG_BIN"
if ! "$OPENSSL" pkeyutl -verify -rawin -pubin -inkey "$PUBKEY_PEM" \
      -in "$TMP_BIN" -sigfile "$SIG_BIN" >/dev/null 2>&1; then
  die "ed25519 signature verification failed"
fi
done_ "Verified ed25519 signature"
fi

# Apple notarization check is best-effort and macOS-only. Linux has no
# Gatekeeper-equivalent; the ed25519 signature above is the only check.
if [ "$OS" = "darwin" ] && command -v spctl >/dev/null 2>&1; then
  if ! spctl --assess --type install "$TMP_BIN" >/dev/null 2>&1; then
    warn "binary not notarized (Gatekeeper may refuse to run)"
  fi
fi

step "Installing binary"
mkdir -p "$OCTO_DATA_DIR/bin" "$OCTO_DATA_DIR/state"
install -m 0755 "$TMP_BIN" "$OCTO_BIN"
done_ "Installed at $OCTO_BIN"

# Drop a ~/.local/bin/octo symlink on both Linux and macOS so users
# can run `octo` instead of the full $OCTO_BIN path. Ubuntu's default
# ~/.profile already puts ~/.local/bin on PATH; on macOS many users
# have it via shell rc tweaks (zsh customization, dotfiles, etc.).
# When PATH doesn't already cover it, we surface a clear hint below.
step "Linking $HOME/.local/bin/octo"
mkdir -p "$HOME/.local/bin"
ln -sf "$OCTO_BIN" "$HOME/.local/bin/octo"
done_ "Linked $HOME/.local/bin/octo"
PATH_HAS_LOCAL_BIN=1
case ":$PATH:" in
  *":$HOME/.local/bin:"*) ;;
  *) PATH_HAS_LOCAL_BIN=0 ;;
esac

# Persist URL overrides so every CLI invocation reads the right
# orchestrator without env vars or rebuilds.
step "Writing endpoints.json"
cat > "$OCTO_DATA_DIR/state/endpoints.json" <<JSON
{
  "app_base_url":     "$OCTO_APP_BASE_URL",
  "api_base_url":     "$OCTO_API_BASE_URL",
  "update_base_url":  "$OCTO_UPDATE_BASE_URL",
  "orchestrator_ws":  "$OCTO_ORCHESTRATOR_WS",
  "preview_tunnel_ws": "$PREVIEW_TUNNEL_WS_URL"
}
JSON
chmod 0644 "$OCTO_DATA_DIR/state/endpoints.json"
done_ "Wrote endpoints.json"

# Pick the short form (`octo`) when ~/.local/bin is already on PATH;
# otherwise show the full $OCTO_BIN so the next-steps line is
# actually runnable.
if [ "$PATH_HAS_LOCAL_BIN" = "1" ]; then
  CMD="octo"
else
  CMD="$OCTO_BIN"
fi

printf '\n  %s%s%s %sOcto %s installed.%s\n' \
  "$C_GREEN" "$GLYPH_CHECK" "$C_RESET" "$C_BOLD" "$VERSION" "$C_RESET"
if [ "$PATH_HAS_LOCAL_BIN" = "0" ]; then
  warn "$HOME/.local/bin is not on your PATH yet"
  if [ "$OS" = "darwin" ]; then
    # zsh is the default shell on macOS 10.15+ — point users at the
    # right rc file. (Older Macs / bash holdouts swap ~/.zshrc for
    # ~/.bash_profile; both work since the export is the same line.)
    hint "fix:  echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc && source ~/.zshrc"
  else
    hint "fix:  echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc && source ~/.bashrc"
  fi
fi

# `octo install` does the full bootstrap end-to-end (downloads
# runtime, registers daemon unit, prompts for runner name, pairs).
# Run it inline so `curl … | sh` is the only command the user has
# to type. Set OCTO_INSTALL_NO_BOOTSTRAP=1 to opt out (e.g. for
# scripted setups that want to chain a non-interactive flow).
if [ "${OCTO_INSTALL_NO_BOOTSTRAP:-0}" = "1" ]; then
  section "Next step"
  printf '  %s%s install%s   %sruntime bootstrap + pair this device%s\n\n' \
    "$C_BOLD" "$CMD" "$C_RESET" "$C_DIM" "$C_RESET"
  hint "after pairing: $CMD            (interactive dashboard)"
  hint "                 $CMD status     (daemon health)"
  printf '\n'
else
  printf '\n'
  # Always invoke via the absolute binary path — `octo` may not be on
  # PATH in this shell yet (Linux symlink, macOS without shell rc
  # tweaks). The Go binary's `octo install` handles the rest:
  # bundle download, daemon unit, pair flow, creds wizard. With curl |
  # sh we don't have an interactive TTY for stdin, so cliui's prompts
  # auto-default — runner-name uses the hostname, linger prompt prints
  # the manual command, etc. The pair flow itself is browser-driven so
  # it doesn't need stdin.
  exec "$OCTO_BIN" install
fi
