#!/bin/sh
# install.sh -- Cross-platform installer for the Weave CLI
#
# Usage:
#   curl -fsSL https://get.weave.build | sh
#
# Environment variables:
#   WEAVE_VERSION         Version to install (default: "latest")
#   WEAVE_INSTALL_DIR     Installation directory (default: ~/.local/bin)
#   WEAVE_BASE_URL        Base URL for binary downloads. Point it at a
#                         channel to track that channel's head, e.g.
#                         WEAVE_BASE_URL=https://dl.weave.build/channels/rc
#                         (channel paths are served from the same release
#                         blobs via a CDN rewrite).
#   WEAVE_NO_MODIFY_PATH  Set to 1 to skip PATH modification
#   WEAVE_MODIFY_PATH     Set to 1 to modify PATH even when
#                         WEAVE_INSTALL_DIR is set. An explicit install
#                         dir is treated as a scripted install and skips
#                         the shell-rc edit by default (the chosen dir is
#                         often ephemeral — CI workspaces, sandboxes —
#                         and a dangling PATH entry can shadow the real
#                         install later).
#   WEAVE_NO_MINISIGN     Set to 1 to skip minisign signature verification
#                         even when a minisign binary is available.
#   WEAVE_USER            HTTP Basic Auth username. Pair with WEAVE_PASSWORD.
#                         Only needed for auth-required repos; the default
#                         public release repo serves anonymously.
#   WEAVE_PASSWORD        HTTP Basic Auth password. Required if WEAVE_USER
#                         is set; both or neither.
#
# Verification: every download is checked against its .sha256 companion.
# When a `minisign` binary is present, the release's signed SHA256SUMS
# inventory is verified instead (signature + version binding), so the
# expected hash itself is authenticated.

set -eu

# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------

if [ -t 1 ]; then
    # Real escape bytes, so the vars render both in printf format strings
    # and as %s arguments (POSIX printf does not expand \033 in arguments).
    BOLD="$(printf '\033[1m')"
    GREEN="$(printf '\033[0;32m')"
    YELLOW="$(printf '\033[0;33m')"
    RED="$(printf '\033[0;31m')"
    RESET="$(printf '\033[0m')"
else
    BOLD='' GREEN='' YELLOW='' RED='' RESET=''
fi

info() { printf "${GREEN}info:${RESET} %s\n" "$1"; }
warn() { printf "${YELLOW}warn:${RESET} %s\n" "$1" >&2; }
err()  { printf "${RED}error:${RESET} %s\n" "$1" >&2; }
die()  { err "$1"; exit 1; }

# ---------------------------------------------------------------------------
# Platform detection
# ---------------------------------------------------------------------------

detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    case "$OS" in
        Linux)                PLATFORM="linux" ;;
        Darwin)               PLATFORM="darwin" ;;
        MINGW*|MSYS*|CYGWIN*) PLATFORM="windows" ;;
        *)                    die "Unsupported operating system: $OS" ;;
    esac

    case "$ARCH" in
        x86_64|amd64)   ARCH="x86_64" ;;
        aarch64|arm64)  ARCH="aarch64" ;;
        *)              die "Unsupported architecture: $ARCH" ;;
    esac

    # macOS uses a universal (fat) binary covering both Intel and Apple Silicon
    if [ "$PLATFORM" = "darwin" ]; then
        BINARY_NAME="weave-darwin-universal"
    elif [ "$PLATFORM" = "windows" ]; then
        if [ "$ARCH" != "x86_64" ]; then
            die "Windows builds are only available for x86_64"
        fi
        BINARY_NAME="weave-windows-x86_64.exe"
    else
        BINARY_NAME="weave-${PLATFORM}-${ARCH}"
    fi
}

# ---------------------------------------------------------------------------
# Tool detection
# ---------------------------------------------------------------------------

detect_downloader() {
    if command -v curl >/dev/null 2>&1; then
        DOWNLOADER="curl"
    elif command -v wget >/dev/null 2>&1; then
        DOWNLOADER="wget"
    else
        die "Either 'curl' or 'wget' is required but neither was found"
    fi
}

