#!/bin/bash

# Download xterm.js files for terminal functionality
XTERM_VERSION="5.3.0"
# Download to web-files directory which gets copied to /docker/whp/web/
TARGET_DIR="/root/whp/web-files/js/xterm"

echo "Downloading xterm.js v${XTERM_VERSION}..."

# Create target directory
mkdir -p "$TARGET_DIR"

# Download xterm.js files
cd "$TARGET_DIR"

# Core files
echo "Downloading xterm.js core files..."
wget "https://unpkg.com/xterm@${XTERM_VERSION}/lib/xterm.js" -O xterm.js
if [ $? -ne 0 ]; then
    echo "Error: Failed to download xterm.js"
    exit 1
fi

wget "https://unpkg.com/xterm@${XTERM_VERSION}/css/xterm.css" -O xterm.css
if [ $? -ne 0 ]; then
    echo "Error: Failed to download xterm.css"
    exit 1
fi

# Addons (separate packages)
echo "Downloading xterm.js addons..."
mkdir -p addons

# FitAddon
wget "https://unpkg.com/@xterm/addon-fit@0.10.0/lib/addon-fit.js" -O addons/xterm-addon-fit.js
if [ $? -ne 0 ]; then
    echo "Error: Failed to download xterm-addon-fit.js"
    exit 1
fi

# WebLinksAddon  
wget "https://unpkg.com/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js" -O addons/xterm-addon-web-links.js
if [ $? -ne 0 ]; then
    echo "Error: Failed to download xterm-addon-web-links.js"
    exit 1
fi

# AttachAddon (not needed for our implementation but keeping for compatibility)
wget "https://unpkg.com/xterm-addon-attach@0.9.0/lib/xterm-addon-attach.js" -O addons/xterm-addon-attach.js
if [ $? -ne 0 ]; then
    echo "Error: Failed to download xterm-addon-attach.js"
    exit 1
fi

echo "xterm.js downloaded successfully to $TARGET_DIR"

# Make sure files are readable
chmod 644 *.js *.css addons/*.js

# Verify files were downloaded
echo "Verifying downloaded files..."
for file in xterm.js xterm.css addons/xterm-addon-fit.js addons/xterm-addon-web-links.js addons/xterm-addon-attach.js; do
    if [ ! -f "$file" ]; then
        echo "Error: $file was not downloaded properly"
        exit 1
    fi
    echo "✓ $file exists ($(du -h "$file" | cut -f1))"
done

# Copy to web document root if it exists
if [ -d "/docker/whp/web/" ]; then
    echo "Copying xterm.js files to web document root..."
    mkdir -p /docker/whp/web/js/xterm/addons
    rsync -av /root/whp/web-files/js/xterm/ /docker/whp/web/js/xterm/
    
    # Verify files were copied
    echo "Verifying files in web root..."
    for file in xterm.js xterm.css addons/xterm-addon-fit.js addons/xterm-addon-web-links.js addons/xterm-addon-attach.js; do
        if [ ! -f "/docker/whp/web/js/xterm/$file" ]; then
            echo "Error: $file was not copied to web root"
            exit 1
        fi
        echo "✓ /docker/whp/web/js/xterm/$file exists"
    done
    
    echo "✓ xterm.js files copied to web root successfully"
fi

echo "Done!"