#!/bin/bash
# TaskPlaner Data Backup Script
# Creates a timestamped backup of the Docker volume

set -e

# Configuration (override via environment)
BACKUP_DIR="${BACKUP_DIR:-./backups}"
VOLUME_NAME="${VOLUME_NAME:-taskplaner_taskplaner_data}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/taskplaner_backup_${TIMESTAMP}.tar.gz"

# Create backup directory if needed
mkdir -p "$BACKUP_DIR"

echo "========================================="
echo "TaskPlaner Backup"
echo "========================================="
echo "Volume: $VOLUME_NAME"
echo "Output: $BACKUP_FILE"
echo ""

# Check if volume exists
if ! docker volume inspect "$VOLUME_NAME" > /dev/null 2>&1; then
  echo "Error: Volume '$VOLUME_NAME' not found"
  echo ""
  echo "Available volumes:"
  docker volume ls --format '  - {{.Name}}' | grep -i taskplaner || echo "  (none with 'taskplaner' in name)"
  echo ""
  echo "Tip: Set VOLUME_NAME environment variable to use a different volume"
  exit 1
fi

# Create backup using temporary Alpine container
echo "Creating backup..."
docker run --rm \
  -v "${VOLUME_NAME}:/data:ro" \
  -v "$(cd "$BACKUP_DIR" && pwd):/backup" \
  alpine:latest \
  tar czf "/backup/taskplaner_backup_${TIMESTAMP}.tar.gz" -C /data .

echo ""
echo "Backup complete!"
echo "File: $BACKUP_FILE"
echo "Size: $(du -h "$BACKUP_FILE" | cut -f1)"
echo ""
echo "To restore: docker run --rm -v ${VOLUME_NAME}:/data -v \$(pwd)/${BACKUP_DIR}:/backup alpine tar xzf /backup/taskplaner_backup_${TIMESTAMP}.tar.gz -C /data"
