/** @param {import(".").NS } ns */
const doc = eval('document');

export async function main(ns) {
    // ns.disableLog('ALL');

    /**
     * Recursively kill simple-hack.js running on servers in the network
     * @async
     * @param {string} currentServer server to scan
     */
    function scanServer(currentServer, targetServer, previousServer = currentServer) {
        // ns.tprint(currentServer);
        if (currentServer == targetServer) {
            return [currentServer];
        } else {
            let availableServers = ns.scan(currentServer);

            for (let i = 0; i < availableServers.length; ++i) {
                let nextServer = availableServers[i];

                if (nextServer != currentServer && nextServer != previousServer) {
                    let result = scanServer(nextServer, targetServer, currentServer);

                    if (result != null) {
                        return [currentServer].concat(result);
                    }
                }
            }

            return null;
        }
    }

    let targetPath = scanServer('home', ns.args[0]);
    ns.tprint(targetPath);

    const terminalInput = doc.getElementById("terminal-input");
    const handler = Object.keys(terminalInput)[1];
    let backdoorCommand = '';

    for (let index = 1; index < targetPath.length; index++) {
        const server = targetPath[index];

        backdoorCommand += `connect ${server}; `;
    }

    // ns.tprint(backdoorCommand);
    terminalInput.value = backdoorCommand;
    terminalInput[handler].onChange({ target: terminalInput });
    terminalInput[handler].onKeyDown({ key: 'Enter', preventDefault: () => null });

    backdoorCommand = 'run BruteSSH.exe; ';
    backdoorCommand += 'run FTPCrack.exe; ';
    backdoorCommand += 'run relaySMTP.exe; ';
    backdoorCommand += 'run HTTPWorm.exe; ';
    backdoorCommand += 'run SQLInject.exe; ';
    backdoorCommand += 'run NUKE.exe; ';
    backdoorCommand += 'backdoor';

    // ns.tprint(backdoorCommand);
    terminalInput.value = backdoorCommand;
    terminalInput[handler].onChange({ target: terminalInput });
    terminalInput[handler].onKeyDown({ key: 'Enter', preventDefault: () => null });
}