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

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <backup-file-or-directory>" >&2
  exit 1
fi

SOURCE="$1"

if [[ -d "${SOURCE}" ]]; then
  if [[ -z "${MEDIA_S3_TARGET:-}" ]]; then
    echo "MEDIA_S3_TARGET is required when restoring from a synced directory backup" >&2
    exit 1
  fi
  aws s3 sync "${SOURCE}" "${MEDIA_S3_TARGET}" ${AWS_EXTRA_ARGS:-}
  echo "Media restore synced to ${MEDIA_S3_TARGET}"
  exit 0
fi

TARGET_DIR="${MEDIA_TARGET_DIR:-./uploads}"
if [[ ! -f "${SOURCE}" ]]; then
  echo "Backup source not found: ${SOURCE}" >&2
  exit 1
fi

mkdir -p "${TARGET_DIR}"
rm -rf "${TARGET_DIR}"/*
tar -xzf "${SOURCE}" -C "${TARGET_DIR}"
echo "Media restore completed into ${TARGET_DIR}"
