#!/bin/bash

# This file is a simple backup method intended to backup relations in
# a database and maintain another object which is always the latest.
# If this is run by some kind of cron, consider adding lifecycle management to $s3_destination.
#
# Usage:   ./backup-relations $s3_destination $schema $table1 [$table2...]
# Example: ./backup-relations s3://d8a-web-backup/postgres/tmi/relations justintv_prod schema_migrations

set -e
set -u

s3_destination=${1}; shift
schema=${1}; shift

if [ "$#" -eq 0 ]; then
  echo "No relations given. Please specify at least one relation to backup."
  exit 1
fi

for relation in "$@"; do
  timestamp=$(date --utc +'%Y%m%dT%H%M')
  pattern="relation-${schema}.${relation}"
  base_name="${pattern}-${timestamp}.sql"
  file_name=/tmp/"${base_name}"
  pg_dump --no-owner --table "${relation}" --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}.${relation} backup ${base_name} available at ${s3_destination}/${base_name}.bz2 and ${s3_destination}/${pattern}-latest.bz2."
done
