new object $daemon: $network;

var $daemon connection = 0;
var $daemon default_port = 9000;
var $daemon current_port = 0;
var $daemon next_connection = 0;
var $daemon port = 0;
var $root inited = 1;

driver method .connect() {
  arg remote, local, port;
  var new;

  // An incoming connection was received.  Spawn off a new $connection
  // and pass off to it.
  new = connection.spawn();
  reassign_connection(new);
  new.new(local, remote, port);
};

public method .port() {
  return current_port;
};

public method .shutdown() {
  arg [args];

  (> .stop_listening() <);
  connection.daemon_shutdown();
};

public method .start_listening() {
  arg [port];

  (| .stop_listening() |);
  current_port = [@port, default_port][1];
  (> bind_port(current_port) <);
  .log("** Starting " + .objname() + " on port " + current_port + " **");
};

public method .startup() {
  arg [args];
  var opt;

  if (caller() != $sys) {
    throw(~perm, "Caller is not $sys");
  }
  catch any {
    (> .start_listening() <);
  } with {
    switch (error()) {
      case ~bind:
	.log(("** Unable to bind to port " + tostr(port)) + "! **");
      default:
	.log($parse_lib.traceback(traceback()));
    }
  }
};

public method .stop_listening() {
  arg [port];

  unbind_port(current_port);
};