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

backup_dir=/chucun/wangzhan-production/backups/gitea
container_dump=/data/gitea-backup.zip
host_dump=/data/gitea/data/gitea-backup.zip
stamp=$(date -u +%Y%m%dT%H%M%SZ)
target="$backup_dir/gitea-$stamp.zip"

install -d -o ubuntu -g ubuntu -m 0770 "$backup_dir"
if [ -e "$host_dump" ]; then
  unlink "$host_dump"
fi

docker exec -u git gitea sh -c \
  'mkdir -p /tmp/gitea-dump && find /tmp/gitea-dump -mindepth 1 -delete'
docker exec -u git gitea gitea dump \
  --config /data/gitea/conf/app.ini \
  --file "$container_dump" \
  --tempdir /tmp/gitea-dump

cp "$host_dump" "$target"
sha256sum "$target" > "$target.sha256"
unlink "$host_dump"
printf 'Gitea backup created: %s\n' "$target"
