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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/.env"

if [ ! -d "$BACKUP_DIR" ]; then
  echo "Error: BACKUP_DIR does not exist: $BACKUP_DIR" >&2
  exit 1
fi
if ! docker info > /dev/null 2>&1; then
  echo "Error: Docker is not accessible" >&2
  exit 1
fi

cleanup() {
  echo "Restarting all services..."
  docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d
}
trap cleanup EXIT

echo "Stopping all services..."
docker compose -f "$SCRIPT_DIR/docker-compose.yml" down

echo "Starting database only..."
docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d db
sleep 5

echo "Running gitea dump..."
docker run --rm \
  --network gitea_gitea \
  -e USER_UID=1001 \
  -e USER_GID=1001 \
  -v "${GITEA_DATA}:/data" \
  -v "${BACKUP_DIR}:/backup" \
  docker.gitea.com/gitea:1.25.3 \
  /bin/sh -c "chown 1001:1001 /tmp && su-exec 1001:1001 /bin/sh -c 'cd /tmp && gitea dump -c /data/gitea/conf/app.ini --tempdir /tmp' > /backup/backup.log 2>&1 && cp /tmp/gitea-dump-*.zip /backup/"

echo "Backup completed successfully"
