#!/bin/bash

set -e

die() {
  echo "ERROR: $*" >&2
  exit 1
}

if ! [[ -r /etc/ngcp-backup-tools/db-backup.conf ]] ; then
  die "Cannot read mandatory config file: /etc/ngcp-backup-tools/db-backup.conf"
fi

# shellcheck disable=SC1091
source /etc/ngcp-backup-tools/db-backup.conf

if [[ -z "${BACKUP}" ]] ; then
  die "Missing mandatory environment variable '\$BACKUP', cannot continue!"
fi

if [[ -z "${NGCP_DB_BACKUP_FINAL_LIST[*]}" ]] ; then
  die "Missing mandatory environment variables '\$NGCP_DB_BACKUP_FINAL_LIST', cannot continue!"
fi

# TT#66556 Check that no mysqldump process is running
check_mysqldump_running() {
  while ps -C mysqldump &>/dev/null ; do
    echo "Warning: mysqldump process(es) already running, this will likely cause"
    echo "         the upgrade process to hang."
    echo "         We recommend that you wait or stop these processes before continuing."

    if [[ "${FORCE_UPGRADE}" = "true" ]] ; then
      echo "Forcing as requested via environment variable FORCE_UPGRADE."
      break
    fi

    echo -n "Should we continue? (yes/no): "
    read -r answer
    case "${answer,,}" in
      yes)
        echo "Continue as requested."
        break
        ;;
      no)
        die "Aborted as requested."
        ;;
      *)
        echo "Please answer 'yes' or 'no'."
        ;;
    esac
    unset answer
  done
}

systemctl start mariadb

mkdir -p "${BACKUP}"

DB_BACKUP_STARTED="${BACKUP}/db_backup_started"
DB_BACKUP_DONE="${BACKUP}/db_backup_done"
DO_DB_BACKUP="${DO_DB_BACKUP:-yes}"

if command -v zstd &>/dev/null ; then
  DB_BACKUP_COMPRESSION_COMMAND="zstd -T0"
  DB_BACKUP="${BACKUP}/db_backup.sql.zst"
elif command -v lz4 &>/dev/null ; then
  DB_BACKUP_COMPRESSION_COMMAND="lz4"
  DB_BACKUP="${BACKUP}/db_backup.sql.lz4"
elif command -v gzip &>/dev/null ; then
  DB_BACKUP_COMPRESSION_COMMAND="gzip -1"
  DB_BACKUP="${BACKUP}/db_backup.sql.gz"
else
  die "Compression commands not found"
fi

# TT#25704, backing up from a common list of DBs to include/exclude
# (e.g. exclude "sipstats" from config), include "mysql" as special one if it's
# not included (as it happens in some versions)
declare -a db_list
re_mysql='\bmysql\b'
if [[ "${NGCP_DB_BACKUP_FINAL_LIST[*]}" =~ ${re_mysql} ]]; then
  db_list=("${NGCP_DB_BACKUP_FINAL_LIST[@]}")
else
  db_list=("mysql" "${NGCP_DB_BACKUP_FINAL_LIST[@]}")
fi
unset re_mysql
echo "List of DBs to backup: " "${db_list[@]}"

# check if there is a completed backup already
if [[ -d "${BACKUP}" ]] ; then
  # the backup is already completed
  if [[ -f "${DB_BACKUP_DONE}" ]] ; then
    echo "DB backup ${BACKUP} is already completed. skipping..."
    DO_DB_BACKUP="no"
  fi
fi

if [[ "${DO_DB_BACKUP}" == "yes" ]] ; then

  check_mysqldump_running

  if [[ -f "${DB_BACKUP}" ]] ; then
    echo "Removing not completed DB backup ${BACKUP}"
    rm -f "${DB_BACKUP}"
  fi

  touch           "${DB_BACKUP}"
  chmod 600       "${DB_BACKUP}"
  chown root:root "${DB_BACKUP}"

  echo "Starting DB backup ${BACKUP}"
  date > "${DB_BACKUP_STARTED}"
  if ! mysqldump --defaults-extra-file="/etc/mysql/sipwise_extra.cnf" --databases --add-drop-database \
       "${db_list[@]}" | ${DB_BACKUP_COMPRESSION_COMMAND} > "${DB_BACKUP}" ; then
    die "Error backing up DBs to ${DB_BACKUP}"
  fi
  date > "${DB_BACKUP_DONE}"
  echo "DB backup is completed"
fi
