import { Server } from "../../server/server"
import { cmd } from "./cmd"
import { withNetworkOptions, resolveNetworkOptions } from "../network"
import { Flag } from "@saeeol/core/flag/flag"
import { InstanceStore } from "../../project/instance-store" 

export const ServeCommand = cmd({
  command: "serve",
  builder: (yargs) => withNetworkOptions(yargs),
  describe: "starts a headless saeeol server", 
  handler: async (args) => {
    if (!Flag.SAEEOL_SERVER_PASSWORD) {
      console.log("Warning: SAEEOL_SERVER_PASSWORD is not set; server is unsecured.")
    }
    const opts = await resolveNetworkOptions(args)
    const server = await Server.listen(opts)
    console.log(`saeeol server listening on http://${server.hostname}:${server.port}`)
    const abort = new AbortController()
    const shutdown = async () => {
      try {
        await InstanceStore.disposeAllInstances()
        await server.stop(true)
      } finally {
        abort.abort()
      }
    }
    process.on("SIGTERM", shutdown)
    process.on("SIGINT", shutdown)
    process.on("SIGHUP", shutdown)
    await new Promise((resolve) => abort.signal.addEventListener("abort", resolve))
  },
})
