#!/bin/bash

# ============================================================================
# Script: auto_generate_gitkeep.sh
# Purpose: Automatically parse .gitignore files and generate .gitkeep in
#          un-ignored directories
# ============================================================================

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Function to extract un-ignored directories from .gitignore
extract_unignored_dirs() {
    local gitignore_file="$1"
    local base_path="$2"

    if [ ! -f "$gitignore_file" ]; then
        echo -e "${RED}Warning: $gitignore_file not found${NC}"
        return
    fi

    # Extract lines that start with ! and end with /
    # These are the un-ignored directories
    grep -E '^!/' "$gitignore_file" | \
        sed 's/^!\///' | \
        sed 's/\/$//' | \
        while read -r dir; do
            # Skip non-directory entries (files like index.php, favicon.ico)
            if [[ "$dir" != *.* ]] || [[ "$dir" == */* ]]; then
                echo "${base_path}${dir}"
            fi
        done
}

# Function to create .gitkeep
create_gitkeep() {
    local dir_path="$1"

    if [ ! -d "$dir_path" ]; then
        echo -e "${YELLOW}[SKIPPED]${NC} $dir_path (directory does not exist)"
        return
    fi

    local gitkeep_file="${dir_path}/.gitkeep"
    if [ ! -f "$gitkeep_file" ]; then
        touch "$gitkeep_file"
        echo -e "${GREEN}[CREATED]${NC} $gitkeep_file"
    else
        echo -e "${RED}[EXISTS]${NC} $gitkeep_file"
    fi
}
# ============================================================================
# MAIN
# ============================================================================

BASE_DIR="${1:-.}"

echo "========================================"
echo " Auto-generating .gitkeep files"
echo " Base directory: $BASE_DIR"
echo "========================================"
echo ""

# Process www/.gitignore
echo "--- Processing www/.gitignore ---"
if [ -f "${BASE_DIR}/.gitignore" ]; then
    while IFS= read -r dir; do
        [ -z "$dir" ] && continue
        create_gitkeep "${BASE_DIR}/${dir}"
    done < <(extract_unignored_dirs "${BASE_DIR}/.gitignore" "")
fi

echo ""

# Process www/admin/.gitignore
echo "--- Processing www/admin/.gitignore ---"
if [ -f "${BASE_DIR}/admin/.gitignore" ]; then
    while IFS= read -r dir; do
        [ -z "$dir" ] && continue
        create_gitkeep "${BASE_DIR}/admin/${dir}"
    done < <(extract_unignored_dirs "${BASE_DIR}/admin/.gitignore" "")
fi

echo ""
echo "========================================"
echo -e "${GREEN} Done!${NC}"
echo "========================================"
