#!/bin/bash

# Script to create symbolic links for hashed pkg files
# This allows serving static HTML with non-hashed filenames while maintaining cache busting

set -e

PKG_DIR="pkg"

echo "🔗 Creating symbolic links for hashed pkg files..."

# Check if pkg directory exists
if [ ! -d "$PKG_DIR" ]; then
    echo "❌ Error: pkg directory not found"
    exit 1
fi

cd "$PKG_DIR"

# Find all hashed files in the current directory
echo "📦 Scanning for hashed files..."
HASHED_JS=$(ls website.*.js 2>/dev/null | grep -v '^website\.js$' | head -1)
HASHED_WASM=$(ls website.*.wasm 2>/dev/null | grep -v '^website\.wasm$' | head -1)

if [ -n "$HASHED_JS" ]; then
    echo "  Found hashed JS: $HASHED_JS"
else
    echo "  No hashed JS files found"
fi

if [ -n "$HASHED_WASM" ]; then
    echo "  Found hashed WASM: $HASHED_WASM"
else
    echo "  No hashed WASM files found"
fi

# Create symbolic links from non-hashed names to hashed files (if they exist)
if [ -n "$HASHED_JS" ] && [ -f "$HASHED_JS" ]; then
    # Remove existing non-hashed file if it's a regular file
    [ -f "website.js" ] && [ ! -L "website.js" ] && rm "website.js"
    # Create symlink
    ln -sf "$HASHED_JS" "website.js"
    echo "✅ Created symbolic link: website.js -> $HASHED_JS"
fi

if [ -n "$HASHED_WASM" ] && [ -f "$HASHED_WASM" ]; then
    # Remove existing non-hashed file if it's a regular file
    [ -f "website.wasm" ] && [ ! -L "website.wasm" ] && rm "website.wasm"
    # Create symlink
    ln -sf "$HASHED_WASM" "website.wasm"
    echo "✅ Created symbolic link: website.wasm -> $HASHED_WASM"
fi

# Ensure CSS is available (usually not hashed)
if [ -f "website.css" ]; then
    echo "✅ CSS file found: website.css"
else
    echo "❌ Warning: CSS file not found"
fi

echo "🎉 Symbolic links created successfully!"
echo ""
echo "Final file structure:"
ls -la website.*
