#!/bin/sh
# kuberoku installer — downloads the latest (or pinned) binary for your platform.
#
# Usage:
#   curl -fsSL https://github.com/amanjain/kuberoku/releases/latest/download/install.sh | sh
#
# Environment variables:
#   KUBEROKU_VERSION      — install a specific version (e.g. "v0.1.0"), default: latest
#   KUBEROKU_INSTALL_DIR  — custom install directory, default: /usr/local/bin or ~/.local/bin

set -e

REPO="amanjain/kuberoku"
BINARY_NAME="kuberoku"

# --- helpers ---

log() {
    printf '[kuberoku] %s\n' "$1"
}

err() {
    printf '[kuberoku] ERROR: %s\n' "$1" >&2
    exit 1
}

need_cmd() {
    if ! command -v "$1" > /dev/null 2>&1; then
        err "need '$1' (command not found)"
    fi
}

# --- detect platform ---

detect_os() {
    case "$(uname -s)" in
        Linux*)  echo "linux" ;;
        Darwin*) echo "darwin" ;;
        CYGWIN*|MINGW*|MSYS*)
            err "Windows is not supported by this installer. Download the binary from https://github.com/${REPO}/releases"
            ;;
        *)
            err "unsupported OS: $(uname -s)"
            ;;
    esac
}

detect_arch() {
    case "$(uname -m)" in
        x86_64|amd64)   echo "amd64" ;;
        aarch64|arm64)   echo "arm64" ;;
        *)
            err "unsupported architecture: $(uname -m)"
            ;;
    esac
}

# --- download helper ---

download() {
    url="$1"
    dest="$2"
    if command -v curl > /dev/null 2>&1; then
        curl -fsSL -o "$dest" "$url"
    elif command -v wget > /dev/null 2>&1; then
        wget -qO "$dest" "$url"
    else
        err "need 'curl' or 'wget' to download files"
    fi
}

# --- resolve version ---

resolve_version() {
    if [ -n "${KUBEROKU_VERSION:-}" ]; then
        echo "${KUBEROKU_VERSION}"
    else
        # Fetch latest release tag from GitHub API
        if command -v curl > /dev/null 2>&1; then
            tag=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name"' | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/')
        elif command -v wget > /dev/null 2>&1; then
            tag=$(wget -qO- "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name"' | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/')
        else
            err "need 'curl' or 'wget' to resolve latest version"
        fi
        if [ -z "$tag" ]; then
            err "could not determine latest version. Set KUBEROKU_VERSION explicitly."
        fi
        echo "$tag"
    fi
}

# --- resolve install dir ---

resolve_install_dir() {
    if [ -n "${KUBEROKU_INSTALL_DIR:-}" ]; then
        echo "${KUBEROKU_INSTALL_DIR}"
    elif [ -w /usr/local/bin ]; then
        echo "/usr/local/bin"
    else
        dir="${HOME}/.local/bin"
        mkdir -p "$dir"
        echo "$dir"
    fi
}

# --- main ---

main() {
    os="$(detect_os)"
    arch="$(detect_arch)"
    version="$(resolve_version)"
    install_dir="$(resolve_install_dir)"

    # Validate supported platform
    case "${os}-${arch}" in
        linux-amd64|linux-arm64|darwin-amd64|darwin-arm64) ;;
        *)
            err "no pre-built binary for ${os}/${arch}. Use 'pip install kuberoku' instead." ;;
    esac

    asset="${BINARY_NAME}-${os}-${arch}"
    url="https://github.com/${REPO}/releases/download/${version}/${asset}"

    log "platform: ${os}/${arch}"
    log "version:  ${version}"
    log "target:   ${install_dir}/${BINARY_NAME}"

    # Download to a temp file then move atomically
    tmpfile="$(mktemp)"
    trap 'rm -f "$tmpfile"' EXIT

    log "downloading ${url} ..."
    download "$url" "$tmpfile"

    # Verify download produced a non-empty file
    if [ ! -s "$tmpfile" ]; then
        err "download failed — file is empty"
    fi

    chmod +x "$tmpfile"

    # Remove macOS quarantine attribute if present
    if [ "$os" = "darwin" ]; then
        xattr -d com.apple.quarantine "$tmpfile" 2>/dev/null || true
    fi

    mv "$tmpfile" "${install_dir}/${BINARY_NAME}"

    # Verify
    if "${install_dir}/${BINARY_NAME}" --version > /dev/null 2>&1; then
        installed_version="$("${install_dir}/${BINARY_NAME}" --version 2>&1)"
        log "installed: ${installed_version}"
    else
        log "installed to ${install_dir}/${BINARY_NAME} (could not verify version)"
    fi

    # Warn if not in PATH
    case ":${PATH}:" in
        *":${install_dir}:"*) ;;
        *)
            log "WARNING: ${install_dir} is not in your PATH"
            log "Add it with: export PATH=\"${install_dir}:\$PATH\""
            ;;
    esac

    log "done! Run 'kuberoku --help' to get started."
}

main
