#!/bin/bash
set -e

until pg_isready -h db-master -U e-ticket; do
  echo "Waiting for master..."
  sleep 2
done

echo "db-master:5432:replication:replicator:e-ticket" > /tmp/.pgpass
chown postgres:postgres /tmp/.pgpass
chmod 600 /tmp/.pgpass

rm -rf "$PGDATA"/*
chown postgres:postgres "$PGDATA"
chmod 700 "$PGDATA"
su-exec postgres env PGPASSFILE=/tmp/.pgpass pg_basebackup -h db-master -D "$PGDATA" -U replicator -Fp -Xs -P -R

echo "hot_standby = on" >> "$PGDATA/postgresql.conf"

exec su-exec postgres "$@"
