package launchers

import java.lang.management.ManagementFactory

private data class SupervisorLauncher(
    val displayName: String,
    val executablePath: String,
)

private const val SUPERVISOR_PROTOCOL = "minecraft-server-supervisor-v1"

private val minecraftServerJava =
    SupervisorLauncher(
        displayName = "Minecraft Java systemd supervisor",
        executablePath = "/usr/libexec/minecraft-server-java-supervisor",
    )

private val minecraftServerFabric =
    SupervisorLauncher(
        displayName = "Minecraft Fabric systemd supervisor",
        executablePath = "/usr/libexec/minecraft-server-fabric-supervisor",
    )

object MinecraftServerJavaMain {
    @JvmStatic
    fun main(args: Array<String>) = launchSupervisor(minecraftServerJava, args)
}

object MinecraftServerFabricMain {
    @JvmStatic
    fun main(args: Array<String>) = launchSupervisor(minecraftServerFabric, args)
}

private fun launchSupervisor(
    launcher: SupervisorLauncher,
    args: Array<String>,
) {
    val jvmArguments = ManagementFactory.getRuntimeMXBean().inputArguments
    val command = supervisorCommand(launcher.executablePath, javaExecutable(), jvmArguments, args)
    exec(launcher.displayName, command)
}

internal fun supervisorCommand(
    executable: String,
    javaExecutable: String,
    jvmArguments: List<String>,
    applicationArguments: Array<String>,
): List<String> =
    buildList {
        add(executable)
        add(SUPERVISOR_PROTOCOL)
        add(javaExecutable)
        add(jvmArguments.size.toString())
        addAll(jvmArguments)
        addAll(applicationArguments)
    }
