#!/bin/bash
#
# Cleanup Script for Cached 404 Pages
#
# This script removes cached 404 pages from the .next/server/app/dealers/ directory.
# It uses CONTENT-BASED detection to ensure we only delete actual 404 pages,
# not legitimate dealer pages that might have suspicious-looking subdomains.
#
# How it works:
# 1. Scans all .html files in the dealer cache directory
# 2. Checks if the file contains our 404 page signature ("Page Not Found")
# 3. Only deletes files that are confirmed 404 pages
# 4. Also removes associated .meta, .rsc, and .segments files
#
# Usage: ./scripts/cleanup-cached-404s.sh [--dry-run] [--production]
#
# Options:
#   --dry-run     Show what would be deleted without actually deleting
#   --production  Target the production cache directory
#

set -euo pipefail

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

# Parse arguments
DRY_RUN=false
PRODUCTION=false
CACHE_DIR=".next/server/app/dealers"

while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --production)
            PRODUCTION=true
            shift
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--dry-run] [--production]"
            exit 1
            ;;
    esac
done

# Adjust cache directory for production if needed
if [ "$PRODUCTION" = true ]; then
    if [ -d "/var/www/amsoil-dlp/.next/server/app/dealers" ]; then
        CACHE_DIR="/home/amsoildlp/public_html/amsoil.aimclear.com"
    fi
fi

# Check if cache directory exists
if [ ! -d "$CACHE_DIR" ]; then
    echo -e "${YELLOW}Cache directory not found: $CACHE_DIR${NC}"
    echo "This might be normal if the build hasn't run yet or the server is fresh."
    exit 0
fi

echo "=== Cached 404 Cleanup Script (Content-Based) ==="
echo "Cache directory: $CACHE_DIR"
if [ "$DRY_RUN" = true ]; then
    echo -e "${YELLOW}Running in DRY RUN mode - no files will be deleted${NC}"
fi
echo ""

# 404 page signature - this text appears in our not-found.tsx
# We check for this to confirm a file is actually a 404 page
SIGNATURE_404="Page Not Found"

# Alternative signatures to check (in case the main one changes)
ALT_SIGNATURES=(
    "The page you're looking for doesn't exist"
    "404"
)

# Count files before
TOTAL_BEFORE=$(find "$CACHE_DIR" -type f -name "*.html" 2>/dev/null | wc -l)
echo "Total HTML files in dealer cache: $TOTAL_BEFORE"
echo ""

# Find all HTML files and check their content
echo -e "${BLUE}Scanning for 404 pages by content...${NC}"

FOUND_404S=()
SCANNED=0
FOUND_COUNT=0

while IFS= read -r -d '' html_file; do
    ((SCANNED++))

    # Check if file contains 404 signature
    if grep -q "$SIGNATURE_404" "$html_file" 2>/dev/null; then
        FOUND_404S+=("$html_file")
        ((FOUND_COUNT++))
    fi
done < <(find "$CACHE_DIR" -type f -name "*.html" -print0 2>/dev/null)

echo "Scanned: $SCANNED HTML files"
echo -e "Found: ${YELLOW}$FOUND_COUNT${NC} confirmed 404 pages"

if [ $FOUND_COUNT -eq 0 ]; then
    echo ""
    echo -e "${GREEN}No cached 404 pages found - cache is clean!${NC}"
    exit 0
fi

# Collect all related files (.html, .meta, .rsc, .segments)
ALL_FILES_TO_DELETE=()
for html_file in "${FOUND_404S[@]}"; do
    # Get the base path without extension
    base_path="${html_file%.html}"

    # Add the HTML file
    ALL_FILES_TO_DELETE+=("$html_file")

    # Add related files if they exist
    for ext in meta rsc segments; do
        related_file="${base_path}.${ext}"
        if [ -f "$related_file" ]; then
            ALL_FILES_TO_DELETE+=("$related_file")
        fi
    done

    # Also check for directory-based cache structure
    # e.g., /dealers/wp-login.php/index.html
    dir_path="${html_file%/index.html}"
    if [ "$dir_path" != "$html_file" ] && [ -d "$dir_path" ]; then
        # This is a directory-based entry, collect all files in it
        while IFS= read -r -d '' related_file; do
            if [[ ! " ${ALL_FILES_TO_DELETE[*]} " =~ " ${related_file} " ]]; then
                ALL_FILES_TO_DELETE+=("$related_file")
            fi
        done < <(find "$dir_path" -type f -print0 2>/dev/null)
    fi
done

TOTAL_FILES=${#ALL_FILES_TO_DELETE[@]}
echo ""
echo "Total files to delete (including .meta, .rsc, .segments): $TOTAL_FILES"

# Show sample of found 404s (show the subdomain/path, not full path)
echo ""
echo "Sample of 404 pages found:"
for html_file in "${FOUND_404S[@]:0:15}"; do
    # Extract the subdomain/path from the file path
    relative="${html_file#$CACHE_DIR/}"
    # Remove common suffixes for cleaner display
    clean_path="${relative%.html}"
    clean_path="${clean_path%/index}"
    echo "  - $clean_path"
done
if [ $FOUND_COUNT -gt 15 ]; then
    echo "  ... and $((FOUND_COUNT - 15)) more"
fi

# Calculate disk space
TOTAL_SIZE=$(du -ch "${ALL_FILES_TO_DELETE[@]}" 2>/dev/null | tail -1 | cut -f1 || echo "unknown")
echo ""
echo "Total disk space to be freed: $TOTAL_SIZE"

# Delete files
if [ "$DRY_RUN" = true ]; then
    echo ""
    echo -e "${YELLOW}DRY RUN: No files were deleted${NC}"
    echo "Run without --dry-run to actually delete these files"
else
    echo ""
    echo "Deleting files..."
    DELETED_COUNT=0
    FAILED_COUNT=0

    for file in "${ALL_FILES_TO_DELETE[@]}"; do
        if rm -f "$file" 2>/dev/null; then
            ((DELETED_COUNT++))
        else
            ((FAILED_COUNT++))
        fi
    done

    # Clean up empty directories
    find "$CACHE_DIR" -type d -empty -delete 2>/dev/null || true

    echo -e "${GREEN}Successfully deleted $DELETED_COUNT files${NC}"
    if [ $FAILED_COUNT -gt 0 ]; then
        echo -e "${RED}Failed to delete $FAILED_COUNT files${NC}"
    fi

    # Count files after
    TOTAL_AFTER=$(find "$CACHE_DIR" -type f -name "*.html" 2>/dev/null | wc -l)
    echo ""
    echo "HTML files before: $TOTAL_BEFORE"
    echo "HTML files after:  $TOTAL_AFTER"
    echo "404 pages removed: $((TOTAL_BEFORE - TOTAL_AFTER))"
fi

echo ""
echo "=== Cleanup Complete ==="
