#!/bin/bash
# b0esche.cloud Backup Script
# Usage: ./backup.sh

set -e

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/opt/backups/b0esche_cloud/$DATE"
RETENTION_DAYS=30

echo "Starting backup for b0esche.cloud - $DATE"

# Create backup directory
mkdir -p "$BACKUP_DIR"

echo "Backing up Go backend PostgreSQL database..."
docker exec go-postgres pg_dump -U go_backend -Fc go_backend > "$BACKUP_DIR/go_backend.sqlc"

echo "Backing up Nextcloud database..."
docker exec nextcloud-db mysqldump -u nextcloud -pSu11Fd02!!! nextcloud > "$BACKUP_DIR/nextcloud.sql"

echo "Backing up Traefik certificates..."
cp -r /opt/traefik/acme "$BACKUP_DIR/"

echo "Backing up configuration files..."
cp /opt/go/.env.production "$BACKUP_DIR/"
cp /opt/go/docker-compose.yml "$BACKUP_DIR/go-docker-compose.yml"
cp /opt/flutter/docker-compose.yml "$BACKUP_DIR/flutter-docker-compose.yml"
cp /opt/flutter/nginx.conf "$BACKUP_DIR/"
cp /opt/traefik/docker-compose.yml "$BACKUP_DIR/traefik-docker-compose.yml"
cp /opt/traefik/traefik.yml "$BACKUP_DIR/"

echo "Backing up Docker volumes..."
docker run --rm -v nextcloud_data_31:/data -v "$BACKUP_DIR":/backup alpine tar czf /backup/nextcloud_data.tar.gz -C /data .

echo "Compressing backup..."
cd /opt/backups/b0esche_cloud
tar czf "$DATE.tar.gz" "$DATE"
rm -rf "$DATE"

echo "Backup completed: /opt/backups/b0esche_cloud/$DATE.tar.gz"

# Clean up old backups
echo "Cleaning up backups older than $RETENTION_DAYS days..."
find /opt/backups/b0esche_cloud -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete

echo "Backup process completed successfully!"

# Show backup size
ls -lh "/opt/backups/b0esche_cloud/$DATE.tar.gz"