#!/bin/sh
set -e

OAK_URL="${OAK_URL:-https://oak.space}"

# Release traffic must stay on authenticated transports, redirects included.
# A private/local HTTP mirror is useful for development, but it must be an
# explicit opt-in so a typo cannot silently remove transport authentication.
# Artifact authenticity still comes from the pinned minisign key below.
case "$OAK_URL" in
    https://*)
        CURL_PROTOCOLS='=https'
        ;;
    http://*)
        if [ "${OAK_ALLOW_INSECURE_HTTP:-}" != "1" ]; then
            printf 'Error: refusing insecure OAK_URL; use HTTPS or set OAK_ALLOW_INSECURE_HTTP=1 for an explicitly trusted local mirror.\n' >&2
            exit 1
        fi
        CURL_PROTOCOLS='=http,https'
        ;;
    *)
        printf 'Error: OAK_URL must use an http:// or https:// URL.\n' >&2
        exit 1
        ;;
esac

curl_release() {
    curl -fsSL --proto "$CURL_PROTOCOLS" --proto-redir "$CURL_PROTOCOLS" "$@"
}

# Public minisign key for Oak release artifacts. This is intentionally not an
# environment override: an installer must not accept a replacement trust root
# supplied by the same environment that selected its download endpoint. Keep
# it in sync with DEFAULT_RELEASE_MINISIGN_PUBKEY in server/api/releases.rs.
# (`oak upgrade` from 0.124.0 checks a manifest signed with a release security
# key instead; CLIs before it, and this installer, still check minisign.)
OAK_RELEASE_MINISIGN_PUBKEY='RWQvvXyHZKQ0v5iV/R3Vb+kNbG+dz2Ttu+OWJ493mIhtaXRequka1FhR'

# --- pretty output -------------------------------------------------------
# A little terminal polish: a green braille spinner on the slow steps, a ✓/✗
# on completion, and an oak-green banner. This is purely cosmetic and is
# gated on supports_fancy(), so anything non-interactive — CI logs,
# `curl ... | sh > file`, NO_COLOR, or a dumb terminal — falls back to plain,
# greppable lines with no escape codes.
supports_fancy() {
    [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != "dumb" ]
}

if supports_fancy; then
    C_RESET=$(printf '\033[0m')
    C_DIM=$(printf '\033[2m')
    C_BOLD=$(printf '\033[1m')
    C_GREEN=$(printf '\033[38;5;107m')   # oak moss green
    C_GREENB=$(printf '\033[38;5;113m')  # brighter green for the ✓
    C_RED=$(printf '\033[38;5;203m')
else
    C_RESET='' C_DIM='' C_BOLD='' C_GREEN='' C_GREENB='' C_RED=''
fi

SPIN_PID=
SPIN_MSG=

# Kill the background animator if one is running (internal helper, also used
# by the cleanup trap). Guarded so a dead PID never trips `set -e`.
_spin_kill() {
    if [ -n "$SPIN_PID" ]; then
        kill "$SPIN_PID" 2>/dev/null || true
        wait "$SPIN_PID" 2>/dev/null || true
        SPIN_PID=
    fi
}

# spin_start "Doing the thing" — begin an animated step. The real work runs in
# the foreground after this returns; call spin_done/spin_fail to finish it.
spin_start() {
    SPIN_MSG="$1"
    if ! supports_fancy; then
        printf '  %s ...\n' "$SPIN_MSG"
        return
    fi
    printf '\033[?25l'  # hide cursor for the duration of the spin
    # Animate braille frames in oak green at ~12fps until killed. Runs in a
    # subshell so the foreground keeps doing the actual download/verify work.
    (
        frames='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏'
        while : ; do
            for f in $frames; do
                printf '\r%s%s%s %s' "$C_GREEN" "$f" "$C_RESET" "$SPIN_MSG"
                sleep 0.08
            done
        done
    ) &
    SPIN_PID=$!
}

# spin_done ["final message"] — stop the animator, leave a green ✓ line.
spin_done() {
    final=${1:-$SPIN_MSG}
    if ! supports_fancy; then
        [ -n "${1:-}" ] && printf '  %s\n' "$final"
        return
    fi
    _spin_kill
    printf '\r\033[K%s✓%s %s\n' "$C_GREENB" "$C_RESET" "$final"
    printf '\033[?25h'  # restore cursor
}

# spin_fail ["final message"] — stop the animator, leave a red ✗ line.
spin_fail() {
    final=${1:-$SPIN_MSG}
    if ! supports_fancy; then
        printf '  %s\n' "$final"
        return
    fi
    _spin_kill
    printf '\r\033[K%s✗%s %s\n' "$C_RED" "$C_RESET" "$final"
    printf '\033[?25h'
}

