#!/bin/sh
set -e

SRC="${SRC:-src}"
DIST="${DIST:-dist}"

# Clean and create dist
rm -rf "$DIST"
mkdir -p "$DIST"

# Copy index.html
cp "$SRC/index.html" "$DIST/index.html"

# Cache-bust assets by appending a content hash to filenames
for ext in css js jpeg png svg ico; do
    for file in "$SRC"/*."$ext"; do
        [ -f "$file" ] || continue
        name=$(basename "$file" | sed "s/\.$ext$//")
        hash=$(md5sum "$file" | cut -d' ' -f1)
        newname="${name}.${hash}.${ext}"

        cp "$file" "$DIST/$newname"

        # Update references in HTML
        case "$ext" in
            css)
                sed -i "s|href=\"${name}.${ext}\"|href=\"${newname}\"|g" "$DIST/index.html"
                ;;
            js)
                sed -i "s|src=\"${name}.${ext}\"|src=\"${newname}\"|g" "$DIST/index.html"
                ;;
            jpeg|png|svg|ico)
                sed -i "s|\"${name}.${ext}\"|\"${newname}\"|g" "$DIST/index.html"
                ;;
        esac
    done
done

echo "Build complete: $DIST/"
echo "Assets with cache-busting hashes:"
ls -1 "$DIST"
