#!/bin/sh

set -eu

backup_dir=${BACKUP_DIR:-/backups}

run_backup() {
  umask 077
  mkdir -p "$backup_dir"

  timestamp=$(date +%Y%m%d-%H%M%S)
  target="$backup_dir/cents-$timestamp.dump"
  temporary="$target.tmp"
  trap 'rm -f "$temporary"' EXIT INT TERM

  pg_dump --format=custom --file="$temporary"
  pg_restore --list "$temporary" >/dev/null
  mv "$temporary" "$target"
  trap - EXIT INT TERM

  find "$backup_dir" -maxdepth 1 -type f -name 'cents-*.dump' -mtime +29 -delete
  printf 'Backup created: %s\n' "$target"
}

case "${1:-cron}" in
  run)
    run_backup
    ;;
  cron)
    cron_dir=/tmp/cents-crontabs
    mkdir -p "$cron_dir"
    printf '%s\n' \
      '0 3 * * * /usr/local/bin/cents-backup run >> /proc/1/fd/1 2>> /proc/1/fd/2' \
      > "$cron_dir/$(id -u)"
    printf 'Backup scheduler started: daily at 03:00 %s, retaining 30 days\n' "${TZ:-local time}"
    exec crond -f -l 2 -c "$cron_dir"
    ;;
  *)
    printf 'Unknown command: %s\n' "$1" >&2
    exit 2
    ;;
esac
