#!/bin/bash

# MongoDB Migration Web Interface
# Serves migration progress at ROOT_URL/migration-progress using Node.js

# Source settings
source $SNAP/bin/wekan-read-settings

# Set up Node.js environment like wekan-control
export NODE_PATH=$SNAP/bin

# Configuration
MIGRATION_STATUS="${SNAP_COMMON}/mongodb-migration-status.json"
MIGRATION_LOG="${SNAP_COMMON}/mongodb-migration-log.txt"
MIGRATION_PROGRESS="${SNAP_COMMON}/mongodb-migration-progress.html"
# Use same PORT as wekan-control, but add 1 to avoid conflicts
MIGRATION_PORT=$((PORT + 1))

# Create Node.js HTTP server script
create_node_server() {
    cat > "${SNAP_COMMON}/migration-web-server.js" << 'EOF'
const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = process.env.MIGRATION_PORT || 8081;
const SNAP_COMMON = process.env.SNAP_COMMON;
const ROOT_URL = process.env.ROOT_URL || 'http://127.0.0.1';
const MIGRATION_STATUS = path.join(SNAP_COMMON, 'mongodb-migration-status.json');
const MIGRATION_LOG = path.join(SNAP_COMMON, 'mongodb-migration-log.txt');

function readFileSafe(filePath) {
    try {
        return fs.readFileSync(filePath, 'utf8');
    } catch (error) {
        return null;
    }
}

function getMigrationStatus() {
    const statusContent = readFileSafe(MIGRATION_STATUS);
    if (!statusContent) {
        return null;
    }
    
    try {
        return JSON.parse(statusContent);
    } catch (error) {
        return null;
    }
}

function getMigrationLog() {
    const logContent = readFileSafe(MIGRATION_LOG);
    if (!logContent) {
        return 'No log available';
    }
    
    const lines = logContent.split('\n');
    return lines.slice(-20).join('\n');
}

function generateHTML(status) {
    if (!status) {
        return `<!DOCTYPE html>
<html>
<head>
    <title>MongoDB Migration Progress</title>
    <meta http-equiv="refresh" content="5">
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; margin: 0 auto; text-align: center; }
    </style>
</head>
<body>
    <div class="container">
        <h1>MongoDB Migration</h1>
        <p>No migration in progress.</p>
        <p><em>This page will refresh automatically every 5 seconds.</em></p>
    </div>
</body>
</html>`;
    }

    const { status: statusValue, step, total_steps, percentage, description, timestamp } = status;
    const logContent = getMigrationLog();

    return `<!DOCTYPE html>
<html>
<head>
    <title>MongoDB Migration Progress</title>
    <meta http-equiv="refresh" content="5">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .progress-bar {
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin: 20px 0;
        }
        .progress-fill {
            height: 40px;
            background: linear-gradient(90deg, #4CAF50, #45a049);
            border-radius: 10px;
            width: ${percentage}%;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        .status {
            margin: 20px 0;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .error { color: #d32f2f; }
        .success { color: #388e3c; }
        .warning { color: #f57c00; }
        .info { color: #1976d2; }
        .log-container {
            margin-top: 30px;
            max-height: 300px;
            overflow-y: auto;
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-running { background-color: #ff9800; }
        .status-completed { background-color: #4caf50; }
        .status-error { background-color: #f44336; }
        .status-unknown { background-color: #9e9e9e; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>MongoDB Migration Progress</h1>
            <p>Migrating from MongoDB 3 to MongoDB 7</p>
        </div>

        <div class="progress-bar">
            <div class="progress-fill">${percentage}%</div>
        </div>

        <div class="status">
            <p><span class="status-indicator status-${statusValue}"></span><strong>Status:</strong> ${statusValue}</p>
            <p><strong>Progress:</strong> ${step} of ${total_steps} steps</p>
            <p><strong>Current Step:</strong> ${description}</p>
            <p><strong>Last Updated:</strong> ${timestamp}</p>
        </div>

        <div class="log-container">
            <h3>Migration Log (Last 20 lines):</h3>
            <pre>${logContent}</pre>
        </div>

        <p style="text-align: center; margin-top: 30px; color: #666;">
            <em>This page will refresh automatically every 5 seconds.</em><br>
            <em>Migration URL: ${ROOT_URL}/migration-progress</em>
        </p>
    </div>
</body>
</html>`;
}

const server = http.createServer((req, res) => {
    if (req.url === '/migration-progress' || req.url === '/') {
        const status = getMigrationStatus();
        const html = generateHTML(status);
        
        res.writeHead(200, {
            'Content-Type': 'text/html; charset=utf-8',
            'Cache-Control': 'no-cache',
            'Connection': 'close'
        });
        res.end(html);
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(PORT, () => {
    console.log(`MongoDB Migration Web Server running on port ${PORT}`);
});

// Handle graceful shutdown
process.on('SIGTERM', () => {
    console.log('Received SIGTERM, shutting down gracefully');
    server.close(() => {
        process.exit(0);
    });
});

process.on('SIGINT', () => {
    console.log('Received SIGINT, shutting down gracefully');
    server.close(() => {
        process.exit(0);
    });
});
EOF
}

# Start the Node.js web server
start_node_server() {
    echo "Starting MongoDB migration web server using Node.js..."
    echo "Migration server will be available at: ${ROOT_URL}/migration-progress"
    echo "Migration server port: ${MIGRATION_PORT}"
    
    # Create the Node.js server script
    create_node_server
    
    # Export environment variables for the Node.js process
    export MIGRATION_PORT
    export ROOT_URL
    
    # Start the server using Node.js from SNAP/bin
    $NODE_PATH/node "${SNAP_COMMON}/migration-web-server.js"
}

# Start the web server
start_node_server