# An instant fact (no spinner) — a dim bullet line.
note() {
    if supports_fancy; then
        printf '%s•%s %s\n' "$C_GREEN" "$C_RESET" "$1"
    else
        printf '  %s\n' "$1"
    fi
}

# Fatal error → red ✗ on stderr, then exit.
die() {
    _spin_kill
    if supports_fancy; then
        printf '%s✗%s %s\n' "$C_RED" "$C_RESET" "$1" >&2
        printf '\033[?25h' >&2
    else
        printf 'Error: %s\n' "$1" >&2
    fi
    exit 1
}

command -v curl >/dev/null 2>&1 || die "curl is required to download Oak. Install curl and run this again."

# Always tidy up: stop any spinner, restore the cursor, remove the temp dir,
# and preserve the real exit code (so failures still surface as failures).
TMP_DIR=
CLEANUP_DONE=
cleanup_once() {
    if [ "${CLEANUP_DONE:-0}" = "1" ]; then
        return
    fi
    CLEANUP_DONE=1
    _spin_kill
    if supports_fancy; then printf '\033[?25h'; fi
    if [ -n "$TMP_DIR" ]; then rm -rf "$TMP_DIR"; fi
}

cleanup_exit() {
    _rc=$?
    trap - EXIT INT TERM
    cleanup_once
    exit "$_rc"
}

cleanup_signal() {
    _rc=$1
    trap - EXIT INT TERM
    cleanup_once
    exit "$_rc"
}

trap cleanup_exit EXIT
trap 'cleanup_signal 130' INT
trap 'cleanup_signal 143' TERM

# --- banner --------------------------------------------------------------
printf '\n%sOak VCS%s\n\n' "$C_BOLD" "$C_RESET"

# Pick the native binary for this host: darwin-arm64 on Apple Silicon,
# darwin-x86_64 on Intel Macs, linux-x86_64 on CI runners and Linux servers.
# (Intel Macs used to be served darwin-arm64 and left to Rosetta 2 — they now
# get their own build.)
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$OS" in
    darwin)
        case "$ARCH" in
            arm64|aarch64)
                PLATFORM="darwin-arm64"
                ;;
            x86_64)
                # `uname -m` also says x86_64 on an Apple Silicon Mac when this
                # script runs under Rosetta 2 (an Intel-mode terminal, an
                # x86_64 CI image). sysctl.proc_translated is 1 in exactly that
                # case, and only there — it's absent on real Intel hardware.
                # Prefer the native arm64 build when translated: it's faster,
                # and `oak upgrade` resolves its platform from the binary's own
                # compile-time target, so installing the Intel build here would
                # pin the machine to darwin-x86_64 for every future upgrade.
                if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
                    PLATFORM="darwin-arm64"
                else
                    PLATFORM="darwin-x86_64"
                fi
                ;;
            *)
                die "Unsupported macOS architecture: $ARCH (arm64 and x86_64 are supported)"
                ;;
        esac
        ;;
    linux)
        case "$ARCH" in
            x86_64|amd64)
                PLATFORM="linux-x86_64"
                ;;
            *)
                die "Unsupported Linux architecture: $ARCH (only x86_64 is supported)"
                ;;
        esac
        ;;
    *)
        die "Unsupported operating system: $OS (macOS and Linux are supported)"
        ;;
esac
note "platform: $PLATFORM"

