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

BACKUP_ROOT="${BACKUP_ROOT:-./backups}"
POSTGRES_RETENTION_DAYS="${POSTGRES_RETENTION_DAYS:-14}"
MEDIA_RETENTION_DAYS="${MEDIA_RETENTION_DAYS:-14}"
DRY_RUN="${DRY_RUN:-false}"

prune() {
  local target_dir="$1"
  local pattern="$2"
  local retention_days="$3"

  if [[ ! -d "${target_dir}" ]]; then
    return 0
  fi

  if [[ "${DRY_RUN}" == "true" ]]; then
    find "${target_dir}" -type f -name "${pattern}" -mtime +"${retention_days}" -print
    return 0
  fi

  find "${target_dir}" -type f -name "${pattern}" -mtime +"${retention_days}" -delete
}

prune_dirs() {
  local target_dir="$1"
  local pattern="$2"
  local retention_days="$3"

  if [[ ! -d "${target_dir}" ]]; then
    return 0
  fi

  if [[ "${DRY_RUN}" == "true" ]]; then
    find "${target_dir}" -maxdepth 1 -mindepth 1 -type d -name "${pattern}" -mtime +"${retention_days}" -print
    return 0
  fi

  find "${target_dir}" -maxdepth 1 -mindepth 1 -type d -name "${pattern}" -mtime +"${retention_days}" -exec rm -rf {} +
}

prune "${BACKUP_ROOT}/postgres" 'postgres-*.dump' "${POSTGRES_RETENTION_DAYS}"
prune "${BACKUP_ROOT}/media" 'media-*.tar.gz' "${MEDIA_RETENTION_DAYS}"
prune_dirs "${BACKUP_ROOT}/media" 'media-*' "${MEDIA_RETENTION_DAYS}"

echo "Backup pruning completed under ${BACKUP_ROOT}"
