#!/bin/bash
# TT#108302 "No space left" in root partition during upgrades

set -e
set -u

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 the upgrade 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
}

# paths to check
paths_to_check=()
paths_to_check+=("/ngcp-data")

# limit of 3GB
free_space_limit=$((3 * 1024 * 1024))

echo "INFO: Check space of filesystems/paths:"
for path in "${paths_to_check[@]}"; do
  echo " - ${path}"
  df -h "${path}" | sed 's/^/  /'
  echo

  avail_size=$(df --output=avail "${path}" | sed '1d')
  if [[ ${avail_size} -lt ${free_space_limit} ]] ; then
    echo "Warning: Free space of filesystem/path '${path}' is ${avail_size},"
    echo "         less than the considered-safe limit of ${free_space_limit}"
    echo "         ($((free_space_limit / 1024)) MB)."
    echo
    echo "         Please consider freeing space from this path by checking"
    echo "         for files that can be removed (e.g. in cache or log dirs)"
    echo "         before continuing."
    echo
    request_confirmation
    echo
  fi
done

# paths to check
paths_to_check=()
paths_to_check+=("/ngcp-fallback")

# limit of 5GB
free_space_limit=$((5 * 1024 * 1024))

echo "INFO: Check size of filesystems/paths:"
for path in "${paths_to_check[@]}"; do
  echo " - ${path}"
  df -h "${path}" | sed 's/^/  /'
  echo

  avail_size=$(df --output=size "${path}" | sed '1d')
  if [[ ${avail_size} -lt ${free_space_limit} ]] ; then
    echo "Warning: The size of filesystem/path '${path}' is ${avail_size},"
    echo "         less than the considered-safe limit of ${free_space_limit}"
    echo "         ($((free_space_limit / 1024)) MB)."
    echo
    echo "         Please consider increasing size from this path by checking"
    echo
    request_confirmation
    echo
  fi
done

unset avail_size
unset free_space_limit
unset paths_to_check
echo "OK, finished successfully"
