#!/usr/bin/env bash

fail() {
    echo "$@"
    exit 3
}

if [[ $# -eq 3 ]]; then
    ns=$1
    pvc_file=$2
    pvc_name=$3
    EXTRA_ARGS="--namespace $ns"
elif [[ $# -eq 4 ]]; then
    ns=$1
    pvc_file=$2
    pvc_name=$3
    kubeconfig=$4
    EXTRA_ARGS="--namespace $ns --kubeconfig $kubeconfig"
else
    echo "Usage: ./create_pvc.sh <kubernetes namespace> <PVC YAML definition> <PVC name> [<kubernetes config file>]"
    exit 1
fi


# If another project started this build or we don't know if the file changed
# (git tag) then we know the provided definition didn't change (or probably
# didn't). Let's make sure it exists on the cluster and if so, don't
# try to recreate it.
if [[ $CI_PIPELINE_SOURCE == "pipeline" ]] || [[ $CI_COMMIT_TAG != null ]]; then
    pvc_exists=$(kubectl $EXTRA_ARGS get pvc $pvc_name -o jsonpath="{.metadata.name}" || echo "")
    if [[ "$pvc_exists" != "" ]]; then
        # it exists
        exit 0
    fi
fi

pvc_pending=$(kubectl $EXTRA_ARGS get pvc $pvc_name -o jsonpath="{.status.phase}" || echo "")
if [[ $pvc_pending == "" ]]; then
    echo "PVC does not exist, creating..."
elif [[ $pvc_pending != "Pending" ]]; then
    echo "PVC already exists and is not pending. Manually 'helm uninstall' all bound pods"
    exit 2
else
    echo "PVC exists but is pending, deleting then recreating..."
    kubectl $EXTRA_ARGS delete pvc $pvc_name || fail "Could not delete existing PVC"
fi


kubectl $EXTRA_ARGS apply -f $pvc_file