#!/usr/bin/env bash

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


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

kubectl $EXTRA_ARGS replace -f $pvc