#!/bin/sh

set -e

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

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

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

# Keep database in build-in SSD, no need to cleanup
if is_link $INTERNAL_DB_ROOT || mountpoint -q /ssd1; then
  exit 0
fi

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

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

  # cleanup workaround for conf directoy was missing
  rm -rf /tmp/.protect_conf_workaround_* || true
fi
