#!/bin/bash

POSTGRES_VERSION=14
EXTERNAL_MINIMUM_SPACE=54683238 # kibibyte = 52.15 GiB = 56 GB

INTERNAL_DB_ROOT=/data/postgresql
INTERNAL_ROOT=/data
RECOVERED_DB_FLAG=/srv/unifi-protect/data/.db-recovered

is_link() {
  [ -L "$1" ] && [ -e "$1" ] && return
  false
}

get_disk_space() {
  df "$1" -k | tail -n 1 | awk '{printf $2}'
}

has_external_storage() {
  (mountpoint -q /srv || is_link /srv) && [ $(get_disk_space /srv) -ge $EXTERNAL_MINIMUM_SPACE ]
}

has_internal_ssd() {
  is_link $INTERNAL_DB_ROOT || is_link $INTERNAL_ROOT || mountpoint -q /ssd1 || [ -d /ssd1 ]
}

remove_legacy_db_directory() {
  # As we only remove DB data from the external storage after we have already
  # restored all DB data from the dump file into the internal database on the SSD.
  if ! has_external_storage || ! has_internal_ssd; then
    return
  fi
  if [ -f $RECOVERED_DB_FLAG ] && [ -d /srv/postgresql/$POSTGRES_VERSION/protect ]; then
    echo "DB recovered, removing legacy directory"
    rm -rf /srv/postgresql/$POSTGRES_VERSION/protect || true
  fi
}

if has_external_storage; then
  PROTECT_MOUNT=/srv
else
  PROTECT_MOUNT=/data
fi

CORRUPTED_DB_FLAG=$PROTECT_MOUNT/unifi-protect/data/.corrupted-db
if [ -e $CORRUPTED_DB_FLAG ]; then
  unset DIR
  source "/etc/default/postgresql/$POSTGRES_VERSION-protect"
  if [[ ! -z "$DIR" && ! -z "$PG_VERSION" ]]; then
    # We cannot stop postgres service and remove data directory here, since it hangs waiting for Protect service to stop
    # "postgresql-cluster-14-protect-upgrade.service" looks for ".configured" and reinstalls the DB, if this file is not found
    echo "Found ${CORRUPTED_DB_FLAG}, removing ${DIR}/.configured to trigger db re-init"
    rm -f "${DIR}"/.configured
  fi
fi

remove_legacy_db_directory || true
