#!/usr/bin/env bash
#
# build.sh — Assemble static HTML from PHP sources + templates
#
# Usage:  bash build.sh [BUILD_DIR]
#   BUILD_DIR  — output directory (default: build)
#
set -uo pipefail

[ -f "build.sh" ] || { echo "Invalid working directory, no build.sh found."; exit 1; }
BUILD_DIR="${1:-build}"
TEMPLATE_DIR="templates"
HEADER="${TEMPLATE_DIR}/header.html"
FOOTER="${TEMPLATE_DIR}/footer.html"

# ── clean / create build dir ─────────────────────────────────────────

rm -rf "${BUILD_DIR}"
mkdir -p "${BUILD_DIR}"
echo "==> Building into ${BUILD_DIR}"

# ── process each .php file ───────────────────────────────────────────

echo
echo "==> Converting PHP to HTML"
php_count=0

while IFS= read -r -d '' php_file; do
    # ── 1. Output path: .php → .html
    out_rel="${php_file%.php}.html"
    out_file="${BUILD_DIR}/${out_rel}"
    mkdir -p "$(dirname "${out_file}")"

    # ── 2. Extract body content ───────────────────────────────────
    #    a) Strip first 2 lines (the <?php ... include_once ... ?> block)
    #    b) Strip any <?php mkFooter(...) ?> lines
    #    c) Replace <?php mkEmail(); ?> with the actual email address
    #    d) Strip any leftover bare <?php ... ?> single-line tags
    body=$(sed \
        -e '1,2d' \
        -e '/<?php[[:space:]]*mkFooter/d' \
        -e 's|<?php[[:space:]]*mkEmail();[[:space:]]*?>|pbaumann@constructor.university|g' \
        "${php_file}")

    # ── 3. Convert internal .php links to .html ──────────────────
    body=$(echo "${body}" | sed -E 's|href="([^"]*)\.php"|href="\1.html"|g')

    # ── 4. Assemble: header + body + footer ──────────────────────
    {
        cat "${HEADER}"
        printf '%s\n' "${body}"
        cat "${FOOTER}"
    } > "${out_file}"

    php_count=$((php_count + 1))
    echo "  ${php_file} → ${out_file}"

done < <(find . -name '*.php' \
            ! -path "*/${BUILD_DIR}/*" ! -path "*/${TEMPLATE_DIR}/*" \
            -print0 | sort -z)

# ── copy already-static .html files ──────────────────────────────────

echo
echo "==> Copying static non-php files"
nonphp_count=0
while IFS= read -r -d '' nonphp_file; do
    out_file="${BUILD_DIR}/${nonphp_file}"
    mkdir -p "$(dirname "${out_file}")"

    # Convert .php links inside static HTML too
    if [[ "$nonphp_file" == *.html ]]; then
        sed -E 's|href="([^"]*)\.php"|href="\1.html"|g' "${nonphp_file}" > "${out_file}"
    else
        cp "$nonphp_file" "$out_file"
    fi

    nonphp_count=$((nonphp_count + 1))
    echo "  ${nonphp_file} (static, copied)"
done < <(find . -type f ! -name '*.php' ! -name 'README.md' ! -name 'Makefile' \
            ! -path "*/.svn*" ! -name '.' ! -name 'globals.inc' \
            ! -path "*/${BUILD_DIR}*" ! -path "*/${TEMPLATE_DIR}*" \
            -print0 | sort -z)

# ── summary ──────────────────────────────────────────────────────────

echo ""
echo "==> Done: ${php_count} PHP + ${nonphp_count} static files → ${BUILD_DIR}/"

# ── check links ──────────────────────────────────────────────────────

echo ""
echo "==> Checking internal links in $BUILD_DIR/..."
for f in $(find "$BUILD_DIR" -name '*.html'); do
    grep -oP 'href="[^"]*\.html"' "$f" | sed 's/href="//;s/"//' | grep -v http | while read -r link; do
        # Strip query strings and fragments
        target=$(echo "$link" | sed 's/[?#].*//');
        # Resolve relative to the file's directory
        base=$(dirname "$f")
        if [[ "$target" == /* ]]; then
            full="$BUILD_DIR/$target"
        else
            full="$base/$target"
        fi
        if [ ! -f "$full" ]; then
            echo "  BROKEN: $f → $target (not found: $full)"
        fi
    done
done
