-- who3.adb - read /etc/utmp and list info therein
--          - suppresses empty records
--          - formats time nicely
--          - buffers input (using UTMP_Buffer)

with Ada.Text_IO;
with Interfaces.C;
with Interfaces.C.Strings;
with POSIX;
with POSIX.C;
with EUP.Strings;
with EUP.UTMP;
with UTMP_Buffer;

procedure Who is
   package Time_Text_IO is new Ada.Text_IO.Integer_IO (POSIX.C.time_t);

   procedure Show (Item : in     POSIX.C.time_t) is
      use Ada.Text_IO;
      use Interfaces.C;
      use Interfaces.C.Strings;

      function ctime (timep : access POSIX.C.time_t) return chars_ptr;
      pragma Import (C, ctime);

      Buffer : aliased POSIX.C.time_t := Item;
   begin
      Put (Value (ctime (Buffer'Access)) (5 .. 16));
   end Show;

   procedure Show (Item : in     EUP.UTMP.Instance) is
      use Ada.Text_IO;
      use EUP.Strings;
      use EUP.UTMP;
      use Time_Text_IO;
   begin
      if Item.Login_Type = User_Process then
         Put (Format (Item.User, Width => 8));
         Put (" ");
         Put (Format (Item.Line, Width => 8));
         Put (" ");
         Show (Item.TV.tv_sec);
         if To_Ada_String (Item.Host)'Length > 0 then
            Put (" (" & To_Ada_String (Item.Host) & ")");
         end if;
         New_Line;
      end if;
   end Show;

   Current_Record : EUP.UTMP.Instance;
begin
   for Counter in 1 .. 10_000 loop
   UTMP_Buffer.Open (Name => EUP.UTMP.File_Name);

   while not UTMP_Buffer.End_Of_File loop
      Current_Record := UTMP_Buffer.Next;
      Show (Item => Current_Record);
   end loop;

   UTMP_Buffer.Close;
   end loop;
end Who;

