#!/usr/bin/env bash
# AccelMars OS — bootstrap installer
# Channel: https://get.accelmars.com  (Cloudflare Worker + R2; GitHub-independent)
# License: Apache-2.0
#
# Installs `os` and `anchor` binaries into $INSTALL_DIR (default: $HOME/.local/bin).
# Verifies each artifact's SHA-256 against the published .sha256 sidecar.
# Verifies anchor minimum version against COMPAT.toml; hard-errors on mismatch.
# Runs `os doctor` as the final step.
#
# Usage:
#   curl -fsSL https://get.accelmars.com/install.sh | bash
#   INSTALL_DIR=/custom/path bash install.sh

set -euo pipefail

CHANNEL="${ACCELMARS_CHANNEL:-https://get.accelmars.com}"
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/bin}"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

log() { printf '[install] %s\n' "$*"; }
err() { printf '[install] error: %s\n' "$*" >&2; }

detect_target() {
    local kernel arch
    kernel="$(uname -s)"
    arch="$(uname -m)"
    case "$kernel:$arch" in
        Darwin:arm64) echo "aarch64-apple-darwin" ;;
        Darwin:x86_64) echo "x86_64-apple-darwin" ;;
        Linux:aarch64) echo "aarch64-unknown-linux-gnu" ;;
        Linux:arm64) echo "aarch64-unknown-linux-gnu" ;;
        Linux:x86_64) echo "x86_64-unknown-linux-gnu" ;;
        *) err "unsupported platform: $kernel/$arch"; exit 2 ;;
    esac
}

# Fetch <engine>'s latest version string from the channel.
latest_version() {
    local engine="$1"
    curl -fsSL --proto '=https' --tlsv1.2 "$CHANNEL/${engine}/latest"
}

# Download + SHA-256-verify an engine artifact, then extract into $outdir.
fetch_and_extract() {
    local engine="$1" version="$2" target="$3" pkg_prefix="$4" outdir="$5"
    local asset="${pkg_prefix}-${target}.tar.xz"
    local base="$CHANNEL/${engine}/${version}/${asset}"
    log "fetching ${engine} ${version} for ${target}"
    if ! curl -fsSL --proto '=https' --tlsv1.2 "$base" -o "$TMP_DIR/${asset}"; then
        err "failed to download $base"; exit 3
    fi
    # SHA-256 verification against the published sidecar.
    if curl -fsSL --proto '=https' --tlsv1.2 "${base}.sha256" -o "$TMP_DIR/${asset}.sha256" 2>/dev/null; then
        local want got
        want="$(awk '{print $1}' "$TMP_DIR/${asset}.sha256")"
        if command -v shasum >/dev/null 2>&1; then
            got="$(shasum -a 256 "$TMP_DIR/${asset}" | awk '{print $1}')"
        else
            got="$(sha256sum "$TMP_DIR/${asset}" | awk '{print $1}')"
        fi
        if [ -n "$want" ] && [ "$want" != "$got" ]; then
            err "checksum mismatch for ${asset}: expected $want, got $got"; exit 4
        fi
        log "✓ ${engine} checksum verified"
    else
        err "warning: no .sha256 sidecar for ${asset}; skipping verification"
    fi
    mkdir -p "$outdir"
    tar -xJf "$TMP_DIR/${asset}" -C "$outdir"
}

# Read anchor min_version from COMPAT.toml (limited grammar; no TOML parser dep).
compat_anchor_min() {
    awk '
        /^\[\[compat\]\]/ { in_anchor = 0 }
        /component[[:space:]]*=[[:space:]]*"anchor"/ { in_anchor = 1 }
        in_anchor && /^[[:space:]]*min_version[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*/, ""); gsub(/"/, ""); print; exit
        }
    ' "$1"
}

version_ge() {
    local highest
    highest="$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)"
    [ "$highest" = "$1" ]
}

main() {
    local target os_ver anchor_ver os_dir anchor_dir compat_file required_anchor anchor_version
    target="$(detect_target)"
    log "channel: $CHANNEL"
    log "platform: $target"
    log "install dir: $INSTALL_DIR"

    os_ver="$(latest_version os)"
    anchor_ver="$(latest_version anchor)"
    [ -n "$os_ver" ] || { err "could not resolve latest os version"; exit 5; }
    [ -n "$anchor_ver" ] || { err "could not resolve latest anchor version"; exit 5; }

    os_dir="$TMP_DIR/os"
    anchor_dir="$TMP_DIR/anchor"
    fetch_and_extract "os" "$os_ver" "$target" "accelmars-os" "$os_dir"
    fetch_and_extract "anchor" "$anchor_ver" "$target" "accelmars-anchor" "$anchor_dir"

    compat_file="$(find "$os_dir" -maxdepth 3 -name COMPAT.toml -type f | head -n1)"
    [ -n "${compat_file:-}" ] || { err "COMPAT.toml not found in os tarball"; exit 6; }
    required_anchor="$(compat_anchor_min "$compat_file")"
    [ -n "${required_anchor:-}" ] || { err "could not read anchor min_version from COMPAT.toml"; exit 7; }

    local anchor_bin os_bin
    anchor_bin="$(find "$anchor_dir" -maxdepth 3 -name anchor -type f | head -n1)"
    [ -n "${anchor_bin:-}" ] || { err "anchor binary not found in tarball"; exit 8; }
    chmod +x "$anchor_bin"
    anchor_version="$("$anchor_bin" --version | awk '{print $NF}')"
    log "anchor required >= $required_anchor; found $anchor_version"
    version_ge "$anchor_version" "$required_anchor" || {
        err "compat mismatch: anchor $anchor_version < required $required_anchor"; exit 9; }

    os_bin="$(find "$os_dir" -maxdepth 3 -name os -type f | head -n1)"
    [ -n "${os_bin:-}" ] || { err "os binary not found in tarball"; exit 10; }

    mkdir -p "$INSTALL_DIR"
    install -m 0755 "$os_bin" "$INSTALL_DIR/os"
    install -m 0755 "$anchor_bin" "$INSTALL_DIR/anchor"
    log "installed: $INSTALL_DIR/os, $INSTALL_DIR/anchor"

    case ":$PATH:" in
        *":$INSTALL_DIR:"*) ;;
        *) log "warning: $INSTALL_DIR is not on PATH; add it to your shell rc" ;;
    esac

    "$INSTALL_DIR/os" doctor || true
}

main "$@"
