#!/bin/sh
# Installs the bcdock CLI binary from GitHub Releases.
#
# Usage:
#   curl -fsSL https://cli.bcdock.io/install.sh | sh
#
# Environment variables:
#   BCDOCK_VERSION      pin a specific release tag (e.g. v0.1.0); default: latest
#   BCDOCK_INSTALL_DIR  skip /usr/local/bin, install directly to this directory

set -eu

GITHUB_REPO="bcdock/cli"
BINARY_NAME="bcdock"

# ── OS detection ─────────────────────────────────────────────────────────────
_os=$(uname -s)
case "$_os" in
    Linux)  _os_name="linux" ;;
    Darwin) _os_name="macos" ;;
    MINGW*|MSYS*|CYGWIN*)
        echo "Windows is not supported by this script." >&2
        echo "Download the binary from: https://github.com/${GITHUB_REPO}/releases" >&2
        exit 1
        ;;
    *)
        echo "Unsupported OS: ${_os}" >&2
        exit 1
        ;;
esac

# ── Arch detection ───────────────────────────────────────────────────────────
_arch=$(uname -m)
case "$_arch" in
    x86_64)          _arch_name="x86_64" ;;
    arm64|aarch64)   _arch_name="arm64" ;;
    *)
        echo "Unsupported architecture: ${_arch}" >&2
        exit 1
        ;;
esac

# ── Version resolution ───────────────────────────────────────────────────────
if [ -n "${BCDOCK_VERSION:-}" ]; then
    _version="$BCDOCK_VERSION"
else
    printf "Fetching latest release... "
    _api_resp=$(curl -fsSL "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null) || {
        echo "" >&2
        echo "error: failed to fetch release info from GitHub API" >&2
        exit 1
    }
    _version=$(printf '%s' "$_api_resp" | grep '"tag_name"' | head -1 \
        | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/')
    if [ -z "$_version" ]; then
        echo "" >&2
        echo "error: could not parse release version from GitHub API response" >&2
        exit 1
    fi
    echo "$_version"
fi

# GoReleaser strips the leading 'v' from archive filenames.
_version_num="${_version#v}"

# ── Build archive name matching .goreleaser.yml:53-59 ────────────────────────
# darwin->macos, amd64->x86_64; aarch64->arm64 already handled above.
_archive="${BINARY_NAME}_${_version_num}_${_os_name}_${_arch_name}.tar.gz"
_base_url="https://github.com/${GITHUB_REPO}/releases/download/${_version}"
_archive_url="${_base_url}/${_archive}"
_checksums_url="${_base_url}/checksums.txt"

# ── Temp dir (cleaned up on any exit) ───────────────────────────────────────
_tmpdir=$(mktemp -d)
trap 'rm -rf "$_tmpdir"' EXIT INT TERM

echo "Downloading ${BINARY_NAME} ${_version} (${_os_name}/${_arch_name})..."
curl -fsSL --output "${_tmpdir}/${_archive}" "$_archive_url" || {
    echo "error: download failed: ${_archive_url}" >&2
    exit 1
}
curl -fsSL --output "${_tmpdir}/checksums.txt" "$_checksums_url" || {
    echo "error: download failed: ${_checksums_url}" >&2
    exit 1
}

# ── Checksum verification (mandatory - no skip path) ────────────────────────
_expected=$(awk -v f="$_archive" '$2 == f {print $1}' "${_tmpdir}/checksums.txt")
if [ -z "$_expected" ]; then
    echo "error: ${_archive} not found in checksums.txt" >&2
    exit 1
fi

if command -v sha256sum >/dev/null 2>&1; then
    _actual=$(sha256sum "${_tmpdir}/${_archive}" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
    _actual=$(shasum -a 256 "${_tmpdir}/${_archive}" | awk '{print $1}')
else
    echo "error: no SHA-256 tool found (tried sha256sum, shasum)" >&2
    exit 1
fi

if [ "$_actual" != "$_expected" ]; then
    echo "error: checksum mismatch for ${_archive}" >&2
    echo "  expected: ${_expected}" >&2
    echo "  actual:   ${_actual}" >&2
    exit 1
fi

# ── Extract ──────────────────────────────────────────────────────────────────
tar -xzf "${_tmpdir}/${_archive}" -C "$_tmpdir" "$BINARY_NAME"
chmod 755 "${_tmpdir}/${BINARY_NAME}"

# ── Install ──────────────────────────────────────────────────────────────────
if [ -n "${BCDOCK_INSTALL_DIR:-}" ]; then
    mkdir -p "$BCDOCK_INSTALL_DIR"
    mv "${_tmpdir}/${BINARY_NAME}" "${BCDOCK_INSTALL_DIR}/${BINARY_NAME}"
    _install_dir="$BCDOCK_INSTALL_DIR"
elif [ -w "/usr/local/bin" ]; then
    mv "${_tmpdir}/${BINARY_NAME}" "/usr/local/bin/${BINARY_NAME}"
    _install_dir="/usr/local/bin"
elif command -v sudo >/dev/null 2>&1; then
    echo "Installing to /usr/local/bin (sudo required)..."
    sudo mv "${_tmpdir}/${BINARY_NAME}" "/usr/local/bin/${BINARY_NAME}"
    _install_dir="/usr/local/bin"
else
    _install_dir="${HOME}/.bcdock/bin"
    mkdir -p "$_install_dir"
    mv "${_tmpdir}/${BINARY_NAME}" "${_install_dir}/${BINARY_NAME}"
    printf '\nnote: installed to %s\n' "$_install_dir" >&2
    # shellcheck disable=SC2016
    printf 'Add to PATH: export PATH="%s:$PATH"\n' "$_install_dir" >&2
fi

printf '\nInstalled: %s/%s (%s)\nNext: bcdock auth login\n' \
    "$_install_dir" "$BINARY_NAME" "$_version"
