-- who2.adb - read /etc/utmp and list info therein
--          - suppresses empty records
--          - formats time nicely

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

procedure Who is
   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;
   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;

   package UTMP_IO is new Ada.Direct_IO (EUP.UTMP.Instance);
   use UTMP_IO;
   Current_Record : EUP.UTMP.Instance;
   UTMP_File      : UTMP_IO.File_Type;
begin
   Open (File => UTMP_File,
         Name => EUP.UTMP.File_Name,
         Mode => In_File);

   while not End_Of_File (UTMP_File) loop
      Read (File => UTMP_File,
            Item => Current_Record);
      Show (Item => Current_Record);
   end loop;

   Close (File => UTMP_File);
end Who;

