#!/bin/sh

set -e

PG_VERSION=9.6
PG_CLUSTER_NAME=protect

INTERNAL_DB_ROOT=/data/postgresql
INTERNAL_DB_DATADIR="$INTERNAL_DB_ROOT/$PG_VERSION/$PG_CLUSTER_NAME/data"
INTERNAL_DB_CONFDIR="$INTERNAL_DB_ROOT/$PG_VERSION/$PG_CLUSTER_NAME/conf"

EXTERNAL_DB_ROOT=/srv/postgresql
EXTERNAL_DB_DATADIR="$EXTERNAL_DB_ROOT/$PG_VERSION/$PG_CLUSTER_NAME/data"
EXTERNAL_DB_CONFDIR="$EXTERNAL_DB_ROOT/$PG_VERSION/$PG_CLUSTER_NAME/conf"

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

show_data_dir() {
  local data_dir="$(pg_conftool -s 9.6 protect get data_directory 2>/dev/null)"
  echo "data_dir: $data_dir"
}

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

if mountpoint -q /srv || is_link /srv; then
  show_data_dir
  pg_conftool $PG_VERSION $PG_CLUSTER_NAME set data_directory $EXTERNAL_DB_DATADIR || true
  show_data_dir
fi

if [ -e /etc/postgresql/$PG_VERSION/$PG_CLUSTER_NAME/postgresql.conf ]; then
  # For ubios migrate to debbox
  pg_conftool $PG_VERSION $PG_CLUSTER_NAME set ssl "off" || true
  pg_conftool $PG_VERSION $PG_CLUSTER_NAME remove ssl || true
  pg_conftool $PG_VERSION $PG_CLUSTER_NAME remove ssl_cert_file || true
  pg_conftool $PG_VERSION $PG_CLUSTER_NAME remove ssl_key_file || true
fi

exit 0
