#!/usr/bin/env bash

GEOSPHERE_NAMESPACE="${GEOSPHERE_NAMESPACE:-"geosphere"}"
GEOSPHERE_TEST_NAMESPACE="${GEOSPHERE_TEST_NAMESPACE:-"geosphere-test"}"
TESTS_NAMESPACE="${TESTS_NAMESPACE:-"geosphere-ci-tests"}"

debug() {
    >&2 echo "DEBUG: $@"
}

error() {
    >&2 echo "ERROR: $@"
}

if [[ -n "$CI_COMMIT_TAG" ]]; then
    debug "Tag detected: $CI_COMMIT_TAG"
    if [[ $CI_COMMIT_TAG =~ $GEOSPHERE_TAG_REGEX ]]; then
        debug "geosphere tag matched"
        ns="${GEOSPHERE_NAMESPACE}"
    elif [[ $CI_COMMIT_TAG =~ $GEOSPHERE_TEST_TAG_REGEX ]]; then
        debug "geosphere-test tag matched"
        ns="${GEOSPHERE_TEST_NAMESPACE}"
    elif [[ $CI_COMMIT_TAG =~ $GCP_TAG_REGEX ]]; then
        debug "gcp tag matched"
        ns="${GCP_NAMESPACE}"
    fi
elif [[ $CI_PROJECT_NAMESPACE =~ $TESTS_PROJECT_NAMESPACE ]]; then
    debug "Tests project namespace matched"
    ns="${TESTS_NAMESPACE}"
else
    debug "Could not determine namespace | $CI_COMMIT_TAG | $CI_PROJECT_NAMESPACE"
fi

if [[ -z $ns ]]; then
    error "Kubernetes jobs don't run unless in master branch or tagged"
    exit 1
fi

debug "Namespace is \"$ns\""
echo $ns
