#!/bin/bash

# env-backup-integration.sh - Integration script for adding .env backup to existing backup system
# Author: Shell Repository
# Description: Add .env backup functionality to existing backup scripts

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${BLUE}=== Environment Files Backup Integration ===${NC}"

# Function to add .env backup to a script
integrate_env_backup() {
    local target_script="$1"
    local integration_point="$2"
    
    if [ ! -f "$target_script" ]; then
        echo -e "${YELLOW}Target script not found: $target_script${NC}"
        return 1
    fi
    
    # Check if already integrated
    if grep -q "backup-env-files.sh" "$target_script"; then
        echo -e "${GREEN}✓ Already integrated with $target_script${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}Integrating with $target_script...${NC}"
    
    # Create backup of original script
    cp "$target_script" "$target_script.backup"
    
    # Integration code
    local integration_code="
# === Environment Files Backup Integration ===
echo -e \"\${YELLOW}Backing up environment files...\${NC}\"
if [ -f \"\$SCRIPT_DIR/backup-env-files.sh\" ]; then
    if \"\$SCRIPT_DIR/backup-env-files.sh\"; then
        echo -e \"\${GREEN}✓ Environment files backed up successfully\${NC}\"
    else
        echo -e \"\${YELLOW}Warning: Environment files backup had issues\${NC}\"
    fi
else
    echo -e \"\${YELLOW}Warning: backup-env-files.sh not found\${NC}\"
fi

# Validate the backup
if [ -f \"\$SCRIPT_DIR/validate-env-backups.sh\" ]; then
    if \"\$SCRIPT_DIR/validate-env-backups.sh\" --summary-only; then
        echo -e \"\${GREEN}✓ Environment backup validation passed\${NC}\"
    else
        echo -e \"\${YELLOW}Warning: Environment backup validation failed\${NC}\"
    fi
fi
echo \"\"
# === End Environment Files Backup Integration ===
"
    
    # Add integration based on integration point
    case "$integration_point" in
        "after_docker")
            # Add after Docker backup section
            if grep -q "docker" "$target_script" || grep -q "backup.*docker" "$target_script"; then
                # Find a good insertion point after docker backup
                local line_num=$(grep -n -i "docker.*backup\|backup.*docker" "$target_script" | tail -1 | cut -d: -f1)
                if [ -n "$line_num" ]; then
                    sed -i "${line_num}a\\${integration_code}" "$target_script"
                    echo -e "${GREEN}✓ Integrated after Docker backup section${NC}"
                else
                    echo -e "${YELLOW}Could not find Docker backup section, adding at end${NC}"
                    echo "$integration_code" >> "$target_script"
                fi
            else
                echo -e "${YELLOW}No Docker backup section found, adding at end${NC}"
                echo "$integration_code" >> "$target_script"
            fi
            ;;
        "before_end")
            # Add before the end of the script
            local last_line=$(wc -l < "$target_script")
            sed -i "${last_line}i\\${integration_code}" "$target_script"
            echo -e "${GREEN}✓ Integrated before end of script${NC}"
            ;;
        "manual")
            echo -e "${BLUE}Manual integration code:${NC}"
            echo "$integration_code"
            echo -e "${YELLOW}Please add this code manually to your script at the appropriate location${NC}"
            ;;
        *)
            echo -e "${YELLOW}Unknown integration point, adding at end${NC}"
            echo "$integration_code" >> "$target_script"
            ;;
    esac
    
    echo -e "${GREEN}Integration completed. Backup saved as $target_script.backup${NC}"
}

# Find and integrate with existing backup scripts
echo -e "${YELLOW}Scanning for backup scripts to integrate with...${NC}"

# Common backup script patterns
declare -a backup_scripts=(
    "$SCRIPT_DIR/backup-docker.sh"
    "$SCRIPT_DIR/backup-media.sh"
    "$SCRIPT_DIR/update.sh"
    "$SCRIPT_DIR/backup.sh"
    "$SCRIPT_DIR/daily-backup.sh"
)

found_scripts=()

for script in "${backup_scripts[@]}"; do
    if [ -f "$script" ]; then
        found_scripts+=("$script")
        echo -e "${GREEN}Found: $(basename "$script")${NC}"
    fi
done

if [ ${#found_scripts[@]} -eq 0 ]; then
    echo -e "${YELLOW}No backup scripts found to integrate with${NC}"
    echo -e "${BLUE}You can manually add the .env backup to your backup routine:${NC}"
    echo ""
    echo "# Add to your backup script:"
    echo "$SCRIPT_DIR/backup-env-files.sh"
    echo "$SCRIPT_DIR/validate-env-backups.sh --summary-only"
    echo ""
else
    echo -e "${BLUE}Select scripts to integrate with (or 'all' for all, 'none' to skip):${NC}"
    for i in "${!found_scripts[@]}"; do
        echo "$((i+1)). $(basename "${found_scripts[$i]}")"
    done
    echo ""
    
    read -p "Enter your choice: " choice
    
    case "$choice" in
        "all")
            for script in "${found_scripts[@]}"; do
                integrate_env_backup "$script" "after_docker"
            done
            ;;
        "none")
            echo -e "${YELLOW}Skipping integration${NC}"
            ;;
        [0-9]*)
            if [ "$choice" -ge 1 ] && [ "$choice" -le ${#found_scripts[@]} ]; then
                script_index=$((choice-1))
                integrate_env_backup "${found_scripts[$script_index]}" "after_docker"
            else
                echo -e "${RED}Invalid choice${NC}"
            fi
            ;;
        *)
            echo -e "${RED}Invalid choice${NC}"
            ;;
    esac
fi

# Create a simple cron entry suggestion
echo -e "${BLUE}=== Automation Suggestions ===${NC}"
echo "Add to crontab for automated backups:"
echo ""
echo "# Daily .env backup at 2 AM"
echo "0 2 * * * $SCRIPT_DIR/backup-env-files.sh >/dev/null 2>&1"
echo ""
echo "# Weekly validation on Sundays at 3 AM"
echo "0 3 * * 0 $SCRIPT_DIR/validate-env-backups.sh --summary-only"
echo ""

echo -e "${GREEN}Integration setup completed!${NC}"
echo -e "${BLUE}Next steps:${NC}"
echo "1. Run: $SCRIPT_DIR/backup-env-files.sh --init"
echo "2. Create private repository in Gitea"
echo "3. Run first backup: $SCRIPT_DIR/backup-env-files.sh"
echo "4. Test restoration: $SCRIPT_DIR/backup-env-files.sh --restore"
