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

BACKUP_DIR="${BACKUP_DIR:-./backups/media}"
RETENTION_DAYS="${RETENTION_DAYS:-14}"
TIMESTAMP="$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p "${BACKUP_DIR}"

if [[ -n "${MEDIA_S3_SOURCE:-}" ]]; then
  TARGET_DIR="${BACKUP_DIR}/media-${TIMESTAMP}"
  mkdir -p "${TARGET_DIR}"
  aws s3 sync "${MEDIA_S3_SOURCE}" "${TARGET_DIR}" ${AWS_EXTRA_ARGS:-}
  ln -sfn "$(basename "${TARGET_DIR}")" "${BACKUP_DIR}/latest"
  find "${BACKUP_DIR}" -maxdepth 1 -mindepth 1 -type d -name 'media-*' -mtime +"${RETENTION_DAYS}" -exec rm -rf {} +
  echo "Media backup synced from ${MEDIA_S3_SOURCE} to ${TARGET_DIR}"
  exit 0
fi

SOURCE_DIR="${MEDIA_SOURCE_DIR:-./uploads}"
FILE_PATH="${BACKUP_DIR}/media-${TIMESTAMP}.tar.gz"

if [[ ! -d "${SOURCE_DIR}" ]]; then
  echo "Set MEDIA_SOURCE_DIR or MEDIA_S3_SOURCE before running this script" >&2
  exit 1
fi

tar -czf "${FILE_PATH}" -C "${SOURCE_DIR}" .
ln -sfn "$(basename "${FILE_PATH}")" "${BACKUP_DIR}/latest.tar.gz"
find "${BACKUP_DIR}" -type f -name 'media-*.tar.gz' -mtime +"${RETENTION_DAYS}" -delete

echo "Media backup written to ${FILE_PATH}"
