#!/bin/sh
set -eu

write_sha256() {
  file=$1
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" > "$file.sha256"
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" > "$file.sha256"
  else
    echo "[WARN] Weder sha256sum noch shasum verfügbar; keine Prüfsummendatei erzeugt." >&2
  fi
}

target="${1:-./vendoo-docker-backup-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "$target"
absolute_target="$(cd "$target" && pwd)"

docker compose config -q
restart=0
if docker compose ps --status running --services | grep -qx vendoo; then
  restart=1
  docker compose stop vendoo
fi
cleanup() {
  code=$?
  if [ "$restart" -eq 1 ]; then docker compose up -d vendoo >/dev/null; fi
  exit "$code"
}
trap cleanup EXIT INT TERM

docker compose run --rm --no-deps --user 0:0 \
  -v "$absolute_target":/backup \
  --entrypoint sh vendoo -eu -c \
  'cd /app/data && tar czf /backup/vendoo-data.tar.gz db uploads backups operations logs config modules'
write_sha256 "$target/vendoo-data.tar.gz"

trap - EXIT INT TERM
if [ "$restart" -eq 1 ]; then docker compose up -d vendoo >/dev/null; fi
echo "Backup erstellt: $target/vendoo-data.tar.gz"
[ "$restart" -eq 0 ] || echo "Vendoo wurde wieder gestartet."