# `minisign` authenticates release artifacts. It and the standard utilities
# used by this shell script (`curl`, `uname`, and SHA-256) are trusted local
# prerequisites when found on PATH: a hostile PATH can already replace curl or
# the shell's other tools. When minisign is absent, bootstrap an official
# archive over HTTPS and authenticate that archive against a digest pinned in
# this installer, independent of the Oak artifact origin.
MINISIGN_BIN="minisign"
if ! command -v "$MINISIGN_BIN" >/dev/null 2>&1; then
    case "$OS" in
        darwin)
            # minisign 0.11's macOS archive is universal, so the same pinned
            # verifier works on both Apple Silicon and Intel Macs. Extract the
            # single expected member rather than unpacking an archive into a
            # directory that will later be executed from.
            MINISIGN_VERSION=0.11
            MINISIGN_ARCHIVE_SHA256=e7c410ae8b8960d7087392472b040bda9b2f307c76df0384ac37f9ad103fc893
            MINISIGN_ARCHIVE_URL="https://github.com/jedisct1/minisign/releases/download/0.11/minisign-0.11-macos.zip"
            MINISIGN_ARCHIVE_KIND=zip
            ;;
        linux)
            MINISIGN_VERSION=0.12
            MINISIGN_ARCHIVE_SHA256=9a599b48ba6eb7b1e80f12f36b94ceca7c00b7a5173c95c3efc88d9822957e73
            MINISIGN_ARCHIVE_URL="https://github.com/jedisct1/minisign/releases/download/0.12/minisign-0.12-linux.tar.gz"
            MINISIGN_ARCHIVE_KIND=tar
            ;;
    esac
    TMP_DIR=$(mktemp -d)
    MINISIGN_ARCHIVE="$TMP_DIR/minisign-archive"
    spin_start "Bootstrapping minisign $MINISIGN_VERSION"
    if ! curl -fsSL --proto '=https' --proto-redir '=https' \
        "$MINISIGN_ARCHIVE_URL" -o "$MINISIGN_ARCHIVE"; then
        spin_fail "Could not download minisign"
        die "A minisign verifier is required and its pinned HTTPS archive could not be downloaded."
    fi
    if command -v sha256sum >/dev/null 2>&1; then
        MINISIGN_ARCHIVE_ACTUAL=$(sha256sum "$MINISIGN_ARCHIVE" | awk '{print $1}')
    elif command -v shasum >/dev/null 2>&1; then
        MINISIGN_ARCHIVE_ACTUAL=$(shasum -a 256 "$MINISIGN_ARCHIVE" | awk '{print $1}')
    else
        spin_fail "Cannot authenticate minisign archive"
        die "sha256sum or shasum is required to authenticate the minisign verifier archive."
    fi
    if [ "$MINISIGN_ARCHIVE_ACTUAL" != "$MINISIGN_ARCHIVE_SHA256" ]; then
        spin_fail "Minisign archive authentication failed"
        die "The pinned minisign verifier archive has an unexpected SHA-256 digest."
    fi
    MINISIGN_BIN="$TMP_DIR/minisign"
    case "$MINISIGN_ARCHIVE_KIND" in
        tar)
            if ! tar -xzf "$MINISIGN_ARCHIVE" -C "$TMP_DIR" \
                "minisign-linux/x86_64/minisign"; then
                spin_fail "Could not unpack minisign"
                die "The authenticated minisign verifier archive could not be unpacked."
            fi
            mv "$TMP_DIR/minisign-linux/x86_64/minisign" "$MINISIGN_BIN"
            ;;
        zip)
            if ! command -v unzip >/dev/null 2>&1 \
                || ! unzip -p "$MINISIGN_ARCHIVE" minisign > "$MINISIGN_BIN"; then
                spin_fail "Could not unpack minisign"
                die "The authenticated minisign verifier archive could not be unpacked."
            fi
            ;;
    esac
    chmod 0755 "$MINISIGN_BIN"
    if [ "$("$MINISIGN_BIN" -v 2>&1)" != "minisign $MINISIGN_VERSION" ]; then
        spin_fail "Unexpected minisign version"
        die "The authenticated verifier did not report minisign $MINISIGN_VERSION."
    fi
    spin_done "Minisign $MINISIGN_VERSION ready"
else
    if ! MINISIGN_VERSION_OUTPUT=$("$MINISIGN_BIN" -v 2>&1); then
        die "MINISIGN_BIN does not name a working minisign verifier: $MINISIGN_BIN"
    fi
    case "$MINISIGN_VERSION_OUTPUT" in
        minisign\ *)
            ;;
        *)
            die "MINISIGN_BIN does not appear to be minisign: $MINISIGN_BIN"
            ;;
    esac
fi

# Get latest version. There is one release line; an OAK_CHANNEL left over
# from older instructions is ignored.
spin_start "Fetching latest version"
if VERSION=$(curl_release "$OAK_URL/api/releases/latest" | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4) && [ -n "$VERSION" ]; then
    spin_done "Latest version: $VERSION"
else
    spin_fail "Could not determine latest version"
    exit 1
fi

# Create a temp directory unless the Linux verifier bootstrap already made
# one. It is cleaned up by the EXIT trap above in either case.
if [ -z "$TMP_DIR" ]; then TMP_DIR=$(mktemp -d); fi

# Download binary
spin_start "Downloading oak $VERSION ($PLATFORM)"
if curl_release "$OAK_URL/api/releases/$VERSION/$PLATFORM" -o "$TMP_DIR/oak"; then
    spin_done "Downloaded oak $VERSION"
else
    spin_fail "Download failed"
    exit 1
fi

# Authenticate the downloaded bytes before they are made executable. Missing,
# malformed, wrong-key, and tampered signatures all fail closed.
spin_start "Verifying release signature"
if ! curl_release "$OAK_URL/api/releases/$VERSION/$PLATFORM/minisig" -o "$TMP_DIR/oak.minisig"; then
    spin_fail "Release signature is missing"
    die "Oak $VERSION ($PLATFORM) cannot be authenticated; nothing was installed."
