#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

BLOG_INDEX="blog/index.html"
SAMPLE_ARTICLE="blog/clanki/2025-11-17-sample-article.html"

echo "Checking links in $BLOG_INDEX..."
# Extract all href attributes and check if they return 200 OK
grep -Eio 'href="([^"]+)"' "$BLOG_INDEX" | sed -E 's/href="([^"]+)"/\1/' | while read -r link; do
    if [[ "$link" == /* ]]; then # Internal link
        # For internal links, check if the file exists
        if [ -f ".${link}" ]; then
            echo "  [OK] Internal link: $link"
        else
            echo "  [ERROR] Internal link not found: $link"
            exit 1
        fi
    elif [[ "$link" == http* ]]; then # External link
        # For external links, use curl to check status
        status_code=$(curl -s -o /dev/null -w "%{http_code}" "$link")
        if [ "$status_code" -eq 200 ]; then
            echo "  [OK] External link: $link"
        else
            echo "  [ERROR] External link failed ($status_code): $link"
            exit 1
        fi
    fi
done

echo "Checking links in $SAMPLE_ARTICLE..."
grep -Eio 'href="([^"]+)"' "$SAMPLE_ARTICLE" | sed -E 's/href="([^"]+)"/\1/' | while read -r link; do
    if [[ "$link" == /* ]]; then # Internal link
        # For internal links, check if the file exists
        if [ -f ".${link}" ]; then
            echo "  [OK] Internal link: $link"
        else
            echo "  [ERROR] Internal link not found: $link"
            exit 1
        fi
    elif [[ "$link" == http* ]]; then # External link
        status_code=$(curl -s -o /dev/null -w "%{http_code}" "$link")
        if [ "$status_code" -eq 200 ]; then
            echo "  [OK] External link: $link"
        else
            echo "  [ERROR] External link failed ($status_code): $link"
            exit 1
        fi
    fi
done

echo "Link checking completed."