#!/bin/bash
#
#
#

MINIO_URL=$1
ACCESSKEY=$2
SECRETKEY=$3


LOCAL_BACKUP_DIR="${HOME}/backups"
KEYCLOAK_POSTGRES_BACKUP_DIR="${LOCAL_BACKUP_DIR}/keycloak-postgres"
METRICS_FILE=${HOME}/metrics_keycloak.prom

mkdir -p ${KEYCLOAK_POSTGRES_BACKUP_DIR}

rm -rf ${KEYCLOAK_POSTGRES_BACKUP_DIR}/*

mc alias set keycloak ${MINIO_URL} ${ACCESSKEY} ${SECRETKEY}

mc mirror keycloak/postgres ${KEYCLOAK_POSTGRES_BACKUP_DIR} --overwrite --newer-than 1d --json | jq -e '.transferred != 0'
if [ "$?" -eq "0" ] 
then
  NIGHTLY_BACKUP_SUCCESSFUL_POSTGRES="0"
else
  NIGHTLY_BACKUP_SUCCESSFUL_POSTGRES="1"
fi


mc alias rm keycloak

if [[ ${NIGHTLY_BACKUP_SUCCESSFUL_POSTGRES} -eq "0" ]] && [[ ${NIGHTLY_BACKUP_SUCCESSFUL_WORDPRESS} -eq "0" ]]
then
  echo "Nightly Backup Successful - writing METRICS_FILE"
  cat <<EOF > $METRICS_FILE
# HELP nightly_backup_successful_keycloak
# TYPE nightly_backup_successful_keycloak gauge
nightly_backup_successful_keycloak{stage="keycloak"} 0
EOF
else
  echo "Nightly Backup Failed - writing METRICS_FILE"
  cat <<EOF > $METRICS_FILE
# HELP nightly_backup_successful_keycloak
# TYPE nightly_backup_successful_keycloak gauge
nightly_backup_successful_keycloak{stage="keycloak"} 1
EOF
fi