#!/bin/bash

set -eu

: ${NAMESPACE:=openstack}

function run_tests_for_galera_cr {
    cr=$1

    # STEP 1: checks
    
    # get the current mariadbaccount for db root (default if the optional field is not set)
    db_root_account=$(oc -n $NAMESPACE get galera $cr -o json | jq -r .spec.rootDatabaseAccount)
    if [ -z "$db_root_account" ]; then
	db_root_account="${cr}-mariadb-root"
    fi

    # make sure the mariadbaccount cr exists
    oc -n $NAMESPACE get mariadbaccount $db_root_account -o name > /dev/null
    test $? -eq 0

    # get the secret currently targeted in the root mariadbaccount
    account_status_secret=$(oc -n $NAMESPACE get mariadbaccount ${cr}-mariadb-root -o json | jq -r .status.currentSecret)
    
    # make sure this secret is what the galera CR relies upon
    oc -n $NAMESPACE wait galera $cr --for=jsonpath="{.status.rootDatabaseSecret}=$account_status_secret"

    # make sure the secret has a mariadbaccount finalizer, i.e. the mariadb-operator knows
    # about it and would prevent its deletion while it depends on it
    oc -n $NAMESPACE get secret $account_status_secret -o json | jq -r ".metadata.finalizers | .[]" | grep -wq openstack.org/mariadbaccount

    # STEP 2: password update

    # create new secret in Openshift, with a random password
    RANDOMPASS=pass$RANDOM
    NEWPASSNAME=${cr}-new-db-root-secret-$RANDOM
    cat >$NEWPASSNAME.yaml <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: $NEWPASSNAME
type: Opaque
stringData:
  DatabasePassword: "$RANDOMPASS"
EOF
    oc -n $NAMESPACE apply -f $NEWPASSNAME.yaml

    # configure the mariadbaccount CR to use this new secret as the new root password
    oc -n $NAMESPACE patch --type=merge mariadbaccount ${cr}-mariadb-root -p '{"spec": {"secret": "'${NEWPASSNAME}'"}}'

    # STEP 3: post update checks
    
    # wait for the galera CR to pick up the new secret
    oc -n $NAMESPACE wait galera $cr --for=jsonpath="{.status.rootDatabaseSecret}=${NEWPASSNAME}"

    # make sure the new secret has a finalizer assigned to it
    oc -n $NAMESPACE get secret $NEWPASSNAME -o json | jq -r ".metadata.finalizers | .[]" | grep -wq openstack.org/mariadbaccount

    # make sure the old secret is no longer managed by the mariadb-operator (finalizer gone)
    out=$(oc -n $NAMESPACE get secret $account_status_secret -o json | jq -r "select(.metadata.finalizers!=null).metadata.finalizers | .[] | select(contains(\"openstack.org/mariadbaccount\"))")
    test -z "$out"

    # make sure that the running galera pod sees the new password
    pod_pass=$(oc exec -c galera ${cr}-galera-0 -- bash -c '. /var/lib/operator-scripts/mysql_root_auth.sh; echo $MYSQL_PWD')
    test "$pod_pass" = "$RANDOMPASS"
}

run_tests_for_galera_cr openstack
