#!/bin/sh

set -e

CLUSTER_PORT=5433
EXTERNAL_DATADIR=/srv/postgresql/9.6/protect/data

wait_cluster_online() {
  for i in $(seq 1 10); do
    if pg_isready -p $CLUSTER_PORT -q; then
      return
    fi
    sleep 5
  done
  false
}

# Wait while DB cluster is ready
if ! wait_cluster_online; then
  exit 1
fi

# Remove UniFi Users DBs from new cluster
dropdb -U postgres -p $CLUSTER_PORT --if-exists ulp-go
dropdb -U postgres -p $CLUSTER_PORT --if-exists ulp-go-syslog
dropdb -U postgres -p $CLUSTER_PORT --if-exists uid

# Remove UniFi Talk DBs from new cluster
dropdb -U postgres -p $CLUSTER_PORT --if-exists unifi-talk
dropdb -U postgres -p $CLUSTER_PORT --if-exists unifi-base

# Remove UniFi LED DB from new cluster
dropdb -U postgres -p $CLUSTER_PORT --if-exists unifi-led

# if [ "$(pg_conftool -s 9.6 protect show data_directory)" = $EXTERNAL_DATADIR ]; then
#   # Remove this migration service
#   rm -f /etc/systemd/system/postgresql@9.6-protect.service.d/db-migrate.conf
#   systemctl --system daemon-reload >/dev/null || true
# fi

exit 0
