#!/bin/sh

SHA=$(git rev-parse --short HEAD)

# Discover all modules in src/js (excluding main.ts and temp files)
MODULES=$(ls src/js/*.ts | sed 's|src/js/||' | sed 's|.ts$||' | grep -v -E '^(main|.*\.tmp)$' | sort)

# Create temporary exports file
echo "// Auto-generated exports for dynamically loaded browser commands" > ./src/js/exports.tmp.ts

# Generate import statements
for mod in $MODULES; do
  echo "import * as $mod from \"./$mod\"" >> ./src/js/exports.tmp.ts
done

echo "" >> ./src/js/exports.tmp.ts
echo "Object.assign(window, {" >> ./src/js/exports.tmp.ts
echo "  __pluto_modules: {" >> ./src/js/exports.tmp.ts

# Generate module list with proper formatting
FIRST=true
for mod in $MODULES; do
  if [ "$FIRST" = true ]; then
    printf "    %s" "$mod" >> ./src/js/exports.tmp.ts
    FIRST=false
  else
    printf ", %s" "$mod" >> ./src/js/exports.tmp.ts
  fi
done
printf ",\n" >> ./src/js/exports.tmp.ts

echo "  }" >> ./src/js/exports.tmp.ts
echo "})" >> ./src/js/exports.tmp.ts

# Create temporary main.ts that includes exports
cat ./src/js/main.ts ./src/js/exports.tmp.ts > ./src/js/main.tmp.ts

# Build from temporary main
bun build ./src/js/main.tmp.ts \
            --outfile ./public/bundle.tmp.js \
            --target browser

# Clean up temporary files
rm ./src/js/exports.tmp.ts ./src/js/main.tmp.ts

# If bundle.js doesn't exist yet, fake it it
if [ ! -f ./public/bundle.js ]; then
    touch ./public/bundle.js
fi

# Strip version comments from both files and compare
tail -n +4 ./public/bundle.js > ./public/bundle.old.content.tmp
tail -n +1 ./public/bundle.tmp.js > ./public/bundle.new.content.tmp

if ! cmp -s ./public/bundle.old.content.tmp ./public/bundle.new.content.tmp; then
    printf "////\n// version: %s\n\n" "$SHA" | cat - ./public/bundle.tmp.js > ./public/bundle.js
fi

rm ./public/bundle.tmp.js ./public/bundle.old.content.tmp ./public/bundle.new.content.tmp