validate_auth_env() {
    # Fail fast if only one of WEAVE_USER / WEAVE_PASSWORD is set.
    # Silently dropping to no-auth because one half was forgotten is
    # the kind of mistake you only catch in production.
    if [ -n "${WEAVE_USER:-}" ] && [ -z "${WEAVE_PASSWORD:-}" ]; then
        die "WEAVE_USER is set but WEAVE_PASSWORD is empty. Set both or neither."
    fi
    if [ -z "${WEAVE_USER:-}" ] && [ -n "${WEAVE_PASSWORD:-}" ]; then
        die "WEAVE_PASSWORD is set but WEAVE_USER is empty. Set both or neither."
    fi
}

download() {
    # Download a URL to a file. Args: $1=url $2=output_path
    # Auth: WEAVE_USER + WEAVE_PASSWORD → HTTP Basic; otherwise anonymous.
    if [ -n "${WEAVE_USER:-}" ]; then
        if [ "$DOWNLOADER" = "curl" ]; then
            curl -fsSL --retry 3 --retry-delay 2 --user "${WEAVE_USER}:${WEAVE_PASSWORD}" -o "$2" "$1"
        else
            wget -q --tries=3 --user="${WEAVE_USER}" --password="${WEAVE_PASSWORD}" -O "$2" "$1"
        fi
    else
        if [ "$DOWNLOADER" = "curl" ]; then
            curl -fsSL --retry 3 --retry-delay 2 -o "$2" "$1"
        else
            wget -q --tries=3 -O "$2" "$1"
        fi
    fi
}

download_to_stdout() {
    # Download a URL and print to stdout. Args: $1=url
    if [ -n "${WEAVE_USER:-}" ]; then
        if [ "$DOWNLOADER" = "curl" ]; then
            curl -fsSL --retry 3 --retry-delay 2 --user "${WEAVE_USER}:${WEAVE_PASSWORD}" "$1"
        else
            wget -q --tries=3 --user="${WEAVE_USER}" --password="${WEAVE_PASSWORD}" -O - "$1"
        fi
    else
        if [ "$DOWNLOADER" = "curl" ]; then
            curl -fsSL --retry 3 --retry-delay 2 "$1"
        else
            wget -q --tries=3 -O - "$1"
        fi
    fi
}

detect_checksum_tool() {
    if command -v sha256sum >/dev/null 2>&1; then
        CHECKSUM_TOOL="sha256sum"
    elif command -v shasum >/dev/null 2>&1; then
        CHECKSUM_TOOL="shasum"
    else
        die "Either 'sha256sum' or 'shasum' is required for checksum verification"
    fi
}

verify_checksum() {
    # Verify SHA-256 checksum. Args: $1=file_path $2=expected_hash
    if [ "$CHECKSUM_TOOL" = "sha256sum" ]; then
        ACTUAL_HASH="$(sha256sum "$1" | cut -d' ' -f1)"
    else
        ACTUAL_HASH="$(shasum -a 256 "$1" | cut -d' ' -f1)"
    fi

    if [ "$ACTUAL_HASH" != "$2" ]; then
        die "Checksum verification failed!
  Expected: $2
  Got:      $ACTUAL_HASH

This could indicate a corrupted download or a tampered binary."
    fi
}

# ---------------------------------------------------------------------------
# Signature verification (minisign, opportunistic)
# ---------------------------------------------------------------------------

# The weave release-signing public keys (minisign) — the SAME list as
# Weave.App.Upgrade.Signing.trustedReleaseKeyTexts and scripts/install-node.sh
# (a test keeps them equal). Key 1 (24E30514172F00A4) signs every release;
# key 2 (1F7505023482AC1D) is the pre-provisioned standby (#974). Releases
# publish SHA256SUMS + SHA256SUMS.minisig beside the binaries; CI signs with
# the key held in Azure Key Vault (see .gitlab/ci/publish.yml). Selection is
# by the key id embedded in the .minisig.
MINISIGN_PUBKEYS="RWSkAC8XFAXjJExAUqh0R6RZw66xcyuiJJ1bLWThSUuKGjnt0p/6jUoq RWQdrII0AgV1HxKRZRVRAfxeQ4P9CJo+07PqLd2/AjKo+Z/Z1Ns46ejK"

