#!/bin/bash

# TT#97050 Use ngcp-sync-grants check only mode if available

set -eu

die() {
  local message="$*"

  echo "ERROR: ${message}" >&2
  exit 1
}

fatal_missing_var() {
  local var_name="$1"
  if [[ ! -v "${var_name}" ]] ; then
    die "Missing mandatory environment variable '\$${var_name}', exiting."
  fi

  local var_value="${!var_name}"
  if [[ -z "${var_value}" ]] ; then
    die "Empty mandatory environment variable '\$${var_name}', exiting."
  fi
}

fatal_missing_var FORCE_UPGRADE

if ! ngcp-sync-grants --help |& grep 'check|-c' &>/dev/null ; then
  echo "WARNING: ngcp-sync-grants does not support check-only mode, not performing this check"
  exit 0
fi

echo "INFO: will execute read-only operation to check if grants in DB and"
echo "      /etc/mysql/grants.yml are in sync: ngcp-sync-grants --check"

TMPFILE=$(mktemp)
ngcp-sync-grants --check |& tee "${TMPFILE}"

initial_message="--> ** running in 'check only' mode, no changes are made to the users/grants **"
if grep -F -- "${initial_message}" "${TMPFILE}" &>/dev/null && [[ $(wc -l "${TMPFILE}" | awk '{print $1}') = 1 ]]; then
  rm -f "${TMPFILE}"
  echo "INFO: contents of /etc/mysql/grants.yml and DB seem to be in sync, all OK"
  exit 0
else
  rm -f "${TMPFILE}"
  die "contents of /etc/mysql/grants.yml and DB are not in sync, this will cause problems in later stages, please fix"
fi
