unit uAppInit;

interface

procedure PhiAppInit;

implementation

uses
{$IFDEF LINUX}
  Types,
{$ENDIF}
{$IFDEF MSWINDOWS}
  Windows, ShellAPI,
  uAppPath,
{$ENDIF}
  SysUtils,
  Rubies;

var
  Phi_inited: Boolean = False;

function GetRubyLib: string;
var
  Buf: array[0..4095] of Char;
begin
  Buf[0] := #0;
{$IFDEF MSWINDOWS}
  GetEnvironmentVariable(PChar('RUBYLIB'), Buf, SizeOf(Buf));
{$ENDIF}
  Result := Buf;
end;

function ExtractUNIXFileDir(S: string): string;
begin
  Result := ExtractFileDir(S);
  Result := StringReplace(Result, '\', '/', [rfReplaceAll]);
  Result := AnsiLowerCase(Result);
end;

procedure PhiAppInit;
label
  last;
var
  argc: Integer;
  argv: Pointer;
{$IFDEF MSWINDOWS}
  ProgDir, RubyBin, RubyLib: string;
{$ENDIF}
begin
  if Phi_inited then Exit;
  Phi_inited := True;
{$IFDEF LINUX}
  argc := ArgCount;
  argv := ArgValues;
{$ENDIF}
{$IFDEF MSWINDOWS}
  argv := CommandLineToArgvW(GetCommandLineW, argc);
  NtInitialize(@argc, @argv);
{$ENDIF}
  ruby_init;
{$IFDEF MSWINDOWS}
  ProgDir := ExtractUNIXFileDir(ParamStr(0));
  if Pos('/bin', ProgDir) = Length(ProgDir)-4+1 then
    ProgDir := Copy(ProgDir, 0, Length(ProgDir)-4);
  RubyBin := ExtractUNIXFileDir(GetAppPath('ruby_ap.exe'));
  if RubyBin = '' then goto last;
  RubyLib := GetRubyLib;
  if RubyLib = '' then
    SetEnvironmentVariable(PChar('RUBYLIB'), PChar(RubyBin))
  else
    SetEnvironmentVariable(PChar('RUBYLIB'), PChar(RubyLib+';'+RubyBin))
  ;
{$ENDIF}
last:
  if IsConsole then
    ruby_options(argc, argv)
  else begin
    ruby_init_loadpath;
{$IFDEF RUBY18}
    ruby_exec;
{$ENDIF}
  end;
end;

end.
