#!/usr/bin/env sh
# Telhar CLI installer (macOS / Linux)
#
# Usage:
#   curl -fsSL https://get.telhar.io | sh
#   TELHAR_CLI_VERSION=v0.4.0 curl -fsSL ... | sh     # pin a version
#
# Every download is verified against the SHA256SUMS asset of the release
# before it is installed. See SECURITY.md for cosign signature verification.
set -eu

# GitLab project ID of the distribution repository. API URLs by ID are stable
# even if the project is transferred to another namespace/group.
PROJECT_ID="${TELHAR_CLI_PROJECT_ID:-84123513}"
API="https://gitlab.com/api/v4/projects/${PROJECT_ID}"

VERSION="${TELHAR_CLI_VERSION:-latest}"
INSTALL_DIR="${TELHAR_CLI_INSTALL_DIR:-${HOME}/.local/bin}"
BINARY_NAME="telhar-cli"

info() { printf '  \033[36m->\033[0m %s\n' "$*"; }
ok()   { printf '  \033[32mok\033[0m %s\n' "$*"; }
die()  { printf '  \033[31mERROR\033[0m %s\n' "$*" >&2; exit 1; }

main() {
    command -v curl >/dev/null 2>&1 || die "curl is required"

    # ── Detect platform ──────────────────────────────────────────────────
    os="$(uname -s)"
    arch="$(uname -m)"
    case "${os}-${arch}" in
        Darwin-arm64)            target="aarch64-apple-darwin" ;;
        Darwin-x86_64)           target="x86_64-apple-darwin" ;;
        Linux-x86_64)            target="x86_64-unknown-linux-musl" ;;
        Linux-aarch64|Linux-arm64) target="aarch64-unknown-linux-musl" ;;
        *) die "unsupported platform: ${os} ${arch}" ;;
    esac
    info "platform: ${target}"

    # ── Resolve version ──────────────────────────────────────────────────
    if [ "${VERSION}" = "latest" ]; then
        VERSION="$(curl -fsSL "${API}/releases" 2>/dev/null \
            | tr ',' '\n' | grep -m1 '"tag_name"' | cut -d'"' -f4)" || true
        [ -n "${VERSION:-}" ] || die "no releases published yet — see https://gitlab.com/telhar-io/cli-releases/-/releases"
    fi
    info "version: ${VERSION}"

    asset="${BINARY_NAME}-${VERSION}-${target}.tar.gz"
    pkg="${API}/packages/generic/${BINARY_NAME}/${VERSION}"

    # ── Download into a temp dir ─────────────────────────────────────────
    tmp="$(mktemp -d)"
    trap 'rm -rf "${tmp}"' EXIT
    info "downloading ${asset}"
    curl -fsSL -o "${tmp}/${asset}" "${pkg}/${asset}" \
        || die "download failed: ${pkg}/${asset}"
    curl -fsSL -o "${tmp}/SHA256SUMS" "${pkg}/SHA256SUMS" \
        || die "download failed: SHA256SUMS (refusing to install unverified binary)"

    # ── Verify checksum (mandatory) ──────────────────────────────────────
    expected="$(grep " ${asset}\$" "${tmp}/SHA256SUMS" | cut -d' ' -f1)"
    [ -n "${expected}" ] || die "no checksum entry for ${asset} in SHA256SUMS"
    if command -v sha256sum >/dev/null 2>&1; then
        actual="$(sha256sum "${tmp}/${asset}" | cut -d' ' -f1)"
    else
        actual="$(shasum -a 256 "${tmp}/${asset}" | cut -d' ' -f1)"
    fi
    [ "${expected}" = "${actual}" ] || die "checksum mismatch for ${asset}: expected ${expected}, got ${actual}"
    ok "sha256 verified"

    # ── Install ──────────────────────────────────────────────────────────
    mkdir -p "${INSTALL_DIR}"
    tar -xzf "${tmp}/${asset}" -C "${tmp}"
    install -m 0755 "${tmp}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}"
    ok "installed ${INSTALL_DIR}/${BINARY_NAME} (${VERSION})"

    case ":${PATH}:" in
        *":${INSTALL_DIR}:"*) ;;
        *) info "add to PATH:  export PATH=\"${INSTALL_DIR}:\$PATH\"" ;;
    esac
    "${INSTALL_DIR}/${BINARY_NAME}" --version || true
}

main "$@"
