#!/bin/bash

# This script applies Debian-specific patches to the setup scripts
# It should be run before bootstrap.sh on Debian systems

set -e  # Exit on error

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

# Check if running on Debian
if [ -f /etc/os-release ]; then
    . /etc/os-release
    if [[ "$ID" == "debian" ]]; then
        echo -e "${BLUE}Running on Debian $VERSION_ID ($PRETTY_NAME)${NC}"
    else
        echo -e "${YELLOW}This script is intended for Debian systems but detected $PRETTY_NAME${NC}"
        echo -e "${YELLOW}Continue anyway? [y/N]${NC}"
        read -r response
        if [[ ! "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
            echo -e "${RED}Exiting...${NC}"
            exit 1
        fi
    fi
fi

# Create a packages mapping file
PATCH_DIR="$HOME/.shell-debian-patches"
mkdir -p "$PATCH_DIR"

echo -e "${YELLOW}Creating Debian package name mappings...${NC}"
cat > "$PATCH_DIR/debian-packages.map" << 'EOF'
# Debian package name mappings
# format: ubuntu-name|debian-name

# bat is called batcat on Debian
bat|batcat

# Keep original names for packages that are the same
git|git
python3|python3
wget|wget
curl|curl
cowsay|cowsay
lolcat|lolcat
fzf|fzf
zsh|zsh

# Different package names for Nala source
software-properties-common|software-properties-common
EOF

# Create a patching script that will be called by setup.sh
echo -e "${YELLOW}Creating Debian patching script...${NC}"
cat > "$PATCH_DIR/apply-debian-patches.sh" << 'EOF'
#!/bin/bash

# Script to apply Debian-specific patches to the setup process

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

PATCH_DIR="$HOME/.shell-debian-patches"

# Check if running on Debian
if [ -f /etc/os-release ]; then
    . /etc/os-release
    if [[ "$ID" != "debian" ]]; then
        echo -e "${YELLOW}Not running on Debian, skipping patches${NC}"
        exit 0
    fi
fi

echo -e "${BLUE}Applying Debian-specific patches...${NC}"

# Function to map package names from Ubuntu to Debian
map_package() {
    local ubuntu_pkg="$1"
    local debian_pkg

    # Look for the package in the mapping file
    if [ -f "$PATCH_DIR/debian-packages.map" ]; then
        debian_pkg=$(grep -v "^#" "$PATCH_DIR/debian-packages.map" | grep "^$ubuntu_pkg|" | cut -d'|' -f2)
    fi

    # If not found or empty, use the original name
    if [ -z "$debian_pkg" ]; then
        debian_pkg="$ubuntu_pkg"
    fi

    echo "$debian_pkg"
}

# Patch the packages.list file if it exists
if [ -f "$HOME/shell/setup/packages.list" ]; then
    echo -e "${YELLOW}Patching packages.list for Debian compatibility...${NC}"

    # Create a temporary patched file
    temp_file=$(mktemp)

    # Process each line
    while IFS= read -r line; do
        # Skip comments and empty lines
        if [[ "$line" =~ ^//.*$ ]] || [[ -z "$line" ]]; then
            echo "$line" >> "$temp_file"
            continue
        fi

        # Map the package name
        debian_pkg=$(map_package "$line")
        echo "$debian_pkg" >> "$temp_file"

    done < "$HOME/shell/setup/packages.list"

    # Backup original and replace with patched version
    cp "$HOME/shell/setup/packages.list" "$HOME/shell/setup/packages.list.orig"
    mv "$temp_file" "$HOME/shell/setup/packages.list"

    echo -e "${GREEN}Patched packages.list for Debian compatibility${NC}"
fi

# Other Debian-specific patches can be added here...

# Add contrib and non-free repositories if they're not already enabled
echo -e "${YELLOW}Checking Debian repositories...${NC}"
if ! grep -q "contrib" /etc/apt/sources.list; then
    echo -e "${YELLOW}Adding contrib and non-free repositories...${NC}"
    # Create a backup of the original sources.list
    sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup

    # Add contrib and non-free to each deb line
    sudo sed -i 's/main$/main contrib non-free non-free-firmware/g' /etc/apt/sources.list

    echo -e "${GREEN}Added contrib and non-free repositories${NC}"
fi

echo -e "${GREEN}Debian patches applied successfully${NC}"
EOF

chmod +x "$PATCH_DIR/apply-debian-patches.sh"

# Create a wrapper script for bootstrap.sh
echo -e "${YELLOW}Creating Debian bootstrap wrapper...${NC}"
cat > "$HOME/debian-bootstrap.sh" << 'EOF'
#!/bin/bash

# Debian wrapper for bootstrap.sh

set -e  # Exit on error

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

PATCH_DIR="$HOME/.shell-debian-patches"

# Apply Debian patches first
if [ -x "$PATCH_DIR/apply-debian-patches.sh" ]; then
    echo -e "${BLUE}Applying Debian patches before bootstrap...${NC}"
    "$PATCH_DIR/apply-debian-patches.sh"
fi

# Download and run the bootstrap script securely
echo -e "${BLUE}Running bootstrap script...${NC}"
TEMP_BOOTSTRAP=$(mktemp)
if curl -s https://raw.githubusercontent.com/acedanger/shell/main/bootstrap.sh -o "$TEMP_BOOTSTRAP"; then
    echo -e "${BLUE}Bootstrap script downloaded, executing...${NC}"
    bash "$TEMP_BOOTSTRAP"
    rm -f "$TEMP_BOOTSTRAP"
else
    echo -e "${RED}ERROR: Failed to download bootstrap script${NC}"
    exit 1
fi

# Apply patches again after bootstrap (in case packages.list was just downloaded)
if [ -x "$PATCH_DIR/apply-debian-patches.sh" ]; then
    echo -e "${BLUE}Applying Debian patches after bootstrap...${NC}"
    "$PATCH_DIR/apply-debian-patches.sh"
fi

echo -e "${GREEN}Debian bootstrap completed!${NC}"
EOF

chmod +x "$HOME/debian-bootstrap.sh"

# Add a hook to setup.sh to call the Debian patch script
echo -e "${YELLOW}Creating setup.sh hook for Debian...${NC}"
cat > "$PATCH_DIR/setup-hook.sh" << 'EOF'
#!/bin/bash

# Hook to modify setup.sh to call Debian patches

if [ -f /etc/os-release ]; then
    . /etc/os-release
    if [[ "$ID" == "debian" ]]; then
        # Modify setup.sh to call Debian patches
        if [ -f "$HOME/shell/setup/setup.sh" ]; then
            # Check if the patch hasn't been applied yet
            if ! grep -q "apply-debian-patches" "$HOME/shell/setup/setup.sh"; then
                # Add call to Debian patch script right after the shebang
                sed -i '2i\
# Apply Debian patches if available\
if [ -x "$HOME/.shell-debian-patches/apply-debian-patches.sh" ]; then\
    echo -e "${YELLOW}Applying Debian-specific patches...${NC}"\
    "$HOME/.shell-debian-patches/apply-debian-patches.sh"\
fi' "$HOME/shell/setup/setup.sh"
            fi
        fi
    fi
fi
EOF

chmod +x "$PATCH_DIR/setup-hook.sh"

echo -e "${GREEN}Debian compatibility patch has been set up!${NC}"
echo -e "${YELLOW}To bootstrap your Debian system, run:${NC}"
echo -e "  ${BLUE}bash ~/debian-bootstrap.sh${NC}"
echo ""
echo -e "${YELLOW}This has created:${NC}"
echo -e "1. Package name mappings for Debian"
echo -e "2. A patch script for Debian-specific adjustments"
echo -e "3. A Debian-specific bootstrap wrapper"
