#! /usr/bin/env bash

if [ "${POSTGRES_SLAVE_INDEX}" == "" ]
then
  echo "No POSTGRES_SLAVE_INDEX defined. Exiting."
  exit 0
fi

set_var_value()
{
  var_name="${1}"_"${POSTGRES_SLAVE_INDEX}"
  export "${1}"="${!var_name}"
}

set_var_value POSTGRES_SLAVE_ENABLED

if [ "${POSTGRES_SLAVE_ENABLED}" -ne 1 ]
then
  echo "Slave is disabled. Exiting."
  exit 0
fi

set_var_value POSTGRES_SLAVE_REP_HOST
set_var_value POSTGRES_SLAVE_REP_USER
set_var_value POSTGRES_SLAVE_REP_PASSWORD
set_var_value POSTGRES_SLAVE_REP_PORT

. /common.sh

replace_files

replace_var /var/lib/postgresql/data/recovery.conf POSTGRES_SLAVE_REP_HOST
replace_var /var/lib/postgresql/data/recovery.conf POSTGRES_SLAVE_REP_USER
replace_var /var/lib/postgresql/data/recovery.conf POSTGRES_SLAVE_REP_PASSWORD
replace_var /var/lib/postgresql/data/recovery.conf POSTGRES_SLAVE_REP_PORT

rm -rf /tmp/*

mv /var/lib/postgresql/data/*.conf /tmp

rm -rf /var/lib/postgresql/data/*

PGPASSWORD="${POSTGRES_SLAVE_REP_PASSWORD}" pg_basebackup -h "${POSTGRES_SLAVE_REP_HOST}" -p "${POSTGRES_SLAVE_REP_PORT}" -D /var/lib/postgresql/data -U "${POSTGRES_SLAVE_REP_USER}" -v

mv /tmp/*.conf /var/lib/postgresql/data/

docker-entrypoint.sh postgres
