with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Command_Line;

procedure Get_GCC
is
   use Ada.Strings.Fixed;
   use Ada.Text_IO;
   use Ada.Command_Line;

   function Get_GCC_Name
     (From : in String)
     return String
   is
      F      : File_Type;
      Buffer : String (1 ..  500);
      Last   : Natural;
      I      : Natural;
   begin
      Open (F, In_File, From);
      Get_Line (F, Buffer, Last);
      Close (F);
      I := Index (Buffer (1 .. Last), " ");
      if I > 0 then
         return Buffer (1 .. I - 1);
      else
         return "gcc";
      end if;
   exception
      when others =>
         if Is_Open (F) then Close (F); end if;
         return "gcc";
   end Get_GCC_Name;

   procedure Create_File
     (GCC : in String)
   is
      F : File_Type;
   begin
      begin
         Create (F, Out_File, "ad-setup.ads");
      exception
         when others =>
            Open (F, Out_File, "ad-setup.ads");
      end;
      Put_Line
        (F, "--  This file has been automatically generated.");
      New_Line (F);
      Put_Line
        (F, "pragma License (GPL);");
      New_Line (F);
      Put_Line
        (F, "package AD.Setup is");
      New_Line (F);
      Put_Line
        (F, "   pragma Pure;");
      New_Line (F);
      Put_Line
        (F, "   GNAT_Name : constant String;");
      New_Line (F);
      Put_Line
        (F, "private");
      New_Line (F);
      Put_Line
        (F, "   GNAT_Name : constant String :=");
      Put_Line
        (F, "     """ & GCC & """;");
      New_Line (F);
      Put_Line
        (F, "end AD.Setup;");
      Close (F);
   exception
      when others =>
         if Is_Open (F) then Close (F); end if;
         raise;
   end Create_File;

begin
   if Argument_Count /= 2 then
      Set_Exit_Status (Failure);
      return;
   end if;
   if Argument (1) = "-gcc" then
      Put (Get_GCC_Name (Argument (2)));
      Set_Exit_Status (Success);
   elsif Argument (1) = "-setup" then
      Create_File (Get_GCC_Name (Argument (2)));
      Set_Exit_Status (Success);
   else
      Set_Exit_Status (Failure);
   end if;
exception
   when others =>
      Set_Exit_Status (Failure);
end Get_GCC;


