#!/bin/sh
set -eu

BINARY_NAME="fafb-q"
INSTALL_DIR="/usr/local/bin"
BASE_URL="https://bitbucket.org/thermsio/fafb-q/downloads"

run() {
    if [ "$needs_sudo" = true ]; then
        sudo "$@"
    else
        "$@"
    fi
}

main() {
    # Check for curl
    if ! command -v curl >/dev/null 2>&1; then
        echo "Error: curl is required but not found"
        exit 1
    fi

    # Detect OS
    os="$(uname -s)"
    if [ "$os" != "Linux" ]; then
        echo "Error: unsupported OS: $os"
        echo "On macOS, install via: cargo install fafb-q"
        exit 1
    fi

    # Detect architecture
    arch="$(uname -m)"
    case "$arch" in
        x86_64)  target="x86_64-unknown-linux-musl" ;;
        aarch64|arm64) target="aarch64-unknown-linux-musl" ;;
        *)
            echo "Error: unsupported architecture: $arch"
            exit 1
            ;;
    esac

    echo "Detected: Linux $arch"

    # Create temp directory with cleanup trap
    tmpdir="$(mktemp -d)"
    trap 'rm -rf "$tmpdir"' EXIT INT TERM

    # Download
    tarball="fafb-q-latest-${target}.tar.gz"
    echo "Downloading fafb-q for ${target}..."
    curl -fsSL --connect-timeout 10 --max-time 120 "${BASE_URL}/${tarball}" -o "${tmpdir}/${tarball}"

    # Extract
    tar xzf "${tmpdir}/${tarball}" --strip-components=1 -C "$tmpdir"

    # Verify binary exists and is executable
    if [ ! -x "${tmpdir}/${BINARY_NAME}" ]; then
        echo "Error: binary not found or not executable after extraction"
        exit 1
    fi

    # Determine if we need sudo
    needs_sudo=false
    if [ "$(id -u)" -ne 0 ]; then
        if ! command -v sudo >/dev/null 2>&1; then
            echo "Error: permission denied. Run as root or install sudo."
            exit 1
        fi
        needs_sudo=true
    fi

    # Install
    echo "Installing to ${INSTALL_DIR}/${BINARY_NAME}..."
    run mkdir -p "$INSTALL_DIR"
    run install -m 755 "${tmpdir}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}"

    # Smoke test
    "${INSTALL_DIR}/${BINARY_NAME}" --version

    echo "Install complete."
}

main
