#!/bin/bash
# Full Server Backup Script for V2-Docker
# Creates comprehensive backup including configs, database, volumes, and git status

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
BACKUP_BASE_DIR="/opt/v2-Docker/server-backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="$BACKUP_BASE_DIR/server_backup_$TIMESTAMP"
PROJECT_ROOT="/opt/v2-Docker"

# GitHub configuration
GITHUB_REMOTE="backup"
GITHUB_BRANCH="main"
GIT_PATH="/home/root/.local/bin"

echo -e "${GREEN}Starting V2-Docker Full Server Backup...${NC}"
echo "Backup directory: $BACKUP_DIR"

# Create backup directory structure
mkdir -p "$BACKUP_DIR"/{configs,volumes}

# 1. Backup configuration files
echo -e "${YELLOW}Backing up configuration files...${NC}"
cp "$PROJECT_ROOT/v2/docker-compose.yaml" "$BACKUP_DIR/configs/" 2>/dev/null || echo "docker-compose.yaml not found"
cp "$PROJECT_ROOT/v2/.env" "$BACKUP_DIR/configs/" 2>/dev/null || echo ".env not found"
cp "$PROJECT_ROOT/v2_nginx/nginx.conf" "$BACKUP_DIR/configs/" 2>/dev/null || echo "nginx.conf not found"

# Backup SSL certificates
if [ -d "$PROJECT_ROOT/v2_nginx/ssl" ]; then
    mkdir -p "$BACKUP_DIR/configs/ssl"
    cp -r "$PROJECT_ROOT/v2_nginx/ssl/"* "$BACKUP_DIR/configs/ssl/" 2>/dev/null || echo "SSL files not found"
fi

# 2. Capture Git status and recent commits
echo -e "${YELLOW}Capturing Git information...${NC}"
cd "$PROJECT_ROOT"
git status > "$BACKUP_DIR/git_status.txt" 2>&1
git log --oneline -50 > "$BACKUP_DIR/git_recent_commits.txt" 2>&1

# 3. Capture Docker status
echo -e "${YELLOW}Capturing Docker status...${NC}"
docker ps -a > "$BACKUP_DIR/docker_containers.txt" 2>&1
cd "$PROJECT_ROOT/v2" && docker-compose ps > "$BACKUP_DIR/docker_compose_status.txt" 2>&1 && cd "$PROJECT_ROOT"

# 4. Backup PostgreSQL database
echo -e "${YELLOW}Backing up PostgreSQL database...${NC}"
DB_CONTAINER="db"  # Korrigierter Container-Name
DB_NAME="meinedatenbank"  # Korrigierter DB-Name
DB_USER="adminuser"  # Korrigierter User

# Get DB password from .env or environment
if [ -f "$PROJECT_ROOT/v2/.env" ]; then
    source "$PROJECT_ROOT/v2/.env"
fi
DB_PASS="${POSTGRES_PASSWORD:-supergeheimespasswort}"

# Create database dump
docker exec "$DB_CONTAINER" pg_dump -U "$DB_USER" -d "$DB_NAME" | gzip > "$BACKUP_DIR/database_backup.sql.gz"

# 5. Backup Docker volumes
echo -e "${YELLOW}Backing up Docker volumes...${NC}"
# PostgreSQL data volume
docker run --rm -v postgres_data:/data -v "$BACKUP_DIR/volumes":/backup alpine tar czf /backup/postgres_data.tar.gz -C /data .

# Create backup info file
cat > "$BACKUP_DIR/backup_info.txt" << EOF
V2-Docker Server Backup
Created: $(date)
Timestamp: $TIMESTAMP
Type: Full Server Backup
Contents:
- Configuration files (docker-compose, nginx, SSL)
- PostgreSQL database dump
- Docker volumes
- Git status and history
- Docker container status
EOF

# Calculate backup size
BACKUP_SIZE=$(du -sh "$BACKUP_DIR" | cut -f1)
echo -e "${GREEN}Backup created successfully!${NC}"
echo "Size: $BACKUP_SIZE"

# Push to GitHub if requested (default: yes)
if [ "${SKIP_GITHUB:-no}" != "yes" ]; then
    echo -e "${YELLOW}Pushing backup to GitHub...${NC}"
    
    # Create tar archive for GitHub
    cd "$BACKUP_BASE_DIR"
    TAR_FILE="server_backup_$TIMESTAMP.tar.gz"
    tar czf "$TAR_FILE" "server_backup_$TIMESTAMP"
    
    # Push to GitHub
    cd "$PROJECT_ROOT"
    PATH="$GIT_PATH:$PATH" git pull "$GITHUB_REMOTE" "$GITHUB_BRANCH" --rebase 2>/dev/null || true
    PATH="$GIT_PATH:$PATH" git add "server-backups/$TAR_FILE"
    PATH="$GIT_PATH:$PATH" git commit -m "Server backup $TIMESTAMP - Full system backup before changes"
    PATH="$GIT_PATH:$PATH" git push "$GITHUB_REMOTE" "$GITHUB_BRANCH"
    
    echo -e "${GREEN}Backup pushed to GitHub successfully!${NC}"
    
    # Keep local copy for manual backups (for quick rollback)
    # Automated backups will delete this later
    echo -e "${YELLOW}Local backup kept at: $BACKUP_DIR${NC}"
else
    echo -e "${YELLOW}Skipped GitHub push (SKIP_GITHUB=yes)${NC}"
fi

echo "Backup file: $BACKUP_DIR"
echo -e "${GREEN}Backup completed successfully!${NC}"