#!/bin/bash
# Machanirobotics — System Setup
# curl -fsSL setup.machanirobotics.dev | bash
set -euo pipefail

REPO="machanirobotics/setup"
INSTALL_DIR="/usr/local/bin"
BINARY="machanirobotics_setup"
CDN="https://dl.machanirobotics.dev"

# ── Colors ──
R='\033[0;31m'   G='\033[0;32m'   C='\033[0;36m'
P='\033[0;35m'   D='\033[0;90m'   B='\033[1m'
NC='\033[0m'

info()    { echo -e "  ${C}→${NC} $1"; }
ok()      { echo -e "  ${G}✓${NC} $1"; }
fail()    { echo -e "  ${R}✗${NC} $1"; exit 1; }
dim()     { echo -e "  ${D}$1${NC}"; }

# ── Banner ──
banner() {
    echo ""
    printf '%b' "${P}"
    cat << 'BANNER'
                       _                 _           _           _   _
  _ __ ___   __ _  ___| |__   __ _ _ __ (_)_ __ ___ | |__   ___ | |_(_) ___ ___
 | '_ ` _ \ / _` |/ __| '_ \ / _` | '_ \| | '__/ _ \| '_ \ / _ \| __| |/ __/ __|
 | | | | | | (_| | (__| | | | (_| | | | | | | | (_) | |_) | (_) | |_| | (__\__ \
 |_| |_| |_|\__,_|\___|_| |_|\__,_|_| |_|_|_|  \___/|_.__/ \___/ \__|_|\___|___/
BANNER
    printf '%b' "${NC}"
    echo ""
    echo -e "  ${B}System Setup${NC}"
    echo ""
}

# ── Platform detection ──
detect_platform() {
    local os arch

    case "$(uname -s)" in
        Darwin) os="darwin" ;;
        Linux)  os="linux" ;;
        *)      fail "Unsupported OS: $(uname -s)" ;;
    esac

    case "$(uname -m)" in
        x86_64|amd64)  arch="amd64" ;;
        arm64|aarch64) arch="arm64" ;;
        *)             fail "Unsupported architecture: $(uname -m)" ;;
    esac

    echo "${os}_${arch}"
}

detect_os_name() {
    case "$(uname -s)" in
        Darwin) echo "macOS" ;;
        Linux)
            if [[ -f /etc/nv_tegra_release ]] || grep -qi jetson /proc/device-tree/model 2>/dev/null; then
                echo "Jetson"
            elif grep -qi ubuntu /etc/os-release 2>/dev/null; then
                echo "Ubuntu"
            else
                echo "Linux"
            fi
            ;;
    esac
}

# ── Download helper ──
download() {
    local url="$1" dest="$2"
    if command -v curl &>/dev/null; then
        curl -fsSL "$url" -o "$dest"
    elif command -v wget &>/dev/null; then
        wget -q "$url" -O "$dest"
    else
        fail "curl or wget required"
    fi
}

# ── Cleanup on failure ──
cleanup() {
    [[ -n "${TMP_FILE:-}" ]] && rm -f "$TMP_FILE"
}
trap cleanup EXIT

# ── Main ──
main() {
    banner

    local platform os_name
    platform=$(detect_platform)
    os_name=$(detect_os_name)

    info "Platform: ${B}${os_name}${NC} (${platform})"

    # Fetch latest version tag (try CDN first, fall back to GitHub API)
    local version
    version=$(download "${CDN}/setup/latest" - 2>/dev/null || true)
    if [[ -z "${version}" || "${version}" == "latest" ]]; then
        version=$(download "https://api.github.com/repos/${REPO}/releases/latest" - 2>/dev/null \
            | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/' || echo "latest")
    fi
    dim "Version: ${version}"
    echo ""

    # Download binary (try CDN first, fall back to GitHub)
    local url="${CDN}/setup/${version}/${BINARY}_${version}_${platform}"
    local fallback_url="https://github.com/${REPO}/releases/download/${version}/${BINARY}_${version}_${platform}"
    info "Downloading ${BINARY}..."
    dim "${url}"

    TMP_FILE=$(mktemp)
    if ! download "$url" "$TMP_FILE" 2>/dev/null; then
        dim "CDN unavailable, falling back to GitHub..."
        url="$fallback_url"
        dim "${url}"
        download "$url" "$TMP_FILE"
    fi
    chmod +x "$TMP_FILE"
    ok "Downloaded"

    # Install
    if [[ -w "$INSTALL_DIR" ]]; then
        mv "$TMP_FILE" "${INSTALL_DIR}/${BINARY}"
    else
        info "Installing to ${INSTALL_DIR} (requires sudo)..."
        sudo mv "$TMP_FILE" "${INSTALL_DIR}/${BINARY}"
    fi
    ok "Installed to ${B}${INSTALL_DIR}/${BINARY}${NC}"
    echo ""

    # Launch
    info "Launching setup..."
    echo ""
    exec "${INSTALL_DIR}/${BINARY}"
}

main "$@"