detect_minisign() {
    MINISIGN=""
    if [ "${WEAVE_NO_MINISIGN:-0}" = "1" ]; then
        return
    fi
    if command -v minisign >/dev/null 2>&1; then
        MINISIGN="minisign"
    fi
}

verify_signed_sums() {
    # Fetch the signed SHA256SUMS inventory, verify its signature, and
    # check the downloaded binary against it. Returns 1 — caller falls
    # back to the unsigned .sha256 path — ONLY when no inventory exists
    # for this version (releases before v0.2.0 shipped none). An
    # inventory that exists but fails verification is always fatal:
    # falling back there would let corruption or tampering demote the
    # check silently.
    SUMS_URL="${BASE_URL%/}/v${VERSION}/SHA256SUMS"
    TMP_SUMS="${TMP_DIR}/SHA256SUMS"

    if ! download "$SUMS_URL" "$TMP_SUMS" 2>/dev/null; then
        warn "No signed SHA256SUMS published for v${VERSION}; falling back to unsigned .sha256 verification"
        return 1
    fi
    download "${SUMS_URL}.minisig" "${TMP_SUMS}.minisig" || \
        die "SHA256SUMS exists for v${VERSION} but its signature could not be fetched:
  ${SUMS_URL}.minisig"

    info "Verifying SHA256SUMS signature (minisign)..."
    SIG_VERIFIED=0
    for key in $MINISIGN_PUBKEYS; do
        if MINISIGN_OUT="$("$MINISIGN" -V -P "$key" -m "$TMP_SUMS" 2>&1)"; then
            SIG_VERIFIED=1
            break
        fi
        # A key-id mismatch just means "not this key"; anything else is a
        # real failure under the key that DID match.
        case "$MINISIGN_OUT" in
            *"key id"*) continue ;;
            *) die "Signature verification FAILED for SHA256SUMS:
${MINISIGN_OUT}

This could indicate a tampered release. Aborting." ;;
        esac
    done
    [ "$SIG_VERIFIED" -eq 1 ] || \
        die "SHA256SUMS.minisig was made with a key this installer does not trust:
${MINISIGN_OUT}"

    # The trusted comment binds the signature to one release; a valid
    # signature from a DIFFERENT version's inventory must not pass.
    case "$MINISIGN_OUT" in
        *"weave v${VERSION} SHA256SUMS"*) ;;
        *) die "SHA256SUMS signature is valid but signed for a different release (expected: weave v${VERSION} SHA256SUMS):
${MINISIGN_OUT}" ;;
    esac

    EXPECTED_HASH="$(awk -v name="$BINARY_NAME" '$2 == name { print $1 }' "$TMP_SUMS")"
    if [ -z "$EXPECTED_HASH" ]; then
        die "Signed SHA256SUMS for v${VERSION} has no entry for ${BINARY_NAME}"
    fi
    verify_checksum "$TMP_BINARY" "$EXPECTED_HASH"
    info "Signature verified"
}

# ---------------------------------------------------------------------------
# Version resolution
# ---------------------------------------------------------------------------

resolve_version() {
    VERSION="${WEAVE_VERSION:-latest}"

    if [ "$VERSION" = "latest" ]; then
        info "Resolving latest version..."
        LATEST_URL="${BASE_URL%/}/latest-version"
        VERSION="$(download_to_stdout "$LATEST_URL")" || \
            die "Failed to resolve latest version. Set WEAVE_VERSION explicitly (e.g., WEAVE_VERSION=0.1.0)"
        VERSION="$(printf '%s' "$VERSION" | tr -d '[:space:]')"
        if [ -z "$VERSION" ]; then
            die "Could not determine latest version. Set WEAVE_VERSION explicitly."
        fi
    fi

    # Strip leading 'v' if present
    VERSION="${VERSION#v}"

    info "Installing weave v${VERSION}"
}

