-- Copyright (C) 1984  by Xerox Corporation. All rights reserved. 
-- PupNameServerCold.mesa, HGM,  2-Sep-84  4:21:35

DIRECTORY
  Event USING [aboutToSwap],
  EventTypes USING [aboutToBoot, aboutToBootPhysicalVolume],
  Process USING [Pause, MsecToTicks],
  Runtime USING [IsBound],
  Supervisor USING [
    AddDependency, AgentProcedure, CreateSubsystem, RemoveDependency,
    SubsystemHandle],

  MiscServerDefs USING [
    PupMiscServerOn, PupMiscServerOff, IgnoreThisPacket, SetNameServer],
  NameServerDefs USING [
    busy, CloseDirectoryFiles, OpenDirectoryFiles, PupDirServerOn, PupNameServer,
    UpdatePicture];

PupNameServerCold: PROGRAM
  IMPORTS Event, Process, Runtime, Supervisor, MiscServerDefs, NameServerDefs
  EXPORTS NameServerDefs =
  BEGIN

  useCount: CARDINAL ← 0;
  nameRunning: PUBLIC BOOLEAN ← FALSE;

  broom: Supervisor.SubsystemHandle = Supervisor.CreateSubsystem[Broom];

  PupNameServerOn: PUBLIC PROCEDURE =
    BEGIN
    IF (useCount ← useCount + 1) = 1 THEN
      BEGIN
      Supervisor.AddDependency[client: broom, implementor: Event.aboutToSwap];
      nameRunning ← TRUE;
      Starter[];
      END;
    MaybeUpdatePicture[];
    END;

  Starter: PROCEDURE =
    BEGIN
    MiscServerDefs.PupMiscServerOn[];
    NameServerDefs.OpenDirectoryFiles[];
    MiscServerDefs.SetNameServer[NameServerDefs.PupNameServer];
    END;

  PupNameServerOff: PUBLIC PROCEDURE =
    BEGIN
    IF useCount # 0 AND (useCount ← useCount - 1) = 0 THEN
      BEGIN
      nameRunning ← FALSE;
      Stopper[];
      Supervisor.RemoveDependency[client: broom, implementor: Event.aboutToSwap];
      END;
    MaybeUpdatePicture[];
    END;

  Stopper: PROCEDURE =
    BEGIN
    MiscServerDefs.SetNameServer[MiscServerDefs.IgnoreThisPacket];
    MiscServerDefs.PupMiscServerOff[];
    NameServerDefs.CloseDirectoryFiles[];
    WHILE NameServerDefs.busy DO Process.Pause[Process.MsecToTicks[1000]]; ENDLOOP;
    END;

  MaybeUpdatePicture: PROCEDURE =
    BEGIN
    IF Runtime.IsBound[LOOPHOLE[NameServerDefs.UpdatePicture]] THEN
      NameServerDefs.UpdatePicture[];
    END;

  Broom: Supervisor.AgentProcedure =
    BEGIN
    SELECT event FROM
      EventTypes.aboutToBoot, EventTypes.aboutToBootPhysicalVolume =>
        IF nameRunning THEN Stopper[];
      ENDCASE => NULL;
    END;

  -- AutoStartup
  PupNameServerOn[];
  NameServerDefs.PupDirServerOn[];
  END.