#!/usr/bin/env bash

set -e

if [ $# -ne 1 ] && [ $# -ne 2 ]; then
    echo "Usage: ./helpers/deploy_postgis.sh <values_base_dir> [<release_prefix>]"
    exit 1
fi

# ci_geosphere-test
values_base="$1"

# Prefix Example: testing-YYYYMMDD-
if [[ $# -eq 1 ]]; then
    release_prefix=""
else
    release_prefix="$2"
fi


ns=$(./helpers/get_namespace.sh)
# get password from any previous installation
# if we don't do this the password will get out of sync
# where password is accessed from the kubectl secret:
#   kubectl get secret --namespace geosphere <secret-name> -o jsonpath="{.data.postgresql-password}" | base64 --decode
release_name="${release_prefix}geosphere-postgis"
sec_info=$(kubectl get secret --namespace $ns "${release_name}-postgresql" || echo "")
echo $sec_info
auth_sec="${release_name}-postgresql"
if [[ "$sec_info" != "" ]]; then
    pw=$(kubectl get secret --namespace $ns $auth_sec -o jsonpath="{.data.postgresql-password}" | base64 -d);
    EXTRA_ARGS="--set postgresqlPassword=$pw";
fi
echo "Adding extra arguments: $EXTRA_ARGS"
helm repo add bitnami "https://charts.bitnami.com/bitnami"

helm upgrade -v 2 --install -f ${values_base}/values-postgis.yaml $EXTRA_ARGS --namespace $ns "${release_name}" bitnami/postgres
# do a little waiting for the postgres pod to be ready so future stages
# don't fail to communicate with it
echo "Start waiting for postgres: $(date +%Y%m%dT%H%M%S)"
kubectl wait -n $ns --selector=app.kubernetes.io/instance=${release_name} --timeout 120s --for=condition=Ready
status=$?
echo "Done waiting for postgis: $(date +%Y%m%dT%H%M%S) : $status"
exit $status