#!/bin/bash
# =====================================================================
# generate-sitemap.sh - Generate sitemap.xml for the website
# =====================================================================
# This script generates a sitemap.xml file for the website
# It should be run after any content updates
# =====================================================================

set -e

echo "Generating sitemap.xml..."

# Directory containing the files
BASE_DIR="$(pwd)"
# Use production domain by default, can be overridden with SITEMAP_DOMAIN env var
DOMAIN="${SITEMAP_DOMAIN:-https://colinknapp.com}"

# Get current date in ISO 8601 format
CURRENT_DATE=$(date -u +"%Y-%m-%dT%H:%M:%S+00:00")

# Create sitemap header
cat > "$BASE_DIR/sitemap.xml" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
EOF

# Find all HTML files and add them to sitemap
find "$BASE_DIR" -name "*.html" -type f | sort | while read -r html_file; do
    # Skip files in includes directory and template files
    if [[ "$html_file" == *"/includes/"* ]] || [[ "$html_file" == *"-with-includes.html" ]] || [[ "$html_file" == *"template"* ]]; then
        continue
    fi
    
    # Get relative path from base directory
    rel_path="${html_file#$BASE_DIR/}"
    
    # Skip csv-tool-output.html as it's dynamically generated
    if [[ "$rel_path" == "csv-tool-output.html" ]]; then
        continue
    fi
    
    # Skip consulting-packs.html as it's a private unlisted page
    if [[ "$rel_path" == "consulting-packs.html" ]]; then
        continue
    fi
    
    # Create URL
    url="$DOMAIN/$rel_path"
    
    # Add URL to sitemap
    cat >> "$BASE_DIR/sitemap.xml" << EOF
  <url>
    <loc>$url</loc>
    <lastmod>$CURRENT_DATE</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
EOF
done

# Close sitemap
cat >> "$BASE_DIR/sitemap.xml" << EOF
</urlset>
EOF

echo "Sitemap generated at $BASE_DIR/sitemap.xml"
echo "Total URLs: $(grep -c "<url>" "$BASE_DIR/sitemap.xml")"