fi
if "$MINISIGN_BIN" -Vm "$TMP_DIR/oak" -x "$TMP_DIR/oak.minisig" \
    -P "$OAK_RELEASE_MINISIGN_PUBKEY" -q >/dev/null 2>&1; then
    spin_done "Release signature verified"
else
    spin_fail "Release signature verification failed"
    die "Oak $VERSION ($PLATFORM) has an invalid or tampered minisign signature; nothing was installed."
fi

# Download + verify checksum
spin_start "Verifying checksum"
if ! EXPECTED_SHA256=$(curl_release "$OAK_URL/api/releases/$VERSION/$PLATFORM/sha256"); then
    spin_fail "Could not fetch checksum"
    exit 1
fi
if command -v sha256sum > /dev/null 2>&1; then
    ACTUAL_SHA256=$(sha256sum "$TMP_DIR/oak" | cut -d' ' -f1)
elif command -v shasum > /dev/null 2>&1; then
    ACTUAL_SHA256=$(shasum -a 256 "$TMP_DIR/oak" | cut -d' ' -f1)
else
    spin_done "Checksum skipped (no sha256sum/shasum available)"
    SKIP_VERIFY=1
fi

if [ -z "${SKIP_VERIFY:-}" ]; then
    if [ "$EXPECTED_SHA256" != "$ACTUAL_SHA256" ]; then
        spin_fail "Checksum verification failed"
        printf '    expected: %s\n    actual:   %s\n' "$EXPECTED_SHA256" "$ACTUAL_SHA256" >&2
        exit 1
    fi
    spin_done "Checksum verified"
fi

# Install binary
chmod +x "$TMP_DIR/oak"

# Honor INSTALL_DIR if set (e.g. CI runners want /usr/local/bin so the
# binary lands in a directory already on PATH). Falls back to the per-user
# default ~/.local/bin when running interactively.
INSTALL_DIR="${INSTALL_DIR:-${HOME}/.local/bin}"
if ! mkdir -p "$INSTALL_DIR" 2>/dev/null || [ ! -w "$INSTALL_DIR" ]; then
    die "Cannot write to $INSTALL_DIR. Choose a directory you own, e.g.  curl -fsSL https://oak.space/install.sh | INSTALL_DIR=\$HOME/bin sh"
fi
# Copy next to the destination first, then rename within that directory: the
# rename is atomic, so an interrupted install never leaves a truncated `oak`
# (TMP_DIR is usually on another filesystem, where `mv` copies byte by byte).
STAGED="$INSTALL_DIR/.oak.install.$$"
if ! cp "$TMP_DIR/oak" "$STAGED" || ! chmod +x "$STAGED" || ! mv -f "$STAGED" "$INSTALL_DIR/oak"; then
    rm -f "$STAGED"
    die "Could not install oak into $INSTALL_DIR."
fi

printf '\n%sOak %s installed%s to %s%s%s\n\n' \
    "$C_BOLD" "$VERSION" "$C_RESET" "$C_BOLD" "$INSTALL_DIR/oak" "$C_RESET"

# Check if install dir is in PATH
case ":$PATH:" in
    *":$INSTALL_DIR:"*)
        echo "Run 'oak --help' to get started."
        ;;
    *)
        echo "Add $INSTALL_DIR to your PATH:"
        echo ""
        echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
        echo ""
        echo "Then run 'oak --help' to get started."
        ;;
esac

# Offer to log in right away. This script is usually piped (curl ... | sh), so
# stdin is the script itself, not the keyboard — we read the answer from the
# controlling terminal (/dev/tty) and hand that same terminal to `oak login`,
# so its browser sign-in (and prompt-setup offer) stay interactive. Skipped
# automatically when there's no terminal (CI, cron) or when OAK_NO_LOGIN is set.
if [ -z "${OAK_NO_LOGIN:-}" ] && [ -t 1 ] && [ -r /dev/tty ]; then
    echo ""
    printf "Log in to %s now? [Y/n] " "$OAK_URL"
    if read -r OAK_LOGIN_ANSWER < /dev/tty; then
        case "$OAK_LOGIN_ANSWER" in
            ""|[Yy]|[Yy][Ee][Ss])
                # || true: a cancelled or failed login shouldn't make a
                # successful install look like it errored out.
                "$INSTALL_DIR/oak" login -r "$OAK_URL" < /dev/tty || true
                ;;
            *)
                echo "Skipped. Run 'oak login' when you're ready."
                ;;
        esac
    fi
fi
