#!/bin/bash

# This file is a simple backup method intended to track the schema of
# a database and maintain another objects which tracks the latest.
# If this is run by some kind of cron, consider adding lifecycle management to $s3_destination.
#
# Usage:   ./backup-schema $s3_destination $schema
# Example: ./backup-schema s3://d8a-web-backup/postgres justintv_prod

set -e
set -u

s3_destination=${1}
schema=${2}

timestamp=$(date --utc +'%Y%m%dT%H%M')
pattern="schema-${schema}"
base_name="${pattern}-${timestamp}.sql"
file_name="/tmp/${base_name}"
pg_dump --schema-only --no-owner --file ${file_name} ${schema}
bzip2 -q ${file_name}
aws s3 cp "${file_name}.bz2" "${s3_destination}/${base_name}.bz2"
aws s3 cp "${file_name}.bz2" "${s3_destination}/${pattern}-latest.bz2"
echo "Latest ${schema} backup ${base_name} available at ${s3_destination}/${base_name}.bz2 and ${s3_destination}/${pattern}-latest.sql.bz2"
