#!/bin/bash

# Script to convert noVNC ES6 modules to global scripts

echo "Converting noVNC files from ES6 modules to global scripts..."

# Function to convert a single file
convert_file() {
    local file="$1"
    echo "Converting $file..."

    # Create a backup
    cp "$file" "${file}.bak"

    # Remove import statements and convert exports
    sed -i '
        # Remove import statements
        /^import.*from/d
        /^export function /{
            s/export function /function /
        }
        /^export const /{
            s/export const /const /
        }
        /^export let /{
            s/export let /let /
        }
        /^export default class /{
            s/export default class /class /
        }
        /^export class /{
            s/export class /class /
        }
        /^export default /{
            s/export default /window./
        }
        /^export {/{
            s/export {/window./
            s/}/ = {/
            s/ as /: /
        }
    ' "$file"

    # Add global assignments for exported items
    if grep -q "^function " "$file" || grep -q "^const " "$file" || grep -q "^let " "$file" || grep -q "^class " "$file"; then
        # Find exported functions/variables and add global assignments
        grep "^function \|^const \|^let \|^class " "$file" | while read -r line; do
            if [[ $line =~ ^(function|const|let|class)[[:space:]]+([a-zA-Z_][a-zA-Z0-9_]*) ]]; then
                name="${BASH_REMATCH[2]}"
                # Skip if already assigned to window
                if ! grep -q "window\.$name" "$file"; then
                    echo "window.$name = $name;" >> "$file"
                fi
            fi
        done
    fi
}

# Convert all JS files
find templates/novnc -name "*.js" | while read -r file; do
    convert_file "$file"
done

echo "Conversion complete!"