#!/bin/bash
# mr5.1: check DB size (acc and cdr) before upgrade in each nodes

set -e

# shellcheck disable=SC1091
. /etc/default/ngcp-roles
# shellcheck disable=SC1091
. /etc/default/ngcp-db

MAX_MYSQL_SIZE=81920   # MB (80G)
MAX_MYSQL_ACC=50000    # rows
MAX_MYSQL_CDR=5000000  # rows
opts="--defaults-extra-file=/etc/mysql/sipwise_extra.cnf -h${PAIR_DBHOST} -P${PAIR_DBPORT} -Bs"

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

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

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

# Preliminary checks

# shellcheck disable=SC2086
if ! timeout 2 mysql ${opts} -e "SELECT NOW()" >/dev/null 2>&1 ; then
  die "Is MariaDB up? Failed to connect!"
fi

# Check mysql size
mysql_size=$(du -ms /var/lib/mysql/ | awk '{print $1}' 2>/dev/null)

if [ -z "${mysql_size}" ] ; then
  die "Failed to get MariaDB size. Check if /var/lib/mysql exist!"
fi

if [ "${mysql_size}" -ge ${MAX_MYSQL_SIZE} ] ; then
  echo "MariaDB is too big for an upgrade, please reduce the size below ${MAX_MYSQL_SIZE}MB before upgrade: ${mysql_size}MB / ${MAX_MYSQL_SIZE}MB"
  request_confirmation
fi


# check ACC table size

# shellcheck disable=SC2086
acc_size=$(timeout 2 mysql ${opts} -e "SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'kamailio' AND TABLE_NAME = 'acc';" 2>/dev/null) || true

if [ -z "${acc_size}" ] ; then
  die "Failed to get records count in kamailio.acc"
fi

if [ "${acc_size}" -ge ${MAX_MYSQL_ACC} ] ; then
  echo "kamailio.acc is too big for an upgrade, please reduce the size below ${MAX_MYSQL_ACC} rows before upgrade: ${acc_size} / ${MAX_MYSQL_ACC} rows"
  request_confirmation
fi


# check CDR table SIZE

# shellcheck disable=SC2086
cdr_size=$(timeout 2 mysql ${opts} -e "SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'accounting' AND TABLE_NAME = 'cdr';" 2>/dev/null) || true

if [ -z "${cdr_size}" ] ; then
  die "Failed to get records count in cdr"
fi

if [ "${cdr_size}" -ge ${MAX_MYSQL_CDR} ] ; then
  echo "accounting.cdr is too big for an upgrade, please reduce the size below ${MAX_MYSQL_CDR} rows before upgrade: ${cdr_size} / ${MAX_MYSQL_CDR} rows"
  request_confirmation
fi
