; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "WP2LaTeX"
#define MyAppVersion "4.3"
#define MyAppPublisher "F&T Soft"
#define MyAppURL "http://www.penguin.cz/~fojtik/wp2latex/"

[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{849B528F-3F66-427c-9015-7710922339CA}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
UsePreviousAppDir=yes
DefaultGroupName={#MyAppName}
OutputDir=output_file
OutputBaseFilename=WP2LaTeX_Installer-{#MyAppVersion}
Compression=lzma
SolidCompression=yes
Uninstallable=yes
AppendDefaultDirName=yes
AppMutex=WP2LaTeX_Mutex,Global\WP2LaTeX_Mutex
;SetupIconFile 

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"

[Types]
Name: "full"; Description: "Full installation"
Name: "custom"; Description: "Custom installation"; Flags: iscustom

[Components]
Name: "gui"; Description: "Main Files - GUI"; Types: full custom
Name: "command_line"; Description: "Command line"; Types: full
; TODO: Name: "database"; Description: "Database server"; Types: full

[Tasks]
Name: desktopicon; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:"; Components: gui
Name: desktopicon\common; Description: "For all users"; GroupDescription: "Additional icons:"; Components: gui; Flags: exclusive
Name: desktopicon\user; Description: "For the current user only"; GroupDescription: "Additional icons:"; Components: gui; Flags: exclusive unchecked
; TODO: Name: quicklaunchicon; Description: "Create a &Quick Launch icon"; GroupDescription: "Additional icons:"; Components: main; Flags: unchecked


[Files]
Source: "..\cpp_builder\WP2LaTexGUI.exe"; DestDir: "{app}"; Components: gui; Flags: ignoreversion
Source: "..\msvc\Win32\Release_PNG_Gtxt\wp2latex.exe"; DestDir: "{app}"; Components: command_line; Flags: ignoreversion
;Source: "..\input_files\system32\GDS32.DLL"; DestDir: "{sys}"; Components: gui service; Flags: sharedfile
Source: "..\doc\locale\CS\lc_messages\WP2LaTeX.mo"; DestDir: "{app}\locale\CS\lc_messages"; Components: gui command_line; Flags: ignoreversion
Source: "..\doc\locale\DE\lc_messages\WP2LaTeX.mo"; DestDir: "{app}\locale\DE\lc_messages"; Components: gui command_line; Flags: ignoreversion
Source: "..\doc\wp2latex.pdf "; DestDir: "{app}"; Components: gui command_line; Flags: ignoreversion
Source: "..\styles.tex\accents.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\BoxedEPSF.tex"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\cyracc.def"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\cyrillic.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\endnotes.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\InputPS.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\ulem.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\wasyfont.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\styles.tex\WP2LaTeX.sty"; DestDir: "{app}\styles"; Flags: ignoreversion
Source: "..\help\WP2LaTeX.chm"; DestDir: "{app}"; Components: gui; Flags: ignoreversion
;// ini file contents will be transferred to this file


[InstallDelete]
Type: files; Name: "{app}\WIN_WP2L_main.exe"


[Run]

[UninstallRun]

[Dirs]

[Icons]
Name: "{group}\WP2LaTeX"; Filename: "{app}\WP2LaTexGUI.exe"
Name: "{group}\Manual"; Filename: "{app}\wp2latex.pdf"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"
Name: "{userdesktop}\WP2LaTeX"; Filename: "{app}\WP2LaTexGUI.exe"; Tasks: desktopicon\user
Name: "{commondesktop}\WP2LaTeX"; Filename: "{app}\WP2LaTexGUI.exe"; Tasks: desktopicon\common


[Registry]
Root: HKLM; Subkey: "SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WP2LaTexGUI.exe"; ValueType: string; ValueName: ""; ValueData: "{app}\WP2LaTexGUI.exe"; Flags: uninsdeletekey


[INI]


[CustomMessages]
MikTeX_form_Caption=Specify Path to MikTeX
MikTeX_form_Description=Where is MikTeX located?
MikTeX_form_Label1_Caption0=Select the folder in which MikTeX is located, then click Next. To skip MiKTeX integration, leave this editbox empty.
MikTeX_form_Checkbox1_Caption0=Use MikTeX
MikTeX_form_Label2_Caption0=Specify path to MiKTeX directory:
MikTeX_form_Button_Caption0=Browse ...


[Code]


function SearchForMikTex: string;
var  
  str: String;
  NameFound: String;
  FindRec: TFindRec;
begin
  NameFound := '';
  Result := '';  

     // Try to find the highest version of MikTeX.  

  if IsWin64() then begin
    str := ExpandConstant('{pf32}') + '\';
    //MsgBox(str, mbInformation, MB_OK);
    if FindFirst(ExpandConstant(str+'MiKTeX*'), FindRec) then begin
      repeat
        // Look only for directories
        if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then
        begin
          if FindRec.Name > NameFound then
            NameFound := FindRec.Name;
            Result := str + NameFound;
        end
      until not FindNext(FindRec);    
    end
    FindClose(FindRec);

    str := ExpandConstant('{pf64}') + '\';
    //MsgBox(str, mbInformation, MB_OK);
    if FindFirst(ExpandConstant(str+'MiKTeX*'), FindRec) then begin
      repeat
        // Look only for directories
        if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then
        begin
          if FindRec.Name > NameFound then
            NameFound := FindRec.Name;
            Result := str + NameFound;
        end
      until not FindNext(FindRec);    
    end
    FindClose(FindRec);
  end
  else begin
    str := ExpandConstant('{pf}') + '\';
    //MsgBox(str, mbInformation, MB_OK);
    if FindFirst(ExpandConstant(str+'MiKTeX*'), FindRec) then begin
      repeat
        // Look only for directories
        if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then
        begin
        if FindRec.Name > NameFound then
          NameFound := FindRec.Name;
          Result := str + NameFound;
        end
      until not FindNext(FindRec);    
    end
    FindClose(FindRec);
  end
  
end;


const EnvironmentKey = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';

function SearchForMikTex2: string;
var
    Paths: string;
    PathItem: string;
    P: Integer;
begin
  Result := '';
    { Retrieve current path (use empty string if entry not exists) }
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE, EnvironmentKey, 'Path', Paths) then
      Paths := '';

  while Paths <> '' do
  begin
    P := Pos(';',Paths);
    if P = 0 then begin
      PathItem := Paths;
      Paths := '';
    end
    else begin
      PathItem := Copy(Paths,1,P-1);
      Paths := Copy(Paths,P+1,Length(Paths));
    end

    //MsgBox(PathItem, mbInformation, MB_OK);
    P := Pos('MiKTeX-',PathItem);
    if P <> 0 then begin
      //MsgBox(PathItem, mbInformation, MB_OK);      
      P := Pos('\miktex\bin',PathItem);
      if P <> 0 then begin
        PathItem := Copy(PathItem,1,P-1);
        Result := PathItem;
        break;
      end      
    end
    
  end
end;



var
  MikTeX_Label1: TLabel;
  MikTeX_Label2: TLabel;
  MikTeX_Checkbox1: TCheckBox;
  MikTeX_Editbox1: TEdit;
  MikTeX_BtnBrowse: TButton;


function MikTeX_form_NextButtonClick(Page: TWizardPage): Boolean;
begin
  Result := True;
  if MikTeX_Checkbox1.checked then begin
    if MikTeX_Editbox1.Text='' then begin
    MsgBox('Please specify MiKTeX directory or uncheck checkbox.', mbError, MB_OK);    
    Result := False;
    end
  end
end;


procedure MikTeX_form_BrowseButtonClick(Sender: TObject);
var
  str: String;
begin
  str := MikTeX_Editbox1.Text;
  if BrowseForFolder('Select MiKTeX installation directory', str, false) then begin    
    MikTeX_Editbox1.Text := str;
  end;
end;


function MikTeX_form_CreatePage(PreviousPageId: Integer): Integer;
var
  Page: TWizardPage;  
  NameFound: String;

begin
  Page := CreateCustomPage(
    PreviousPageId,
    ExpandConstant('{cm:MikTeX_form_Caption}'),
    ExpandConstant('{cm:MikTeX_form_Description}')
  );

  MikTeX_Label1 := TLabel.Create(Page);
  with MikTeX_Label1 do
  begin
    Parent := Page.Surface;
    Caption := ExpandConstant('{cm:MikTeX_form_Label1_Caption0}');
    WordWrap:= true;
    Left := ScaleX(0);
    Top := ScaleY(0);
    Width := Page.SurfaceWidth;
    Height := ScaleY(40);
  end;

  MikTeX_Checkbox1 := TCheckBox.Create(Page);
  with MikTeX_Checkbox1 do
  begin
    Parent := Page.Surface;
    Caption := ExpandConstant('{cm:MikTeX_form_Checkbox1_Caption0}');
    Left := ScaleX(0);
    Top := ScaleY(40);
    Width := ScaleX(84);
    Height := ScaleY(17);
  end;

  MikTeX_Label2 := TLabel.Create(Page);
  with MikTeX_Label2 do
  begin
    Parent := Page.Surface;
    Caption := ExpandConstant('{cm:MikTeX_form_Label2_Caption0}');
    Left := ScaleX(0);
    Top := ScaleY(70);
    Width := ScaleX(300);
    Height := ScaleY(17);
  end;

  MikTeX_Editbox1 := TEdit.Create(Page);
  with MikTeX_Editbox1 do
  begin
    Parent := Page.Surface;
    Left := ScaleX(0);
    Top := ScaleY(88);
    Width := Page.SurfaceWidth;
    Height := ScaleY(25);
    TabOrder := 0;
    //Text := ExpandConstant('{cm: authentication_form_ServerNameEdit_Text0}');
  end;
  
  MikTeX_BtnBrowse := TButton.Create(Page);
  with MikTeX_BtnBrowse do
  begin
    Parent := Page.Surface;
    Caption := ExpandConstant('{cm:MikTeX_form_Button_Caption0}');
    Left := ScaleX(180);
    Top := ScaleY(112);
    Width := ScaleX(70);
    Height := ScaleY(20);
    OnClick := @MikTeX_form_BrowseButtonClick;
  end;

  NameFound := SearchForMikTex;
  if NameFound = '' then begin
    NameFound := SearchForMikTex2;
  end

  if NameFound<>'' then begin    
    MikTeX_Editbox1.Text := NameFound + '\';
    MikTeX_Checkbox1.Checked := true;
  end

  with Page do
  begin
    OnNextButtonClick := @MikTeX_form_NextButtonClick;
  end;

  Result := Page.ID;
end;



// This procedure adds a new dialog for entering a path to isql.exe
procedure InitializeWizard;
begin
  MikTeX_form_CreatePage(wpSelectDir);
end;


// Copy wp2latex.sty into a MiKTeX and rehash styles.
procedure CurStepChanged(CurStep: TSetupStep);
var
  source: string;
  destination: string;
  ResultCode: Integer;
  MiKTeX: string;
begin
  if CurStep = ssPostInstall then begin
    if MikTeX_Checkbox1.checked and (MikTeX_Editbox1.Text<>'') then begin

    MiKTeX := MikTeX_Editbox1.Text;
    if MiKTeX[length(MiKTeX)]<>'\' then MiKTeX := MiKTeX + '\';

    destination := MiKTeX + 'tex\latex\wp2latex';
    ForceDirectories(destination);

    source := ExpandConstant('{app}\styles\WP2LaTeX.sty');
    destination := MiKTeX + 'tex\latex\wp2latex\WP2LaTeX.sty';
    //MsgBox(source, mbInformation, MB_OK);
    //MsgBox(destination, mbInformation, MB_OK);
    FileCopy(source,destination,false);

    source := MiKTeX + 'miktex\bin\initexmf.exe';

    if not (FileExists(source)) then
    begin
      source := MiKTeX + 'miktex\bin\x64\initexmf.exe';
      if not (FileExists(source)) then
      begin
        source := 'initexmf.exe';
        if not GetOpenFileName('Please choose manually initexmf.exe', source, MiKTeX, '(*.exe)|*.exe', 'exe') then
        begin
          source := '';
        end
      end
    end
    

    //MsgBox(source, mbInformation, MB_OK);
    if source<>'' then
    begin
      if Exec(source, '--admin --update-fndb', '', SW_SHOW,  ewWaitUntilTerminated, ResultCode) then begin
         // handle success if necessary; ResultCode contains the exit code
        end
        else begin // handle failure if necessary; ResultCode contains the error code
          MsgBox('Cannot rehash LaTeX styles, please do it manually.', mbError, MB_OK);        
        end
      end
    end
  end
end;
