with Interfaces.C, POSIX.IO, POSIX.Unsafe_Process_Primitives;

with EUP.Sockets, Fork, GNAT.Sockets, GNAT.Sockets.Compatibility, Wait;

procedure Forking_Time_Server is
   procedure Process_Request (Connection : in GNAT.Sockets.Socket_Type) is
      use type Interfaces.C.int;
      File, New_File : POSIX.IO.File_Descriptor;
   begin
      case Fork is
         when -1 =>
            return;
         when 0 =>
            File := GNAT.Sockets.Compatibility.POSIX_File_Descriptor
              (Connection);
            New_File :=
              POSIX.IO.Duplicate_And_Close (File,
                                            POSIX.IO.Standard_Output);
            POSIX.IO.Close (File);
            POSIX.Unsafe_Process_Primitives.Exec ("/bin/date");
         when others =>
            declare
               Process_ID : Interfaces.C.int;
               Status     : aliased Interfaces.C.int;
            begin
               Process_ID := Wait (Status'Access);
            end;
      end case;
   end Process_Request;

   Receiver, Connection : GNAT.Sockets.Socket_Type;
   Client               : GNAT.Sockets.Sock_Addr_Type;
begin
   Receiver := EUP.Sockets.Make_Server (Port => 14_000);
   loop
      GNAT.Sockets.Accept_Socket (Server  => Receiver,
                                  Socket  => Connection,
                                  Address => Client);
      Process_Request (Connection);
      GNAT.Sockets.Close_Socket (Socket => Connection);
   end loop;
end Forking_Time_Server;

