set -o errexit
set -o nounset

echo "using RHACM kubeconfig $ACM_KUBECONFIG"
echo "managed cluster name: $CLUSTER_NAME"

if [[ $REMOTE_CONNECTION_TYPE != "ssh" && $REMOTE_CONNECTION_TYPE != "kubeconfig" ]] 
then
    echo "env var REMOTE_CONNECTION_TYPE not configured, please refer to README instructions"
else
    # create namespace for MC
    KUBECONFIG=$ACM_KUBECONFIG oc new-project ${CLUSTER_NAME}
    KUBECONFIG=$ACM_KUBECONFIG oc label namespace ${CLUSTER_NAME} cluster.open-cluster-management.io/managedCluster=${CLUSTER_NAME}

    # create mc resource
    envsubst < resources/managed-cluster.yaml | KUBECONFIG=$ACM_KUBECONFIG oc apply -f -

    if [ $REMOTE_CONNECTION_TYPE == "ssh" ]
    then
        echo "managed cluster shell address: $SHELL_ADDR"
        echo "shell key path: $SSH_KEY"

        echo "using remote shell to deploy cluster addons"
        echo "==== begin ===="
        # apply klusterlet-crd.yaml that was generated by the import controller on remote cluster
        ssh -i ${SSH_KEY} ${SHELL_ADDR} "echo $(oc get secret ${CLUSTER_NAME}-import -n ${CLUSTER_NAME} -o jsonpath={.data.crds\\.yaml}) | base64 -d | kubectl apply -f -"

        # apply import.yaml that was generated by the import controller on remote cluster
        ssh -i ${SSH_KEY} ${SHELL_ADDR} "echo $(oc get secret ${CLUSTER_NAME}-import -n ${CLUSTER_NAME} -o jsonpath={.data.import\\.yaml}) | base64 -d | kubectl apply -f -"
        echo "==== end ===="
    else
        echo "managed cluster kubeconfig $EDGE_KUBECONFIG"

        echo "using edge kubeconfig to deploy cluster addons"
        echo "==== begin ===="
        envsubst < resources/auto-import-secret.yaml | KUBECONFIG=$ACM_KUBECONFIG oc apply -f -
        echo "==== end ===="
    fi

    # apply klusterlet-addon-config.yaml on ACM cluster
    envsubst < resources/klusterlet-addon-config.yaml | KUBECONFIG=$ACM_KUBECONFIG oc apply -f -
fi








