-- File: GateControlFinish.mesa,  Last Edit: HGM  October 18, 1980  11:56 PM

DIRECTORY
  Ascii USING [CR],
  Process USING [Detach],
  String USING [AppendString, AppendChar],
  Time USING [AppendCurrent],

  File USING [Capability, nullCapability],
  George USING [
    CreateAppendStream, Destroy, Handle, LookupExistingFile, NameToCapability,
    PutChar],

  Put USING [Line],
  TajoMisc USING [Quit],

  GateControlDefs USING [msg],
  PupDefs USING [AppendHostName, PupBuffer, PupAddress];

GateControlFinish: MONITOR
  IMPORTS Process, String, Time, George, Put, TajoMisc, PupDefs, GateControlDefs
  EXPORTS GateControlDefs =
  BEGIN

  verbose: BOOLEAN = TRUE;

  restarting: BOOLEAN ← FALSE;

  RestartGateway: PUBLIC ENTRY PROCEDURE [b: PupDefs.PupBuffer] =
    BEGIN
    IF restarting THEN RETURN;
    restarting ← TRUE;
    Process.Detach[FORK Restart[b.source, TRUE]];
    END;

  HaltGateway: PUBLIC ENTRY PROCEDURE [b: PupDefs.PupBuffer] =
    BEGIN
    IF restarting THEN RETURN;
    restarting ← TRUE;
    Process.Detach[FORK Restart[b.source, FALSE]];
    END;

  Restart: ENTRY PROCEDURE [who: PupDefs.PupAddress, restart: BOOLEAN] =
    BEGIN
    sh: George.Handle;
    dally: CONDITION;
    StuffCommand: PROCEDURE [s: STRING] =
      BEGIN
      i: CARDINAL;
      FOR i IN [0..s.length) DO George.PutChar[sh, s[i]]; ENDLOOP;
      George.PutChar[sh, Ascii.CR];
      END;
    IF verbose THEN
      BEGIN
      text: STRING = [100];
      Time.AppendCurrent[text];
      String.AppendString[text, "  Gateway "L];
      String.AppendString[text, IF restart THEN "restarted"L ELSE "halted"L];
      String.AppendString[text, " by "L];
      PupDefs.AppendHostName[text, who];
      String.AppendChar[text, '.];
      LogString[text];
      END;
    -- Pause a while to be sure that GateControl gets the ack.
    THROUGH [0..3) DO WAIT dally; ENDLOOP;
    sh ← George.CreateAppendStream[George.NameToCapability["Rem.cm"L, 1]];
    George.PutChar[sh, Ascii.CR];
    George.PutChar[sh, Ascii.CR];
    BEGIN
    file: File.Capability;
    file ← George.LookupExistingFile["NewGateway.image"L];
    IF file # File.nullCapability THEN
      BEGIN
      StuffCommand["Delete Gateway.image"L];
      StuffCommand["Rename NewGateway.image Gateway.image"L];
      END;
    END;
    StuffCommand[IF restart THEN "Gateway"L ELSE "// Gateway Halted"L];
    George.Destroy[sh];
    TajoMisc.Quit[];
    END;

  LogString: PROCEDURE [text: STRING] =
    BEGIN
    IF GateControlDefs.msg # NIL THEN Put.Line[GateControlDefs.msg, text];
    Put.Line[NIL, text];
    END;

  END.