#!/usr/bin/env bash
# RXShell bootstrap installer — downloads signed rxs into ~/.rxshell/bin
# Usage:
#   curl -fsSL https://rxshell.com/install.sh | bash
#   RXSHELL_VERSION=0.1.0 curl -fsSL https://rxshell.com/install.sh | bash
set -euo pipefail

VERSION="${RXSHELL_VERSION:-latest}"
BASE="${RXSHELL_BASE_URL:-https://cdn.rxshell.com}"
HOME_DIR="${RXSHELL_HOME:-$HOME/.rxshell}"
BIN_DIR="$HOME_DIR/bin"
os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"

case "$os-$arch" in
  linux-x86_64|linux-amd64) platform="linux-amd64"; artifact="rxs-linux-amd64" ;;
  *)
    echo "error: unsupported platform: $os-$arch" >&2
    echo "  Phase 2 bootstrap supports linux-amd64 only." >&2
    echo "  Build from source: cargo install --git https://github.com/rxshell/rxshell --locked" >&2
    echo "  Or: cargo build -p rxs --release && install -m755 target/release/rxs \$HOME/.rxshell/bin/" >&2
    exit 1
    ;;
esac

if [ "$VERSION" = "latest" ]; then
  rel_prefix="releases/rxs/latest"
else
  rel_prefix="releases/rxs/$VERSION"
fi

url="$BASE/$rel_prefix/$artifact"
csum_url="$BASE/$rel_prefix/checksums.json"
sig_url="$BASE/$rel_prefix/checksums.json.sig"

mkdir -p "$BIN_DIR"
tmp="$(mktemp)"
csum_tmp="$(mktemp)"
cleanup() { rm -f "$tmp" "$csum_tmp" "${csum_tmp}.sig"; }
trap cleanup EXIT

echo "RXShell installer"
echo "  platform: $platform"
echo "  home:     $HOME_DIR"
echo "  version:  $VERSION"
echo "  url:      $url"

if ! curl -fsSL "$url" -o "$tmp"; then
  echo "error: failed to download rxs from $url" >&2
  echo "hint: publish with scripts/release-rxs.sh && scripts/publish-cdn.sh" >&2
  echo "      or build from source: cargo build -p rxs --release" >&2
  exit 3
fi

# SHA-256 + size from checksums.json (required when present)
if curl -fsSL "$csum_url" -o "$csum_tmp"; then
  if command -v sha256sum >/dev/null 2>&1; then
    expected="$(python3 - "$csum_tmp" "$platform" <<'PY' 2>/dev/null || true
import json,sys
c=json.load(open(sys.argv[1]))
p=sys.argv[2]
f=c.get("files",{}).get(p) or c.get("files",{}).get("linux-amd64") or {}
print(f.get("sha256",""))
print(f.get("size",""))
PY
)"
    # fallback without python
    if [ -z "${expected:-}" ] && command -v jq >/dev/null 2>&1; then
      exp_sha="$(jq -r --arg p "$platform" '.files[$p].sha256 // .files["linux-amd64"].sha256 // empty' "$csum_tmp")"
      exp_size="$(jq -r --arg p "$platform" '.files[$p].size // .files["linux-amd64"].size // empty' "$csum_tmp")"
    else
      exp_sha="$(printf '%s\n' "$expected" | sed -n '1p')"
      exp_size="$(printf '%s\n' "$expected" | sed -n '2p')"
    fi
    actual="$(sha256sum "$tmp" | awk '{print $1}')"
    asize="$(stat -c%s "$tmp" 2>/dev/null || wc -c <"$tmp" | tr -d ' ')"
    if [ -n "${exp_sha:-}" ] && [ "$exp_sha" != "$actual" ]; then
      echo "error: sha256 mismatch" >&2
      echo "  expected: $exp_sha" >&2
      echo "  actual:   $actual" >&2
      exit 4
    fi
    if [ -n "${exp_size:-}" ] && [ "$exp_size" != "null" ] && [ "$exp_size" != "$asize" ]; then
      echo "error: size mismatch (expected $exp_size got $asize)" >&2
      exit 4
    fi
    echo "  checksum: ok ($actual)"
  else
    echo "  warning: sha256sum not found; skipped integrity check" >&2
  fi
  # optional signature presence (full verify needs rxs/python cryptography)
  if curl -fsSL "$sig_url" -o "${csum_tmp}.sig" 2>/dev/null; then
    echo "  signature: present ($(basename "$sig_url"))"
  fi
else
  echo "  warning: checksums.json missing at $csum_url — install is unverified" >&2
fi

install -m 0755 "$tmp" "$BIN_DIR/rxs"
echo "installed: $BIN_DIR/rxs"
case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    echo "add to PATH:"
    echo "  export PATH=\"$BIN_DIR:\$PATH\""
    ;;
esac
echo "next:"
echo "  rxs doctor"
echo "  rxs install jq yq rg fd sd bat delta mlr gron dasel pup codex claude codex claude"
echo "  dig example.com | rxs --dig   # built-in jc mode"