# ---------------------------------------------------------------------------
# Installation
# ---------------------------------------------------------------------------

setup_install_dir() {
    INSTALL_DIR="${WEAVE_INSTALL_DIR:-${HOME}/.local/bin}"

    if [ ! -d "$INSTALL_DIR" ]; then
        info "Creating installation directory: $INSTALL_DIR"
        mkdir -p "$INSTALL_DIR" || die "Failed to create directory: $INSTALL_DIR"
    fi

    if [ ! -w "$INSTALL_DIR" ]; then
        die "Installation directory is not writable: $INSTALL_DIR
  Try: WEAVE_INSTALL_DIR=/some/writable/path curl -fsSL <url> | sh"
    fi
}

do_install() {
    DOWNLOAD_URL="${BASE_URL%/}/v${VERSION}/${BINARY_NAME}"
    CHECKSUM_URL="${DOWNLOAD_URL}.sha256"

    TMP_DIR="$(mktemp -d)" || die "Failed to create temporary directory"
    trap 'rm -rf "$TMP_DIR"' EXIT INT TERM

    TMP_BINARY="${TMP_DIR}/${BINARY_NAME}"
    TMP_CHECKSUM="${TMP_DIR}/${BINARY_NAME}.sha256"

    info "Downloading weave v${VERSION} for ${PLATFORM}/${ARCH}..."
    download "$DOWNLOAD_URL" "$TMP_BINARY" || \
        die "Failed to download binary from: $DOWNLOAD_URL
  If the registry requires auth, set WEAVE_USER + WEAVE_PASSWORD."

    if [ -n "$MINISIGN" ] && verify_signed_sums; then
        : # verified via the signed SHA256SUMS inventory
    else
        if [ -z "$MINISIGN" ]; then
            info "minisign not found — using checksum-only verification"
        fi
        info "Verifying checksum..."
        download "$CHECKSUM_URL" "$TMP_CHECKSUM" || \
            die "Failed to download checksum file from: $CHECKSUM_URL"

        EXPECTED_HASH="$(cut -d' ' -f1 < "$TMP_CHECKSUM")"
        verify_checksum "$TMP_BINARY" "$EXPECTED_HASH"
        info "Checksum verified"
    fi

    TARGET_BINARY="${INSTALL_DIR}/weave"
    if [ "$PLATFORM" = "windows" ]; then
        TARGET_BINARY="${INSTALL_DIR}/weave.exe"
    fi

    # Atomic install: copy to temp in target dir, then rename
    TMP_TARGET="${INSTALL_DIR}/.weave.tmp.$$"
    cp "$TMP_BINARY" "$TMP_TARGET"
    chmod +x "$TMP_TARGET"
    mv "$TMP_TARGET" "$TARGET_BINARY"

    info "Installed weave to: $TARGET_BINARY"
}

# ---------------------------------------------------------------------------
# PATH setup
# ---------------------------------------------------------------------------

