package de.steamwar.commands.profiler

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.help
import com.github.ajalt.clikt.parameters.arguments.optional
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.int

const val SPARK = "/jars/spark.jar"

class ProfilerCommand : CliktCommand("profiler") {
    val pid by argument().help("Process id").int().optional()
    val port by option("--port", "-p").int().default(8543)

    override fun run() {
        if (pid != null) {
            ProcessBuilder()
                .command("java", "-jar", SPARK, pid.toString(), "port=$port")
                .start()
                .waitFor()

            Thread.sleep(1000)

            ProcessBuilder()
                .command("ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-p", port.toString(), "spark@localhost")
                .inheritIO()
                .start()
                .waitFor()
        } else {
            ProcessBuilder()
                .command("java", "-jar", SPARK)
                .inheritIO()
                .start()
                .waitFor()
        }
    }

    override fun help(context: Context): String =
        "Start a profiler"
}