#!/bin/bash

# Check if the search word is provided as an argument
if [ -z "$1" ]; then
    echo "Usage: $0 <search_word>"
    exit 1
fi

# Search word from the command line argument
search_word="$1"

# Output HTML file
output_file="${search_word}.html"

# Temporary file to store the unsorted results
temp_file=$(mktemp)

# Process each gz file
for file in ./zonefiles/*.gz; do
    # Decompress and search for 'example.com', capturing matching lines
    zcat "$file" | grep "$search_word" | while read -r line ; do
        # Extract the word between the first and second dot
        extracted_word=$(echo "$line" | awk -F'.' '{print $2}')
        # Escape HTML special characters in the output
        escaped_line=$(echo "$line" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g')
        # Append the extracted word and line to the temporary file
        echo "$extracted_word|$escaped_line" >> "$temp_file"
    done
done

# Sort the results by the extracted word
sort -t '|' -k1,1 "$temp_file" -o "$temp_file"

# Count the number of matches
match_count=$(wc -l < "$temp_file")

# Start HTML structure
cat <<EOF > "$output_file"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Results</title>
    <style>
        body { font-family: Arial, sans-serif; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border: 1px solid #ddd; padding: 8px; }
        th { background-color: #f2f2f2; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        tr:hover { background-color: #f1f1f1; }
        h1 { text-align: center; }
        p { text-align: center; font-weight: bold; }
    </style>
</head>
<body>
    <h1>Search Results for '$search_word'</h1>
    <p>Total Matches: $match_count</p>
    <table>
        <thead>
            <tr>
                <th>TLD</th>
                <th>Matching Line</th>
            </tr>
        </thead>
        <tbody>
EOF

# Read sorted results from the temporary file and add them to the HTML file
while IFS='|' read -r extracted_word escaped_line; do
    echo "<tr><td>$extracted_word</td><td>$escaped_line</td></tr>" >> "$output_file"
done < "$temp_file"

# End HTML structure
cat <<EOF >> "$output_file"
        </tbody>
    </table>
</body>
</html>
EOF

# Clean up the temporary file
rm "$temp_file"

echo "Results saved to $output_file"

