#!/bin/bash
# BreakPilot Database Backup Script
# Erstellt automatische Backups der PostgreSQL-Datenbank

set -e

# Konfiguration
BACKUP_DIR="${BACKUP_DIR:-./backups}"
CONTAINER_NAME="${CONTAINER_NAME:-breakpilot-pwa-postgres}"
DB_USER="${DB_USER:-breakpilot}"
DB_NAME="${DB_NAME:-breakpilot_db}"
RETENTION_DAYS="${RETENTION_DAYS:-30}"

# Timestamp für Dateinamen
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/breakpilot_${TIMESTAMP}.sql.gz"

# Farben für Output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== BreakPilot Database Backup ===${NC}"
echo "Timestamp: $(date)"
echo ""

# Backup-Verzeichnis erstellen
mkdir -p "$BACKUP_DIR"

# Prüfen ob Container läuft
if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${RED}Error: Container '$CONTAINER_NAME' is not running${NC}"
    exit 1
fi

echo -e "${YELLOW}Creating backup...${NC}"

# Backup erstellen (komprimiert)
docker exec "$CONTAINER_NAME" pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"

# Größe des Backups
BACKUP_SIZE=$(ls -lh "$BACKUP_FILE" | awk '{print $5}')

echo -e "${GREEN}✓ Backup created: $BACKUP_FILE ($BACKUP_SIZE)${NC}"

# Alte Backups löschen
echo ""
echo -e "${YELLOW}Cleaning up old backups (older than $RETENTION_DAYS days)...${NC}"
DELETED_COUNT=$(find "$BACKUP_DIR" -name "breakpilot_*.sql.gz" -mtime +$RETENTION_DAYS -delete -print | wc -l)
echo -e "${GREEN}✓ Deleted $DELETED_COUNT old backup(s)${NC}"

# Statistik
echo ""
echo "=== Backup Statistics ==="
TOTAL_BACKUPS=$(ls -1 "$BACKUP_DIR"/breakpilot_*.sql.gz 2>/dev/null | wc -l)
TOTAL_SIZE=$(du -sh "$BACKUP_DIR" 2>/dev/null | awk '{print $1}')
echo "Total backups: $TOTAL_BACKUPS"
echo "Total size: $TOTAL_SIZE"
echo ""
echo -e "${GREEN}Backup completed successfully!${NC}"
