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

container="${GITEA_CONTAINER:-gitea-npm-registry}"
backup_dir="${GITEA_BACKUP_DIR:-/opt/bytelyst/backups/gitea}"
retention_days="${GITEA_BACKUP_RETENTION_DAYS:-14}"
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
name="gitea-dump-${timestamp}.zip"
container_tmp="/tmp/${name}"
host_path="${backup_dir}/${name}"

mkdir -p "$backup_dir"

docker exec --user git "$container" rm -f "$container_tmp" >/dev/null 2>&1 || true
docker exec --user git "$container" gitea dump --quiet --skip-log --file "$container_tmp"
docker cp "${container}:${container_tmp}" "$host_path"
docker exec --user git "$container" rm -f "$container_tmp" >/dev/null 2>&1 || true

chmod 600 "$host_path"
find "$backup_dir" -type f -name 'gitea-dump-*.zip' -mtime +"$retention_days" -delete

printf 'created %s\n' "$host_path"
