#!/bin/sh

PGDIR=`pwd`
PGBIN=${PGDIR}/bin

ACTDATA=${PGDIR}/actdata
SBYDATA=${PGDIR}/sbydata
ARCHDIR=${PGDIR}/archive

CANCELT=${PGDIR}/cancel.trigger
FINISHT=${PGDIR}/finish.trigger
ARCHCMD="cp %p ${ARCHDIR}/%f"
RSTRCMD="${PGBIN}/pg_standby -r 1 -t ${CANCELT} ${ARCHDIR} %f %p"

ACTHOST=localhost
ACTPORT=5432
SBYPORT=5433
#ACTUSER=postgres

if [ ! -f ${PGBIN}/pg_config ]; then
    echo "Change the current directory to postgres installation dir"
    exit 1
fi

if [ ! -f ${PGBIN}/pg_standby ]; then
    echo "Install pg_standby (replication needs pg_standby)"
    exit 1
fi

# clear the old data
rm -rf ${ACTDATA} ${SBYDATA} ${ARCHDIR} ${CANCELT} ${FINISHT}
mkdir ${ARCHDIR}

# set up the primary
${PGBIN}/initdb -D ${ACTDATA} --locale=C --encoding=UTF8
echo "host all all 0.0.0.0/0 trust"    >> ${ACTDATA}/pg_hba.conf
echo "listen_addresses = '*'"          >> ${ACTDATA}/postgresql.conf
echo "port = ${ACTPORT}"               >> ${ACTDATA}/postgresql.conf
echo "archive_mode = unsent"           >> ${ACTDATA}/postgresql.conf
echo "archive_command = '${ARCHCMD}'"  >> ${ACTDATA}/postgresql.conf
echo "log_line_prefix = 'Primary %p '" >> ${ACTDATA}/postgresql.conf

# get online-backup
${PGBIN}/pg_ctl -D ${ACTDATA} start
sleep 5
${PGBIN}/psql template1 -c "CHECKPOINT"
${PGBIN}/psql template1 -c "SELECT pg_start_backup('replication')"
cp -rf ${ACTDATA} ${SBYDATA}
${PGBIN}/psql template1 -c "SELECT pg_stop_backup()"
rm -rf ${SBYDATA}/postmaster.pid ${SBYDATA}/pg_xlog
mkdir ${SBYDATA}/pg_xlog ${SBYDATA}/pg_xlog/archive_status

# set up the standby
echo "port = ${SBYPORT}"               >> ${SBYDATA}/postgresql.conf
echo "log_line_prefix = 'Standby %p '" >> ${SBYDATA}/postgresql.conf
touch ${SBYDATA}/recovery.conf
echo "restore_command          = '${RSTRCMD}'" >> ${SBYDATA}/recovery.conf
echo "recovery_trigger_file    = '${FINISHT}'" >> ${SBYDATA}/recovery.conf
echo "enable_replication       = 'true'      " >> ${SBYDATA}/recovery.conf
echo "replication_primary_host = '${ACTHOST}'" >> ${SBYDATA}/recovery.conf
echo "replication_primary_port = '${ACTPORT}'" >> ${SBYDATA}/recovery.conf
# ${PGBIN}/pg_ctl -D ${SBYDATA} start
${PGBIN}/postmaster -D ${SBYDATA} -d5
