#!/usr/bin/env bash
set -euo pipefail

BACKUP_ROOT="${BACKUP_ROOT:-./backups}"
OFFSITE_TARGET="${OFFSITE_TARGET:-}"
AWS_EXTRA_ARGS="${AWS_EXTRA_ARGS:-}"
RSYNC_EXTRA_ARGS="${RSYNC_EXTRA_ARGS:-}"

if [[ -z "${OFFSITE_TARGET}" ]]; then
  echo "OFFSITE_TARGET is required (rsync path or s3:// bucket)" >&2
  exit 1
fi

if [[ ! -d "${BACKUP_ROOT}" ]]; then
  echo "Backup root not found: ${BACKUP_ROOT}" >&2
  exit 1
fi

if [[ "${OFFSITE_TARGET}" == s3://* ]]; then
  aws s3 sync "${BACKUP_ROOT}" "${OFFSITE_TARGET}" ${AWS_EXTRA_ARGS}
  echo "Backups synced to ${OFFSITE_TARGET}"
  exit 0
fi

rsync -av --delete ${RSYNC_EXTRA_ARGS} "${BACKUP_ROOT}/" "${OFFSITE_TARGET}/"
echo "Backups synced to ${OFFSITE_TARGET}"
