export const onExit = (cb: () => void) => {
  /*
  const origCb = cb;
  cb = () => {
    origCb();
    console.log("finished");
  };
  */
  const cbAndExit = () => {
    cb();
    process.exit();
  };

  const exitSignals = [
    "SIGINT",
    "SIGTERM",
    "uncaughtException",
    "SIGUSR1",
    "SIGUSR2",
  ];
  const cbSignals = ["beforeExit"];

  for (const signal of exitSignals) {
    process.on(signal, cbAndExit);
  }
  for (const signal of cbSignals) {
    process.on(signal, cb);
  }

  return () => {
    for (const signal of exitSignals) {
      process.off(signal, cbAndExit);
    }
    for (const signal of cbSignals) {
      process.off(signal, cb);
    }
  };
};
