#!/bin/sh
# Install a published spill binary. Inspect: https://spill.rs/install.sh
# Usage: sh install.sh [--version 0.5.2] [--install-dir /absolute/path]
set -eu

main() {
    version=
    install_dir=${HOME:?HOME must be set}/.local/bin
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --version|--install-dir)
                [ "$#" -ge 2 ] || die "$1 requires a value"
                case "$1" in
                    --version) version=${2#v} ;;
                    --install-dir) install_dir=$2 ;;
                esac
                shift 2 ;;
            -h|--help)
                printf '%s\n' 'Usage: install.sh [--version X.Y.Z] [--install-dir /absolute/path]' \
                    'Default: latest stable release, installed to ~/.local/bin. No sudo or service setup.'
                return ;;
            *) die "Unknown option: $1 (use --help)" ;;
        esac
    done
    case "$install_dir" in /*) ;; *) die '--install-dir must be an absolute path' ;; esac
    for tool in curl tar awk mktemp uname; do
        command -v "$tool" >/dev/null 2>&1 || die "Required command not found: $tool"
    done
    if command -v sha256sum >/dev/null 2>&1; then
        hasher=sha256sum
    elif command -v shasum >/dev/null 2>&1; then
        hasher=shasum
    else
        die 'Install sha256sum or shasum to verify the download'
    fi
    case "$(uname -s)/$(uname -m)" in
        Linux/x86_64) target=x86_64-unknown-linux-gnu ;;
        Linux/aarch64|Linux/arm64) target=aarch64-unknown-linux-gnu ;;
        Darwin/arm64) target=aarch64-apple-darwin ;;
        *) die 'No binary for this platform. Use cargo install spill --locked instead.' ;;
    esac

    base=https://github.com/spillrs/spill/releases
    if [ -z "$version" ]; then
        latest=$(fetch -o /dev/null -w '%{url_effective}' "$base/latest")
        case "$latest" in
            "$base/tag/v"*) version=${latest##*/v} ;;
            *) die 'Could not resolve the latest release' ;;
        esac
    fi
    # Only stable numeric tags are accepted, never URL or shell fragments.
    printf '%s\n' "$version" | awk '
        NR == 1 && /^[0-9]+\.[0-9]+\.[0-9]+$/ { valid=1 }
        END { exit !(valid && NR == 1) }
    ' || die 'Version must be X.Y.Z (a stable release)'

    work=$(mktemp -d)
    stage=
    trap 'rm -rf "$work"; if [ -n "$stage" ]; then rm -rf "$stage"; fi' EXIT
    trap 'exit 1' HUP INT TERM
    archive=spill-${version}-${target}.tar.gz
    printf 'Downloading spill %s (%s)\n' "$version" "$target"
    fetch -o "$work/$archive" "$base/download/v$version/$archive"
    fetch -o "$work/SHA256SUMS" "$base/download/v$version/SHA256SUMS"
    expected=$(awk -v file="$archive" '$2 == file { count++; hash=$1 } END { if (count == 1) print hash; else exit 1 }' "$work/SHA256SUMS") \
        || die 'No unique checksum for this archive'
    [ "${#expected}" -eq 64 ] || die 'Invalid SHA-256 checksum'
    case "$expected" in *[!0-9a-fA-F]*) die 'Invalid SHA-256 checksum' ;; esac
    if [ "$hasher" = sha256sum ]; then
        actual=$(sha256sum "$work/$archive")
    else
        actual=$(shasum -a 256 "$work/$archive")
    fi
    actual=${actual%% *}
    [ "$actual" = "$expected" ] || die 'Checksum mismatch; nothing installed'

    # Extract only the expected file from the verified archive.
    tar -xzf "$work/$archive" -C "$work" spill
    [ -f "$work/spill" ] && [ ! -L "$work/spill" ] || die 'Archive does not contain a regular spill binary'
    mkdir -p "$install_dir"
    [ ! -d "$install_dir/spill" ] || die 'Destination spill is a directory'
    # Stage on the destination filesystem so replacement is atomic.
    stage=$(mktemp -d "$install_dir/.spill-install.XXXXXX")
    cp "$work/spill" "$stage/spill"
    chmod 755 "$stage/spill"
    mv -f "$stage/spill" "$install_dir/spill"
    printf 'Installed spill %s to %s/spill\n' "$version" "$install_dir"
    case ":${PATH:-}:" in
        *:"$install_dir":*) ;;
        *) printf '\nAdd this directory to PATH in your shell profile:\n  export PATH="%s:$PATH"\n' "$install_dir" ;;
    esac
    printf '\nRun spill --help to get started. No services were started.\n'
}

fetch() {
    curl --fail --silent --show-error --location --retry 3 \
        --connect-timeout 15 --max-time 300 --proto '=https' --proto-redir '=https' --tlsv1.2 "$@"
}

die() {
    printf 'spill installer: %s\n' "$*" >&2
    exit 1
}

# Keep execution last so a truncated piped download cannot partially install.
main "$@"
