#!/bin/bash
#
#
#

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


LOCAL_BACKUP_DIR="${HOME}/backups/${STAGE}"
POSTGRES_BACKUP_DIR="${LOCAL_BACKUP_DIR}/postgres"
WORDPRESS_BACKUP_DIR="${LOCAL_BACKUP_DIR}/wordpress"
METRICS_FILE=${HOME}/metrics_${STAGE}.prom

mkdir -p ${POSTGRES_BACKUP_DIR}
mkdir -p ${WORDPRESS_BACKUP_DIR}

rm -rf ${POSTGRES_BACKUP_DIR}/*
rm -rf ${WORDPRESS_BACKUP_DIR}/*

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

mc mirror ${STAGE}/postgres ${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 mirror ${STAGE}/wordpress ${WORDPRESS_BACKUP_DIR} --overwrite --newer-than 1d --json | jq -e '.transferred != 0'
if [ "$?" -eq "0" ] 
then
  NIGHTLY_BACKUP_SUCCESSFUL_WORDPRESS="0"
else
  NIGHTLY_BACKUP_SUCCESSFUL_WORDPRESS="1"
fi

mc alias rm ${STAGE}

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_$STAGE
# TYPE nightly_backup_successful_$STAGE gauge
nightly_backup_successful_$STAGE{stage="$STAGE"} 0
EOF
else
  echo "Nightly Backup Failed - writing METRICS_FILE"
  cat <<EOF > $METRICS_FILE
# HELP nightly_backup_successful_$STAGE
# TYPE nightly_backup_successful_$STAGE gauge
nightly_backup_successful_$STAGE{stage="$STAGE"} 1
EOF
fi
