#!/bin/bash

# This script handles half of the rotation of the development
# databases from the lastest backup in barman. The point of this
# script is that we take the postgresql out of rotation and
# sync to the latest backup.

# Call with the version number of postgres so we can determine full data dir.
# ./devdb-teardown cluster version master_fqdn
# Eg, ./setup-postgres-dir.sh 9.5 us-west-2 s3://science-inputs/path/to/wal UTCTIMESTAMP base_0000000 /output/path

source /etc/zenyatta/zenyatta.env
bucket=${3}
recover_time=${4}
backup=${5}

version=${1}
host=$(hostname)
hostname=$(hostname --fqdn)
master_db=${hostname}

export AWS_REGION=${2}
export WALE_S3_PREFIX="${bucket}"

dest=${6}

sudo rm -rf "${dest}"
mkdir -p "${dest}"
cp /mnt/postgres/* "${dest}"

echo ${version} > ${dest}/PG_VERSION

echo "wal-e backup-fetch ${dest} ${backup}"
wal-e --aws-instance-profile backup-fetch "${dest}" "${backup}"
chmod 0700 "${dest}"
echo "Starting recovery to ${latest} at $(date +'%F %T %Z')."
echo "bucket: ${bucket}"
aws s3 cp --recursive "${bucket}/history/" "${dest}/pg_xlog/"
echo "Recover to ${latest} done at $(date +'%F %T %Z')."

recovery=${dest}/recovery.conf

echo 'recovery_target_action = pause' > ${recovery}
echo restore_command = \'WALE_S3_PREFIX="${bucket}" AWS_REGION=${2} wal-e --aws-instance-profile wal-fetch "%f" "%p"\' >> ${recovery}
echo recovery_target_time = ${recover_time} >> ${recovery}

echo "done making"

