/**
 * The entry point: read the environment, build the app, bind the socket.
 *
 * It binds `127.0.0.1` by default and is meant to stay there — Caddy terminates
 * TLS and is the only thing that talks to this port. A container sets
 * `TERA_HOST=0.0.0.0` because inside a container the loopback interface is a
 * different loopback interface, which is the only reason that knob exists.
 *
 * Nothing is fetched at boot. A source is contacted the first time somebody asks
 * for it, so this process is up and answering health before it has any opinion
 * about the weather.
 */

import { buildApp } from "./app.ts";
import { loadConfig } from "./config.ts";

const config = loadConfig();
const app = buildApp(config);

try {
  await app.listen({ host: config.host, port: config.port });
} catch (err) {
  app.log.error({ err }, `could not bind ${config.host}:${config.port}`);
  process.exit(1);
}

for (const signal of ["SIGINT", "SIGTERM"] as const) {
  // `once`, not `on`: a second SIGTERM during a shutdown should kill the process
  // outright rather than start a second shutdown.
  process.once(signal, () => {
    app.log.info(`${signal} — closing`);
    void app.close().then(() => process.exit(0));
  });
}
