# shellcheck shell=bash
# shellcheck source=scripts/shared/lib/source_only
. "${BASH_SOURCE%/*}"/source_only

### Constants ###

readonly CE_IPSEC_IKEPORT=500
readonly CE_IPSEC_NATTPORT=4500
readonly SUBM_COLORCODES=blue
readonly SUBM_ENGINE_IMAGE_REPO=localhost:5000
readonly SUBM_ENGINE_IMAGE_TAG=${image_tag:-local}
# shellcheck disable=SC2034 # this variable is used elsewhere
# Some projects rely on the default subctl being determined by the PATH
readonly SUBCTL=${SUBCTL:-subctl}

### Functions ###

function deploytool_prereqs() {
    command -v subctl > /dev/null 2>&1
    "${SUBCTL}" version
    # shellcheck disable=SC2086 # image_tag should expand to nothing if empty
    import_image quay.io/submariner/submariner-operator ${image_tag}
}

function setup_broker() {
    local gn
    [[ $globalnet != true ]] || gn="--globalnet"
    echo "Installing broker..."
    # shellcheck disable=SC2086 # Split on purpose
    (
        cd "${OUTPUT_DIR}" && \
        "${SUBCTL}" deploy-broker \
               --kubeconfig "${KUBECONFIGS_DIR}/kind-config-$cluster" \
               ${gn} \
               ${deploytool_broker_args}
    )
}

function subctl_install_subm() {
    if [[ ${cluster_subm[$cluster]} != "true" ]]; then
        echo "Skipping installation as requested in cluster settings"
        return
    fi

    # We use the "subctl" image_tag to indicate that we want to let
    # subctl use its default repository and version
    subctlrepver=
    if [ "${SUBM_ENGINE_IMAGE_TAG}" != "subctl" ]; then
        subctlrepver="--repository ${SUBM_ENGINE_IMAGE_REPO} --version ${SUBM_ENGINE_IMAGE_TAG}"
    fi

    # shellcheck disable=SC2086 # Split on purpose
    "${SUBCTL}" join --kubeconfig "${KUBECONFIGS_DIR}/kind-config-$cluster" \
                --clusterid "${cluster}" \
                ${subctlrepver} \
                --nattport "${CE_IPSEC_NATTPORT}" \
                --ikeport "${CE_IPSEC_IKEPORT}" \
                --colorcodes "${SUBM_COLORCODES}" \
                --globalnet-cidr "${global_CIDRs[$cluster]}" \
                --disable-nat \
                --cable-driver "${cable_driver}" \
                ${deploytool_submariner_args} \
                "${OUTPUT_DIR}"/broker-info.subm
}

function install_subm_all_clusters() {
    run_subm_clusters subctl_install_subm
}
