#!/bin/bash
set -e

source ${SCRIPTS_DIR}/lib/cluster_settings
source ${DAPPER_SOURCE}/scripts/cluster_settings
source ${SCRIPTS_DIR}/lib/debug_functions
source ${SCRIPTS_DIR}/lib/deploy_funcs
source ${SCRIPTS_DIR}/lib/utils
source ${SCRIPTS_DIR}/lib/version

### Functions ###

function update_coredns_configmap() {
    kubectl get cm -n kube-system coredns -o yaml > /tmp/coremap-${cluster}.yaml
    if !(grep -q clusterset /tmp/coremap-${cluster}.yaml); then
        CLUSTER_IP=`kubectl get svc -n submariner-operator submariner-lighthouse-coredns | tail -n 1| awk '{print $3;}'`
        sed 's/dnsip/'${CLUSTER_IP}'/g' scripts/resources/coredns-cm.yaml > /tmp/coredns-cm-${CLUSTER_IP}.yaml
        sed -i -e "/Corefile:/r /tmp/coredns-cm-${CLUSTER_IP}.yaml" /tmp/coremap-${cluster}.yaml
        kubectl -n kube-system replace -f /tmp/coremap-${cluster}.yaml
        kubectl -n kube-system describe cm coredns
    fi 
}

### Extract the image_tag if necessary ###
image_tag=
for arg; do
    if [[ "$arg" =~ "--image_tag=" ]]; then
        image_tag=${arg##*=}
    fi
done

### Main ###

declare_kubeconfig
import_image quay.io/submariner/lighthouse-agent ${image_tag}
import_image quay.io/submariner/lighthouse-coredns ${image_tag}

${SCRIPTS_DIR}/deploy.sh "$@"

run_subm_clusters update_coredns_configmap