ensure_in_path() {
    if [ "${WEAVE_NO_MODIFY_PATH:-0}" = "1" ]; then
        return
    fi

    # Check if install dir is already in PATH
    case ":${PATH}:" in
        *":${INSTALL_DIR}:"*) return ;;
    esac

    # An explicit WEAVE_INSTALL_DIR is almost always a scripted install
    # (CI, sandboxes, tooling): editing dotfiles there is a surprise,
    # and the chosen dir is often ephemeral — leaving a dangling PATH
    # entry that can shadow a later real install. Hands off by default;
    # WEAVE_MODIFY_PATH=1 opts back in for a human who picked a custom
    # permanent dir.
    if [ -n "${WEAVE_INSTALL_DIR:-}" ] && [ "${WEAVE_MODIFY_PATH:-0}" != "1" ]; then
        warn "${INSTALL_DIR} is not on your PATH (left untouched: WEAVE_INSTALL_DIR is explicit; set WEAVE_MODIFY_PATH=1 to opt in)"
        return
    fi

    SHELL_NAME="$(basename "${SHELL:-/bin/sh}")"
    RC_FILE=""

    case "$SHELL_NAME" in
        bash)
            # macOS bash uses .bash_profile for login shells (Terminal.app),
            # Linux bash uses .bashrc for interactive non-login shells.
            if [ "$PLATFORM" = "darwin" ]; then
                RC_FILE="${HOME}/.bash_profile"
            elif [ -f "${HOME}/.bashrc" ]; then
                RC_FILE="${HOME}/.bashrc"
            elif [ -f "${HOME}/.bash_profile" ]; then
                RC_FILE="${HOME}/.bash_profile"
            else
                RC_FILE="${HOME}/.bashrc"
            fi
            ;;
        zsh)
            # .zshrc is sourced for interactive shells on both macOS and Linux.
            # macOS Terminal.app starts login shells, but zsh sources .zshrc
            # for all interactive shells regardless of login status.
            RC_FILE="${HOME}/.zshrc"
            ;;
        fish)
            RC_FILE="${HOME}/.config/fish/config.fish"
            ;;
        *)
            RC_FILE="${HOME}/.profile"
            ;;
    esac

    PATH_LINE="export PATH=\"${INSTALL_DIR}:\$PATH\""
    if [ "$SHELL_NAME" = "fish" ]; then
        PATH_LINE="fish_add_path ${INSTALL_DIR}"
    fi

    # Idempotent: check if already present
    if [ -f "$RC_FILE" ] && grep -qF "$INSTALL_DIR" "$RC_FILE" 2>/dev/null; then
        return
    fi

    printf '\n# Added by weave installer\n%s\n' "$PATH_LINE" >> "$RC_FILE"
    warn "Added ${INSTALL_DIR} to PATH in ${RC_FILE}"
    NEED_RELOAD=1
}

# ---------------------------------------------------------------------------
# Success message
# ---------------------------------------------------------------------------

print_success() {
    printf "\n"
    printf '%s%sWeave v%s installed successfully!%s\n' "$GREEN" "$BOLD" "$VERSION" "$RESET"
    printf "\n"
    printf '  %sBinary:%s  %s\n' "$BOLD" "$RESET" "$TARGET_BINARY"
    printf '  %sConfig:%s  ~/.config/weave/\n' "$BOLD" "$RESET"
    printf '  %sData:%s    ~/.local/share/weave/\n' "$BOLD" "$RESET"
    printf "\n"

    if [ "${NEED_RELOAD:-0}" = "1" ]; then
        printf '  %sRestart your shell or run:%s\n' "$YELLOW" "$RESET"
        printf "    source %s\n" "$RC_FILE"
        printf "\n"
    fi

    printf '  %sGet started:%s\n' "$BOLD" "$RESET"
    printf "    weave --help\n"
    printf "\n"
    # Informational only — downloading is not acceptance (design §6.5);
    # weave itself collects acceptance at the first state-changing command.
    printf '  %sLicense:%s proprietary — free tier covers any use up to 3 cluster nodes.\n' "$BOLD" "$RESET"
    printf "    EULA: %s/v%s/EULA.md\n" "${BASE_URL%/}" "$VERSION"
    printf "\n"
    printf '  %sTo uninstall:%s\n' "$BOLD" "$RESET"
    printf "    rm %s\n" "$TARGET_BINARY"
    printf "    # Optionally remove config and data:\n"
    printf "    # rm -rf ~/.config/weave ~/.local/share/weave\n"
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

main() {
    BASE_URL="${WEAVE_BASE_URL:-https://dl.weave.build/releases}"
    NEED_RELOAD=0

    validate_auth_env
    detect_platform
    detect_downloader
    detect_checksum_tool
    detect_minisign
    resolve_version
    setup_install_dir
    do_install
    ensure_in_path
    print_success
}

main "$@"
