#!/bin/bash

POSTGRES_VERSION=14
EXTERNAL_MINIMUM_SPACE=67108864 # 64 GB

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 ]
}

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
