#!/usr/bin/env bash

# Default environment
ENVIRONMENT="default"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --env|--environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        *)
            echo "Unknown argument: $1"
            exit 1
            ;;
    esac
done

# Set URL based on environment
case "$ENVIRONMENT" in
    dev)
        SOURCEGRAPH_URL="https://sourcegraph.nonprod-dev.dwpcloud.uk"
        ;;
    test)
        SOURCEGRAPH_URL="https://sourcegraph.nonprod-test.dwpcloud.uk"
        ;;
    nonprod)
        SOURCEGRAPH_URL="https://sourcegraph.nonprod.dwpcloud.uk"
        ;;
    default)
        SOURCEGRAPH_URL="https://sourcegraph.nonprod.dwpcloud.uk"
        ;;
    *)
        echo "Invalid environment: $ENVIRONMENT"
        exit 1
        ;;
esac

# Determine token based on environment
if [[ "$ENVIRONMENT" == "default" || "$ENVIRONMENT" == "nonprod" ]]; then
    USER_TOKEN="$SOURCEGRAPH_TOKEN"
else
    TOKEN_VAR="SOURCEGRAPH_TOKEN_$(echo "$ENVIRONMENT" | tr '[:lower:]' '[:upper:]')"
    USER_TOKEN="${!TOKEN_VAR}"
fi

# Prompt if token is not set
if [ -z "$USER_TOKEN" ]; then
    echo "No token found for environment '$ENVIRONMENT'."
    read -rsp "Enter Sourcegraph token for $ENVIRONMENT: " USER_TOKEN
    echo
fi

# API endpoint
API_ENDPOINT="/.api/graphql"

# GraphQL query to get Sourcegraph version
GRAPHQL_QUERY='{"query":"{ site { productVersion } }"}'

# Function to get the Sourcegraph version
get_sourcegraph_version() {
    curl -s -H "Authorization: token $USER_TOKEN" \
         -H "Content-Type: application/json" \
         -d "$GRAPHQL_QUERY" \
         "$SOURCEGRAPH_URL$API_ENDPOINT" | \
    jq -r '.data.site.productVersion'
}

# Output the version
version=$(get_sourcegraph_version)
echo "Sourcegraph version ($ENVIRONMENT): $version"
