#!/bin/sh
set -e

# ==============================================================================
# Grafbase Gateway
#
# Usage:
#   - Latest version: curl -sL https://your-domain.com/install | sh
#   - Specific version: curl -sL https://your-domain.com/install | sh -s 0.53.2
# ==============================================================================

GH_OWNER="grafbase"
GH_REPO="grafbase"
BINARY_NAME="grafbase-gateway"

supports_color() {
    if [ ! -t 1 ]; then
        return 1
    fi

    if [ -z "$TERM" ] || [ "$TERM" = "dumb" ]; then
        return 1
    fi

    if command -v tput >/dev/null 2>&1; then
        COLORS=$(tput colors 2>/dev/null || true)
        if [ -n "$COLORS" ] && [ "$COLORS" -ge 8 ] 2>/dev/null; then
            return 0
        fi
        return 1
    fi

    return 0
}

init_colors() {
    if supports_color; then
        INFO_PREFIX="\033[34m[INFO]\033[0m"
        ERROR_PREFIX="\033[31m[ERROR]\033[0m"
    else
        INFO_PREFIX="[INFO]"
        ERROR_PREFIX="[ERROR]"
    fi
}

info() {
    printf "%b %s\n" "$INFO_PREFIX" "$1"
}

error() {
    printf "%b %s\n" "$ERROR_PREFIX" "$1" >&2
    exit 1
}

check_tool() {
    if ! command -v "$1" >/dev/null 2>&1; then
        error "'$1' is required but it's not installed. Please install it to continue."
    fi
}

detect_arch() {
    OS_TYPE=$(uname -s)
    ARCH_TYPE=$(uname -m)

    info "Detecting operating system and architecture..."

    case $OS_TYPE in
        Linux)
            OS="unknown-linux-musl"
            ;;
        Darwin)
            OS="apple-darwin"
            ;;
        *)
            error "Unsupported operating system: '$OS_TYPE'. Please see https://github.com/grafbase/grafbase for alternative installation methods."
            ;;
    esac

    case $ARCH_TYPE in
        x86_64 | amd64)
            ARCH="x86_64"
            ;;
        aarch64 | arm64)
            ARCH="aarch64"
            ;;
        *)
            error "Unsupported architecture: '$ARCH_TYPE'. Please see https://github.com/grafbase/grafbase for alternative installation methods."
            ;;
    esac

    TARGET_TRIPLE="${ARCH}-${OS}"
    info "System detected: ${TARGET_TRIPLE}"
}

get_version() {
    if [ -n "$1" ]; then
        case "$1" in
            gateway-*)
                VERSION="$1"
                ;;
            v*)
                VERSION="gateway-${1#v}"
                ;;
            *)
                VERSION="gateway-$1"
                ;;
        esac
        info "Installing specified version: $VERSION"
    else
        info "No version specified. Fetching the latest Gateway release from GitHub..."

        VERSION="$(curl -fsSL "https://api.github.com/repos/${GH_OWNER}/${GH_REPO}/releases/latest" | grep -m1 '"tag_name":' | sed -E 's/.*"tag_name":[[:space:]]*"([^"]+)".*/\1/' || true)"

        if [ -z "$VERSION" ]; then
            info "GitHub API unavailable or rate-limited. Falling back to release redirect..."
            LATEST_RELEASE_URL="$(curl -fsSL -o /dev/null -w '%{url_effective}' "https://github.com/${GH_OWNER}/${GH_REPO}/releases/latest" || true)"
            VERSION="$(printf "%s" "$LATEST_RELEASE_URL" | sed -nE 's#.*/releases/tag/([^/?#]+).*#\1#p')"
        fi

        if [ -z "$VERSION" ]; then
            error "Could not determine the latest version from GitHub. Please specify a version manually."
        fi

        case "$VERSION" in
            gateway-*)
                ;;
            *)
                error "Latest release tag '$VERSION' is not a Gateway release tag. Please specify a Gateway version manually."
                ;;
        esac

        if [ "$VERSION" = "gateway-" ]; then
            error "Could not determine a valid Gateway version from GitHub Releases."
        fi

        info "Latest version found: $VERSION"
    fi
}

download_and_install() {
    ASSET_NAME="grafbase-gateway-${TARGET_TRIPLE}"
    DOWNLOAD_URL="https://github.com/${GH_OWNER}/${GH_REPO}/releases/download/${VERSION}/${ASSET_NAME}"

    info "Downloading binary from: ${DOWNLOAD_URL}"

    # -f: Fail silently on server errors (like 404)
    # -L: Follow redirects
    if ! curl -fL -o "./${BINARY_NAME}" "${DOWNLOAD_URL}"; then
        error "Download failed. Please check if the version '$VERSION' and target '${TARGET_TRIPLE}' exist for this release."
    fi

    chmod +x "./${BINARY_NAME}"

    info "✅ Successfully installed '${BINARY_NAME}' to the current directory."
    info "You can now run it with: ./${BINARY_NAME}"
    info ""
    info "Grafbase has joined The Guild: https://the-guild.dev/graphql/hive/blog/acquired-grafbase"
    info ""
    info "Release page: https://github.com/grafbase/grafbase/releases"
    info "Documentation: https://grafbase.com/docs"
}

main() {
    init_colors

    check_tool "curl"
    check_tool "grep"
    check_tool "sed"
    check_tool "uname"

    detect_arch
    get_version "$1"
    download_and_install
}

main "$@"
