-- Copyright (C) 1983  by Xerox Corporation. All rights reserved. 
-- PupTimeServerCold.mesa, HGM, 23-Sep-83  3:00:54

DIRECTORY
  Event USING [aboutToSwap],
  EventTypes USING [aboutToBoot, aboutToBootPhysicalVolume],
  Supervisor USING [
    AddDependency, AgentProcedure, CreateSubsystem, RemoveDependency,
    SubsystemHandle],

  MiscServerDefs USING [
    PupMiscServerOn, PupMiscServerOff, IgnoreThisPacket, SetTimeServer],
  PupTimeServer USING [],
  PupTimeServerOps USING [PupTimeServer],
  Stats USING [
    StatCounterIndex, StatsGetCounters, StatsStringToIndex];

PupTimeServerCold: PROGRAM
  IMPORTS
    Event, Supervisor,
    MiscServerDefs, PupTimeServerOps, Stats
  EXPORTS PupTimeServer, PupTimeServerOps =
  BEGIN OPEN Stats;

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

  useCount: CARDINAL ← 0;
  pleaseStop, running: PUBLIC BOOLEAN ← FALSE;
  resetText: PUBLIC LONG STRING ← [50];

  stats: POINTER TO ARRAY StatCounterIndex OF LONG CARDINAL ← StatsGetCounters[];
  statAlto, statTenex, statText: PUBLIC StatCounterIndex;


  GetAltoTimeRequests: PUBLIC PROCEDURE RETURNS [LONG CARDINAL] =
    BEGIN
    RETURN[stats[statAlto]];
    END;
    
  GetTenexTimeRequests: PUBLIC PROCEDURE RETURNS [LONG CARDINAL] =
    BEGIN
    RETURN[stats[statTenex]];
    END;
    
  GetTextTimeRequests: PUBLIC PROCEDURE RETURNS [LONG CARDINAL] =
    BEGIN
    RETURN[stats[statText]];
    END;

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

  Starter: PROCEDURE =
    BEGIN
    MiscServerDefs.PupMiscServerOn[];
    MiscServerDefs.SetTimeServer[PupTimeServerOps.PupTimeServer];
    pleaseStop ← FALSE;
    END;

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

  Stopper: PROCEDURE =
    BEGIN
    MiscServerDefs.PupMiscServerOff[];
    MiscServerDefs.SetTimeServer[MiscServerDefs.IgnoreThisPacket];
    pleaseStop ← TRUE;
    END;


  SetupTimeServerThings: PUBLIC PROCEDURE =
    BEGIN
    statText ← StatsStringToIndex["Text Date Requests"];
    statTenex ← StatsStringToIndex["Tenex Date Requests"];
    statAlto ← StatsStringToIndex["Alto Date Requests"];
    END;

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

  SetupTimeServerThings[];
  END.