fixed #136, #162 Сделал выборочную установку, по умолчанию исключены компоненты Снегопата и TestApp

#include <ISPPBuiltins.iss>
#define AppName "OneScript engine"
#define FSFriendlyName "OneScript"
#define MainExe "TestApp.exe"

#define VerMajor
#define VerMinor
#define VerRelease
#define Build
#expr ParseVersion("build\bin\ScriptEngine.dll",VerMajor,VerMinor,VerRelease,Build)

[Setup]
AppName={#AppName}
AppVersion={#VerMajor}.{#VerMinor}.{#VerRelease}
AppPublisher=1Script Team (Open Source)
DefaultDirName="{pf}\{#FSFriendlyName}"
DefaultGroupName="{#FSFriendlyName}"
OutputBaseFilename="OneScript-{#VerMajor}.{#VerMinor}.{#VerRelease}-setup"
DisableProgramGroupPage=yes
UninstallDisplayIcon="{app}\bin\{#MainExe}"
Compression=lzma2
SolidCompression=yes
VersionInfoVersion={#VerMajor}.{#VerMinor}.{#VerRelease}.{#Build}

[InstallDelete]
Type: files; Name: {app}\*.dll
Type: files; Name: {app}\*.exe

[Types]
Name: "normal"; Description: "Стандартная установка"
Name: "custom"; Description: "Выборочная установка"; Flags: iscustom

[Components]
Name: "main"; Description: "Основные файлы"; Types: normal custom; Flags: fixed
Name: "stdlib"; Description: "Стандартная библиотека скриптов"; Types: normal custom;
Name: "testapp"; Description: "Тестовая консоль (TestApp)";
Name: "snegopat"; Description: "Интеграция со 'Снегопатом'";

[Files]
Source: "build\bin\oscript.exe"; DestDir: "{app}\bin"; Components: main
Source: "build\bin\ScriptEngine.HostedScript.dll"; DestDir: "{app}\bin"; Components: main
Source: "build\bin\ScriptEngine.dll"; DestDir: "{app}\bin"; Components: main
Source: "build\bin\Ionic.Zip.dll"; DestDir: "{app}\bin"; Components: main
Source: "build\bin\oscript.cfg"; DestDir: "{app}\bin"; Components: main; Flags: onlyifdoesntexist

Source: "build\examples\*"; DestDir: "{app}\examples"; Components: main

; снегопат
Source: "build\bin\ScriptEngine.Snegopat.dll"; DestDir: "{app}\bin"; Components: snegopat
; testapp
Source: "build\bin\TestApp.exe"; DestDir: "{app}\bin"; Components: testapp
Source: "build\bin\ICSharpCode.AvalonEdit.dll"; DestDir: "{app}\bin"; Components: testapp
; библиотека
Source: "build\lib\*"; DestDir: "{app}\lib"; Components: stdlib; Flags: recursesubdirs

Source: "dotNetFx40_Full_setup.exe"; DestDir: {tmp}; Flags: deleteafterinstall; Check: not IsRequiredDotNetDetected
Source: "vcredist_x86.exe"; DestDir: {tmp}; Flags: deleteafterinstall; Check: VCRedistNeedsInstall

[Icons]
Name: "{group}\{#FSFriendlyName}"; Filename: "{app}\bin\{#MainExe}"

[Registry]
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: expandsz; ValueName: "Path"; ValueData: "{olddata};{app}\bin;"; Check: NeedsAddPath(ExpandConstant('{app}\bin'))

[Run]
Filename: {tmp}\dotNetFx40_Full_setup.exe; Parameters: "/q:a /c:""install /l /q"""; Check: not IsRequiredDotNetDetected; StatusMsg: Microsoft .NET Framework 4.0 is being installed. Please wait..
Filename: {tmp}\vcredist_x86.exe; Parameters: "/q /norestart"; Components: snegopat; StatusMsg: MS Redistributable C++ Runtime is being installed. Please wait..
Filename: "{app}\bin\{#MainExe}"; Description: "Launch application"; Components: testapp; Flags: postinstall nowait skipifsilent unchecked

[Code]

#IFDEF UNICODE
  #DEFINE AW "W"
#ELSE
  #DEFINE AW "A"
#ENDIF
type
  INSTALLSTATE = Longint;
const
  INSTALLSTATE_INVALIDARG = -2;  // An invalid parameter was passed to the function.
  INSTALLSTATE_UNKNOWN = -1;     // The product is neither advertised or installed.
  INSTALLSTATE_ADVERTISED = 1;   // The product is advertised but not installed.
  INSTALLSTATE_ABSENT = 2;       // The product is installed for a different user.
  INSTALLSTATE_DEFAULT = 5;      // The product is installed for the current user.

  // Microsoft Visual C++ 2012 x86 Minimum Runtime - 11.0.61030.0 (Update 4)
  VC_2012_REDIST_MIN_UPD4_X86 = '{BD95A8CD-1D9F-35AD-981A-3E7925026EBB}';
  VC_2012_REDIST_MIN_UPD4_X64 = '{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}';
  // Microsoft Visual C++ 2012 x86 Additional Runtime - 11.0.61030.0 (Update 4)
  VC_2012_REDIST_ADD_UPD4_X86 = '{B175520C-86A2-35A7-8619-86DC379688B9}';
  VC_2012_REDIST_ADD_UPD4_X64 = '{37B8F9C7-03FB-3253-8781-2517C99D7C00}';

function NeedsAddPath(Param: string): boolean;
var
  OrigPath: string;
begin
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE,'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'Path', OrigPath)
  then begin
    Result := True;
    exit;
  end;
  // look for the path with leading and trailing semicolon
  // Pos() returns 0 if not found
  Result := Pos(';' + UpperCase(Param) + ';', ';' + UpperCase(OrigPath) + ';') = 0;
  if Result = True then
     Result := Pos(';' + UpperCase(Param) + '\;', ';' + UpperCase(OrigPath) + ';') = 0;
end;

function IsDotNetDetected(version: string; service: cardinal): boolean;
// Indicates whether the specified version and service pack of the .NET Framework is installed.
//
// version -- Specify one of these strings for the required .NET Framework version:
//    'v1.1.4322'     .NET Framework 1.1
//    'v2.0.50727'    .NET Framework 2.0
//    'v3.0'          .NET Framework 3.0
//    'v3.5'          .NET Framework 3.5
//    'v4\Client'     .NET Framework 4.0 Client Profile
//    'v4\Full'       .NET Framework 4.0 Full Installation
//    'v4.5'          .NET Framework 4.5
//
// service -- Specify any non-negative integer for the required service pack level:
//    0               No service packs required
//    1, 2, etc.      Service pack 1, 2, etc. required
var
    key: string;
    install, release, serviceCount: cardinal;
    check45, success: boolean;
//var reqNetVer : string;
begin
    // .NET 4.5 installs as update to .NET 4.0 Full
    if version = 'v4.5' then begin
        version := 'v4\Full';
        check45 := true;
    end else
        check45 := false;

    // installation key group for all .NET versions
    key := 'SOFTWARE\Microsoft\NET Framework Setup\NDP\' + version;

    // .NET 3.0 uses value InstallSuccess in subkey Setup
    if Pos('v3.0', version) = 1 then begin
        success := RegQueryDWordValue(HKLM, key + '\Setup', 'InstallSuccess', install);
    end else begin
        success := RegQueryDWordValue(HKLM, key, 'Install', install);
    end;

    // .NET 4.0/4.5 uses value Servicing instead of SP
    if Pos('v4', version) = 1 then begin
        success := success and RegQueryDWordValue(HKLM, key, 'Servicing', serviceCount);
    end else begin
        success := success and RegQueryDWordValue(HKLM, key, 'SP', serviceCount);
    end;

    // .NET 4.5 uses additional value Release
    if check45 then begin
        success := success and RegQueryDWordValue(HKLM, key, 'Release', release);
        success := success and (release >= 378389);
    end;

    result := success and (install = 1) and (serviceCount >= service);
end;

function IsRequiredDotNetDetected(): Boolean;
begin
    result := IsDotNetDetected('v4\Full', 0);
end;

function InitializeSetup(): Boolean;
begin
    if not IsDotNetDetected('v4\Full', 0) then begin
        MsgBox('{#AppName} requires Microsoft .NET Framework 4.0 Client Profile.'#13#13
          'The installer will attempt to install it', mbInformation, MB_OK);
    end;

    result := true;
end;

function MsiQueryProductState(szProduct: string): INSTALLSTATE;
  external 'MsiQueryProductState{#AW}@msi.dll stdcall';

function VCVersionInstalled(const ProductID: string): Boolean;
begin
  Result := MsiQueryProductState(ProductID) = INSTALLSTATE_DEFAULT;
end;

function VCRedistNeedsInstall: Boolean;
begin
  // here the Result must be True when you need to install your VCRedist
  // or False when you don't need to, so now it's upon you how you build
  // this statement, the following won't install your VC redist only when
  // the Visual C++ 2010 Redist (x86) and Visual C++ 2010 SP1 Redist(x86)
  // are installed for the current user
  Result := not (VCVersionInstalled(VC_2012_REDIST_MIN_UPD4_X86) and
    VCVersionInstalled(VC_2012_REDIST_ADD_UPD4_X86));
end;

#include <ISPPBuiltins.iss>
#define AppName "OneScript execution engine"
#define FSFriendlyName "OneScript"
#define MainExe "TestApp.exe"

#define VerMajor
#define VerMinor
#define VerRelease
#define Build
#expr ParseVersion("build\bin\ScriptEngine.dll",VerMajor,VerMinor,VerRelease,Build)

[Setup]
AppName={#AppName}
AppVersion={#VerMajor}.{#VerMinor}.{#VerRelease}
DefaultDirName="{pf}\{#FSFriendlyName}"
DefaultGroupName="{#FSFriendlyName}"
OutputBaseFilename="OneScript-{#VerMajor}.{#VerMinor}.{#VerRelease}-setup"
DisableProgramGroupPage=yes
UninstallDisplayIcon="{app}\bin\{#MainExe}"
Compression=lzma2
SolidCompression=yes
VersionInfoVersion={#VerMajor}.{#VerMinor}.{#VerRelease}.{#Build}

[InstallDelete]
Type: files; Name: {app}\*.dll
Type: files; Name: {app}\*.exe

[Files]
Source: "build\*"; DestDir: "{app}"; Excludes: "build\bin\oscript.cfg"; Flags: recursesubdirs
Source: "build\bin\oscript.cfg"; DestDir: "{app}\bin";  Flags: onlyifdoesntexist
Source: "dotNetFx40_Full_setup.exe"; DestDir: {tmp}; Flags: deleteafterinstall; Check: not IsRequiredDotNetDetected
Source: "vcredist_x86.exe"; DestDir: {tmp}; Flags: deleteafterinstall; Check: VCRedistNeedsInstall

[Icons]
Name: "{group}\{#FSFriendlyName}"; Filename: "{app}\bin\{#MainExe}"

[Registry]
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: expandsz; ValueName: "Path"; ValueData: "{olddata};{app}\bin;"; Check: NeedsAddPath(ExpandConstant('{app}\bin'))

[Run]
Filename: {tmp}\dotNetFx40_Full_setup.exe; Parameters: "/q:a /c:""install /l /q"""; Check: not IsRequiredDotNetDetected; StatusMsg: Microsoft .NET Framework 4.0 is being installed. Please wait..
Filename: {tmp}\vcredist_x86.exe; Parameters: "/q /norestart"; StatusMsg: MS Redistributable C++ Runtime is being installed. Please wait..
Filename: "{app}\bin\{#MainExe}"; Description: "Launch application"; Flags: postinstall nowait skipifsilent unchecked

[Code]

#IFDEF UNICODE
  #DEFINE AW "W"
#ELSE
  #DEFINE AW "A"
#ENDIF
type
  INSTALLSTATE = Longint;
const
  INSTALLSTATE_INVALIDARG = -2;  // An invalid parameter was passed to the function.
  INSTALLSTATE_UNKNOWN = -1;     // The product is neither advertised or installed.
  INSTALLSTATE_ADVERTISED = 1;   // The product is advertised but not installed.
  INSTALLSTATE_ABSENT = 2;       // The product is installed for a different user.
  INSTALLSTATE_DEFAULT = 5;      // The product is installed for the current user.

  // Microsoft Visual C++ 2012 x86 Minimum Runtime - 11.0.61030.0 (Update 4)
  VC_2012_REDIST_MIN_UPD4_X86 = '{BD95A8CD-1D9F-35AD-981A-3E7925026EBB}';
  VC_2012_REDIST_MIN_UPD4_X64 = '{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}';
  // Microsoft Visual C++ 2012 x86 Additional Runtime - 11.0.61030.0 (Update 4)
  VC_2012_REDIST_ADD_UPD4_X86 = '{B175520C-86A2-35A7-8619-86DC379688B9}';
  VC_2012_REDIST_ADD_UPD4_X64 = '{37B8F9C7-03FB-3253-8781-2517C99D7C00}';

function NeedsAddPath(Param: string): boolean;
var
  OrigPath: string;
begin
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE,'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'Path', OrigPath)
  then begin
    Result := True;
    exit;
  end;
  // look for the path with leading and trailing semicolon
  // Pos() returns 0 if not found
  Result := Pos(';' + UpperCase(Param) + ';', ';' + UpperCase(OrigPath) + ';') = 0;
  if Result = True then
     Result := Pos(';' + UpperCase(Param) + '\;', ';' + UpperCase(OrigPath) + ';') = 0;
end;

function IsDotNetDetected(version: string; service: cardinal): boolean;
// Indicates whether the specified version and service pack of the .NET Framework is installed.
//
// version -- Specify one of these strings for the required .NET Framework version:
//    'v1.1.4322'     .NET Framework 1.1
//    'v2.0.50727'    .NET Framework 2.0
//    'v3.0'          .NET Framework 3.0
//    'v3.5'          .NET Framework 3.5
//    'v4\Client'     .NET Framework 4.0 Client Profile
//    'v4\Full'       .NET Framework 4.0 Full Installation
//    'v4.5'          .NET Framework 4.5
//
// service -- Specify any non-negative integer for the required service pack level:
//    0               No service packs required
//    1, 2, etc.      Service pack 1, 2, etc. required
var
    key: string;
    install, release, serviceCount: cardinal;
    check45, success: boolean;
//var reqNetVer : string;
begin
    // .NET 4.5 installs as update to .NET 4.0 Full
    if version = 'v4.5' then begin
        version := 'v4\Full';
        check45 := true;
    end else
        check45 := false;

    // installation key group for all .NET versions
    key := 'SOFTWARE\Microsoft\NET Framework Setup\NDP\' + version;

    // .NET 3.0 uses value InstallSuccess in subkey Setup
    if Pos('v3.0', version) = 1 then begin
        success := RegQueryDWordValue(HKLM, key + '\Setup', 'InstallSuccess', install);
    end else begin
        success := RegQueryDWordValue(HKLM, key, 'Install', install);
    end;

    // .NET 4.0/4.5 uses value Servicing instead of SP
    if Pos('v4', version) = 1 then begin
        success := success and RegQueryDWordValue(HKLM, key, 'Servicing', serviceCount);
    end else begin
        success := success and RegQueryDWordValue(HKLM, key, 'SP', serviceCount);
    end;

    // .NET 4.5 uses additional value Release
    if check45 then begin
        success := success and RegQueryDWordValue(HKLM, key, 'Release', release);
        success := success and (release >= 378389);
    end;

    result := success and (install = 1) and (serviceCount >= service);
end;

function IsRequiredDotNetDetected(): Boolean;
begin
    result := IsDotNetDetected('v4\Full', 0);
end;

function InitializeSetup(): Boolean;
begin
    if not IsDotNetDetected('v4\Full', 0) then begin
        MsgBox('{#AppName} requires Microsoft .NET Framework 4.0 Client Profile.'#13#13
          'The installer will attempt to install it', mbInformation, MB_OK);
    end;

    result := true;
end;

function MsiQueryProductState(szProduct: string): INSTALLSTATE;
  external 'MsiQueryProductState{#AW}@msi.dll stdcall';

function VCVersionInstalled(const ProductID: string): Boolean;
begin
  Result := MsiQueryProductState(ProductID) = INSTALLSTATE_DEFAULT;
end;

function VCRedistNeedsInstall: Boolean;
begin
  // here the Result must be True when you need to install your VCRedist
  // or False when you don't need to, so now it's upon you how you build
  // this statement, the following won't install your VC redist only when
  // the Visual C++ 2010 Redist (x86) and Visual C++ 2010 SP1 Redist(x86)
  // are installed for the current user
  Result := not (VCVersionInstalled(VC_2012_REDIST_MIN_UPD4_X86) and
    VCVersionInstalled(VC_2012_REDIST_ADD_UPD4_X86));
end;


Fix installer, now ships the FLEx mapping system to prevent a crash.

[_ISTool]
EnableISX=true

#define MyAppName "Solid"
#define MyAppVersion "0.0.0"
#define MyAppPublisher "Payap Language Software"
#define MyAppURL "http://solid.palaso.org"
#define MyAppExeName "Solid.exe"

[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={{4AE9E6FF-434D-4465-BB07-ADC3673461AC}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DisableDirPage=yes
DisableReadyPage=yes
DefaultGroupName={#MyAppName}
DisableProgramGroupPage=yes
LicenseFile=license.rtf
OutputBaseFilename=SolidInstaller
Compression=lzma
SolidCompression=yes
WizardImageFile=compiler:WIZMODERNIMAGE-IS.BMP
CreateUninstallRegKey=true

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

[Dirs]
Name: {app}\mappings
Name: {app}\exporters
Name: {app}\templates
Name: {userdocs}\Solid Examples

[Files]
Source: ..\installer\isxdl.dll; Flags: dontcopy
Source: ..\output\release\Solid.exe; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\KeymanLink.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\GlacialList.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\PalasoUIWindowsForms.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\LiftIO.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.DictionaryServices.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.Lift.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\mappings\MappingXmlToHtml.xsl; DestDir: {app}\mappings
Source: ..\mappings\LIFT.mappingSystem; DestDir: {app}\mappings
Source: ..\mappings\FLEX.mappingSystem; DestDir: {app}\mappings
Source: ..\templates\MDF Unicode.solid; DestDir: {app}\templates
Source: ..\templates\MDF Legacy Font.solid; DestDir: {app}\templates
Source: ..\templates\MDF Alternate Legacy Font.solid; DestDir: {app}\templates
Source: ..\templates\MDF Alternate Unicode.solid; DestDir: {app}\templates
Source: ..\templates\FLEx-friendly MDF Unicode.solid; DestDir: {app}\templates
Source: ..\templates\FLEx-friendly MDF Legacy Font.solid; DestDir: {app}\templates
Source: ..\Solid Examples\BambaraSolidDemo.db; DestDir: {userdocs}\Solid Examples
Source: ..\Solid Examples\BambaraTutorial2.db; DestDir: {userdocs}\Solid Examples

[Messages]
WinVersionTooLowError=Solid requires Windows 2000 or later.

[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"

[Code]
var
  dotnetRedistPath: string;
  downloadNeeded: boolean;
  dotNetNeeded: boolean;
  memoDependenciesNeeded: string;

procedure isxdl_AddFile(URL, Filename: String);
external 'isxdl_AddFile@files:isxdl.dll stdcall';
function isxdl_DownloadFiles(hWnd: Integer): Integer;
external 'isxdl_DownloadFiles@files:isxdl.dll stdcall';
function isxdl_SetOption(Option, Value: String): Integer;
external 'isxdl_SetOption@files:isxdl.dll stdcall';

const
  dotnetRedistURL = 'http://palaso.org/install/dotnet2/dotnetfx.exe';
  // local system for testing...
  //dotnetRedistURL = 'http://localhost/install/dotnet2/dotnetfx.exe';

function InitializeSetup(): Boolean;

begin
  Result := true;
  dotNetNeeded := false;

  // Check for required netfx installation
  if (not RegKeyExists(HKLM, 'Software\Microsoft\.NETFramework\policy\v2.0')) then begin
    dotNetNeeded := true;
    if (not IsAdminLoggedOn()) then begin
      MsgBox('Solid needs the Microsoft .NET Framework to be installed by an Administrator', mbInformation, MB_OK);
      Result := false;
    end else begin
      memoDependenciesNeeded := memoDependenciesNeeded + '      .NET Framework' #13;
      dotnetRedistPath := ExpandConstant('{src}\dotnetfx.exe');
      if not FileExists(dotnetRedistPath) then begin
        dotnetRedistPath := ExpandConstant('{tmp}\dotnetfx.exe');
        if not FileExists(dotnetRedistPath) then begin
          isxdl_AddFile(dotnetRedistURL, dotnetRedistPath);
          downloadNeeded := true;
        end;
      end;
      SetIniString('install', 'dotnetRedist', dotnetRedistPath, ExpandConstant('{tmp}\dep.ini'));
    end;
  end;

  // For testing
  //dotNetNeeded := true;
  //downloadNeeded := true;
  //SetIniString('install', 'dotnetRedist', dotnetRedistPath, ExpandConstant('{tmp}\dep.ini'));

end;

function NextButtonClick(CurPage: Integer): Boolean;
var
  hWnd: Integer;
  ResultCode: Integer;

begin
  Result := true;

  if CurPage = wpWelcome then begin

    hWnd := StrToInt(ExpandConstant('{wizardhwnd}'));

    // don't try to init isxdl if it's not needed because it will error on < ie 3
    if downloadNeeded then begin

      isxdl_SetOption('label', 'Downloading Microsoft .NET Framework');
      isxdl_SetOption('description', 'Solid needs to install the Microsoft .NET Framework. Please wait while Setup is downloading extra files to your computer. This may take several minutes.');
      if isxdl_DownloadFiles(hWnd) = 0 then Result := false;
    end;
    if (Result = true) and (dotNetNeeded = true) then begin
      if Exec(ExpandConstant(dotnetRedistPath), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then begin
         // handle success if necessary; ResultCode contains the exit code
         if not (ResultCode = 0) then begin
           Result := false;
         end;
      end else begin
         // handle failure if necessary; ResultCode contains the error code
         Result := false;
      end;
    end;
  end;
end;

function UpdateReadyMemo(Space, NewLine, MemoUserInfoInfo, MemoDirInfo, MemoTypeInfo, MemoComponentsInfo, MemoGroupInfo, MemoTasksInfo: String): String;
var
  s: string;

begin
  if memoDependenciesNeeded <> '' then s := s + 'Dependencies to install:' + NewLine + memoDependenciesNeeded + NewLine;
  s := s + MemoDirInfo + NewLine + NewLine;

  Result := s
end;

[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, "&", "&&")}}"; Flags: nowait postinstall skipifsilent

[InnoIDE_Settings]
LogFileOverwrite=false

[_ISTool]
EnableISX=true

#define MyAppName "Solid"
#define MyAppVersion "0.0.0"
#define MyAppPublisher "Payap Language Software"
#define MyAppURL "http://solid.palaso.org"
#define MyAppExeName "Solid.exe"

[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={{4AE9E6FF-434D-4465-BB07-ADC3673461AC}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DisableDirPage=yes
DisableReadyPage=yes
DefaultGroupName={#MyAppName}
DisableProgramGroupPage=yes
LicenseFile=license.rtf
OutputBaseFilename=SolidInstaller
Compression=lzma
SolidCompression=yes
WizardImageFile=compiler:WIZMODERNIMAGE-IS.BMP
CreateUninstallRegKey=true

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

[Dirs]
Name: {app}\mappings
Name: {app}\exporters
Name: {app}\templates
Name: {userdocs}\Solid Examples

[Files]
Source: ..\installer\isxdl.dll; Flags: dontcopy
Source: ..\output\release\Solid.exe; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\KeymanLink.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\GlacialList.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\PalasoUIWindowsForms.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\LiftIO.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.DictionaryServices.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\output\release\Palaso.Lift.dll; DestDir: {app}; Flags: replacesameversion
Source: ..\mappings\MappingXmlToHtml.xsl; DestDir: {app}\mappings
Source: ..\mappings\LIFT.mappingSystem; DestDir: {app}\mappings
Source: ..\templates\MDF Unicode.solid; DestDir: {app}\templates
Source: ..\templates\MDF Legacy Font.solid; DestDir: {app}\templates
Source: ..\templates\MDF Alternate Legacy Font.solid; DestDir: {app}\templates
Source: ..\templates\MDF Alternate Unicode.solid; DestDir: {app}\templates
Source: ..\Solid Examples\BambaraSolidDemo.db; DestDir: {userdocs}\Solid Examples
Source: ..\Solid Examples\BambaraTutorial2.db; DestDir: {userdocs}\Solid Examples

[Messages]
WinVersionTooLowError=Solid requires Windows 2000 or later.

[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"

[Code]
var
  dotnetRedistPath: string;
  downloadNeeded: boolean;
  dotNetNeeded: boolean;
  memoDependenciesNeeded: string;

procedure isxdl_AddFile(URL, Filename: String);
external 'isxdl_AddFile@files:isxdl.dll stdcall';
function isxdl_DownloadFiles(hWnd: Integer): Integer;
external 'isxdl_DownloadFiles@files:isxdl.dll stdcall';
function isxdl_SetOption(Option, Value: String): Integer;
external 'isxdl_SetOption@files:isxdl.dll stdcall';

const
  dotnetRedistURL = 'http://palaso.org/install/dotnet2/dotnetfx.exe';
  // local system for testing...
  //dotnetRedistURL = 'http://localhost/install/dotnet2/dotnetfx.exe';

function InitializeSetup(): Boolean;

begin
  Result := true;
  dotNetNeeded := false;

  // Check for required netfx installation
  if (not RegKeyExists(HKLM, 'Software\Microsoft\.NETFramework\policy\v2.0')) then begin
    dotNetNeeded := true;
    if (not IsAdminLoggedOn()) then begin
      MsgBox('Solid needs the Microsoft .NET Framework to be installed by an Administrator', mbInformation, MB_OK);
      Result := false;
    end else begin
      memoDependenciesNeeded := memoDependenciesNeeded + '      .NET Framework' #13;
      dotnetRedistPath := ExpandConstant('{src}\dotnetfx.exe');
      if not FileExists(dotnetRedistPath) then begin
        dotnetRedistPath := ExpandConstant('{tmp}\dotnetfx.exe');
        if not FileExists(dotnetRedistPath) then begin
          isxdl_AddFile(dotnetRedistURL, dotnetRedistPath);
          downloadNeeded := true;
        end;
      end;
      SetIniString('install', 'dotnetRedist', dotnetRedistPath, ExpandConstant('{tmp}\dep.ini'));
    end;
  end;

  // For testing
  //dotNetNeeded := true;
  //downloadNeeded := true;
  //SetIniString('install', 'dotnetRedist', dotnetRedistPath, ExpandConstant('{tmp}\dep.ini'));

end;

function NextButtonClick(CurPage: Integer): Boolean;
var
  hWnd: Integer;
  ResultCode: Integer;

begin
  Result := true;

  if CurPage = wpWelcome then begin

    hWnd := StrToInt(ExpandConstant('{wizardhwnd}'));

    // don't try to init isxdl if it's not needed because it will error on < ie 3
    if downloadNeeded then begin

      isxdl_SetOption('label', 'Downloading Microsoft .NET Framework');
      isxdl_SetOption('description', 'Solid needs to install the Microsoft .NET Framework. Please wait while Setup is downloading extra files to your computer. This may take several minutes.');
      if isxdl_DownloadFiles(hWnd) = 0 then Result := false;
    end;
    if (Result = true) and (dotNetNeeded = true) then begin
      if Exec(ExpandConstant(dotnetRedistPath), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then begin
         // handle success if necessary; ResultCode contains the exit code
         if not (ResultCode = 0) then begin
           Result := false;
         end;
      end else begin
         // handle failure if necessary; ResultCode contains the error code
         Result := false;
      end;
    end;
  end;
end;

function UpdateReadyMemo(Space, NewLine, MemoUserInfoInfo, MemoDirInfo, MemoTypeInfo, MemoComponentsInfo, MemoGroupInfo, MemoTasksInfo: String): String;
var
  s: string;

begin
  if memoDependenciesNeeded <> '' then s := s + 'Dependencies to install:' + NewLine + memoDependenciesNeeded + NewLine;
  s := s + MemoDirInfo + NewLine + NewLine;

  Result := s
end;

[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, "&", "&&")}}"; Flags: nowait postinstall skipifsilent

[InnoIDE_Settings]
LogFileOverwrite=false


Show the Welcome dialog

Show the Welcome dialog

Rather then potentially being greeted with the newly implemented
prompt on the destination location dialog if they have special
characters in their install path, greet the user with the Welcome
dialog when they initially launch the installer.

;This file will be executed next to the application bundle image
;I.e. current directory will contain folder Bisq with application files
;Note: This file must use UTF-8 encoding with BOM for the unicode custom messages to be displayed properly

#define SourceDir GetEnv('package_dir') + '\windows'
#define AppVersion GetEnv('version')
#define FileVersion GetEnv('file_version')
#define AppCopyrightYear GetDateTimeString('yyyy', '-', ':')

[Setup]
AppId={{bisq}}
AppName=Bisq
AppVersion={#AppVersion}
AppVerName=Bisq v{#AppVersion}
AppPublisher=Bisq
AppComments={cm:AppComments}
AppCopyright=Copyright (C) {#AppCopyrightYear}
AppPublisherURL=https://bisq.network
AppSupportURL=https://bisq.community
;AppUpdatesURL=https://bisq.network/downloads
VersionInfoVersion={#FileVersion}
VersionInfoDescription=Bisq Setup
VersionInfoCopyright=Copyright (C) {#AppCopyrightYear}
DefaultDirName={code:GetDefaultDirName}
DisableStartupPrompt=Yes
DisableDirPage=No
DisableProgramGroupPage=Yes
DisableReadyPage=No
DisableFinishedPage=No
DisableWelcomePage=No
DefaultGroupName=Bisq
;Optional License
LicenseFile=
;Windows 7 with Service Pack 1 or above
MinVersion=0,6.1.7601
OutputBaseFilename=Bisq-{#AppVersion}
Compression=lzma
SolidCompression=yes
PrivilegesRequired=lowest
SetupIconFile=Bisq\Bisq.ico
UninstallDisplayIcon={app}\Bisq.ico
UninstallDisplayName=Bisq
WizardImageFile={#SourceDir}\Bisq-setup-image.bmp
WizardImageStretch=No
WizardSmallImageFile=Bisq-setup-icon.bmp
ArchitecturesInstallIn64BitMode=x64
ShowLanguageDialog=No

[Languages]
Name: en; MessagesFile: "compiler:Default.isl"
Name: de; MessagesFile: "compiler:Languages\German.isl"
Name: fr; MessagesFile: "compiler:Languages\French.isl"
Name: sp; MessagesFile: "compiler:Languages\Spanish.isl"

[CustomMessages]
en.AppComments=The decentralized exchange network
en.AppIsRunning=Bisq is running, please close it and run setup again.
en.SpecialAppPath=Your default install path appears to have special characters: %1%n%nThis may prevent Bisq from starting. See https://github.com/bisq-network/bisq/issues/3605 for more information.%n%nYou can either cancel this installation and install as a user without special characters in the username, or proceed with this installation using a different install path that does not contain special characters (e.g. %2).
de.AppComments=Das dezentrale Austauschnetzwerk
de.AppIsRunning=Bisq läuft, bitte schließen Sie es und führen Sie das Setup erneut aus.
de.SpecialAppPath=Ihr Standardinstallationspfad scheint Sonderzeichen zu enthalten: %1%n%nDies kann den Start von Bisq verhindern. Weitere Informationen finden Sie unter https://github.com/bisq-network/bisq/issues/3605.%n%nSie können diese Installation abbrechen und als Benutzer ohne Sonderzeichen im Benutzernamen installieren oder mit dieser Installation fortfahren, indem Sie einen anderen Installationspfad verwenden, der keine Sonderzeichen enthält (z. B. %2).
fr.AppComments=Le réseau d'échange décentralisé
fr.AppIsRunning=Bisq est en cours d'exécution, fermez-le et exécutez à nouveau le programme d'installation.
fr.SpecialAppPath=Votre chemin d'installation par défaut semble comporter des caractères spéciaux: %1%n%nCela peut empêcher le démarrage de Bisq. Voir https://github.com/bisq-network/bisq/issues/3605 pour plus d'informations.%n%nVous pouvez annuler cette installation et l'installer en tant qu'utilisateur sans caractères spéciaux dans le nom d'utilisateur ou procéder à cette installation en utilisant un chemin d'installation différent ne contenant pas de caractères spéciaux (par exemple, %2).
sp.AppComments=La red de intercambio descentralizado
sp.AppIsRunning=Bisq se está ejecutando, ciérrelo y vuelva a ejecutar la configuración.
sp.SpecialAppPath=Su ruta de instalación predeterminada parece tener caracteres especiales: %1%n%nEsto puede evitar que Bisq se inicie. Consulte https://github.com/bisq-network/bisq/issues/3605 para obtener más información.%n%nPuede cancelar esta instalación e instalar como usuario sin caracteres especiales en el nombre de usuario, o continuar con esta instalación utilizando una ruta de instalación diferente que no contenga caracteres especiales (por ejemplo, %2).

[Files]
Source: "Bisq\Bisq.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "Bisq\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs

[Icons]
Name: "{group}\Bisq"; Filename: "{app}\Bisq.exe"; IconFilename: "{app}\Bisq.ico"
Name: "{userdesktop}\Bisq"; Filename: "{app}\Bisq.exe"; IconFilename: "{app}\Bisq.ico"

[Run]
Filename: "{app}\Bisq.exe"; Description: "{cm:LaunchProgram,Bisq}"; Flags: nowait postinstall skipifsilent

[Code]
procedure DirectoryCopy(SourcePath, DestPath: string);
var
  FindRec: TFindRec;
  SourceFilePath: string;
  DestFilePath: string;
begin
  if FindFirst(SourcePath + '\*', FindRec) then
  begin
    try
      repeat
        if (FindRec.Name <> '.') and (FindRec.Name <> '..') then
        begin
          SourceFilePath := SourcePath + '\' + FindRec.Name;
          DestFilePath := DestPath + '\' + FindRec.Name;
          if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
          begin
            if FileCopy(SourceFilePath, DestFilePath, False) then
            begin
              Log(Format('Copied %s to %s', [SourceFilePath, DestFilePath]));
            end
              else
            begin
              Log(Format('Failed to copy %s to %s', [SourceFilePath, DestFilePath]));
            end;
          end
            else
          begin
            if DirExists(DestFilePath) or CreateDir(DestFilePath) then
            begin
              Log(Format('Created %s', [DestFilePath]));
              DirectoryCopy(SourceFilePath, DestFilePath);
            end
              else
            begin
              Log(Format('Failed to create %s', [DestFilePath]));
            end;
          end;
        end;
      until not FindNext(FindRec);
    finally
      FindClose(FindRec);
    end;
  end
    else
  begin
    Log(Format('Failed to list %s', [SourcePath]));
  end;
end;

//Delete old app directory to prevent issues during update
procedure DeleteOldAppDataDirectory;
var
  entry: String;
begin
  entry := ExpandConstant('{localappdata}') + '\Bisq\';
  if DirExists(entry) then begin
    DelTree(entry, true, true, true);
  end;
end;

procedure DeleteTorFiles;
var
  mainnetDir: String;
  torDir: String;
  hiddenServiceDir: String;
  hiddenServiceBackupDir : String;
begin
  mainnetDir := ExpandConstant('{userappdata}') + '\Bisq\btc_mainnet';
  torDir := mainnetDir + '\tor\*';
  hiddenServiceDir := mainnetDir + '\tor\hiddenservice';
  hiddenServiceBackupDir := mainnetDir + '\hiddenservice_backup';
  if DirExists(hiddenServiceDir) then begin
    if DirExists(hiddenServiceBackupDir) then begin
      DelTree(hiddenServiceBackupDir, true, true, true);
    end;
    CreateDir(hiddenServiceBackupDir);
    DirectoryCopy(hiddenServiceDir, hiddenServiceBackupDir);
    DelTree(torDir, false, true, true);
    CreateDir(hiddenServiceDir);
    DirectoryCopy(hiddenServiceBackupDir, hiddenServiceDir);
  end;
end;

function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
  DeleteOldAppDataDirectory;
  DeleteTorFiles;
  Result := '';
end;

function IsAppRunning(): Boolean;
var
  FSWbemLocator : Variant;
  FWMIService : Variant;
  FWbemObjectSet : Variant;
  ExecutablePath : String;
begin
  Result := False;
  ExecutablePath := Format('%s\Bisq\Bisq.exe', [ExpandConstant('{localappdata}')])
  StringChangeEx(ExecutablePath, '\', '\\', True);
  try
    FSWbemLocator := CreateOleObject('WBEMScripting.SWBEMLocator');
    FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
    FWbemObjectSet := FWMIService.ExecQuery(Format('SELECT Name FROM Win32_Process Where ExecutablePath="%s"', [ExecutablePath]));
    Result := (FWbemObjectSet.Count > 0);
    FWbemObjectSet := Unassigned;
    FWMIService := Unassigned;
    FSWbemLocator := Unassigned;
  except
  end;
end;

function isPathSpecial(Path : String): Boolean;
var
  I : Integer;
begin
  Result := not
    ((Length(Path) >= 3) and
    (Path[1] >= 'A') and (Path[1] <= 'Z') and
    (Path[2] = ':') and
    (Path[3] = '\'));
  if not Result then
  begin
    for I := 4 to Length(Path) do
    begin
      case Path[I] of
        '0'..'9', 'A'..'Z', 'a'..'z', '\', ' ', '.', '-', '_', '(', ')':
      else
        begin
          Result := True;
          Break;
        end;
      end;
    end;
  end;
end;

function InitializeSetup(): Boolean;
begin
  Result := True;
  if IsAppRunning() then begin
    MsgBox(ExpandConstant('{cm:AppIsRunning}'), mbCriticalError, MB_OK);
    Result := False;
  end;
end;

function InitializeUninstall(): Boolean;
begin
  Result := True;
  if IsAppRunning() then
  begin
    MsgBox(ExpandConstant('{cm:AppIsRunning}'), mbCriticalError, MB_OK);
    Result := False;
  end;
end;

procedure CurPageChanged(CurPageID: Integer);
var
  DefaultAppPath : String;
  AppPath : String;
begin
  DefaultAppPath := ExpandConstant('{localappdata}');
  if (CurPageID = wpSelectDir) and isPathSpecial(DefaultAppPath) then
  begin
    AppPath := ExpandConstant('{code:GetDefaultDirName}');
    MsgBox(FmtMessage(CustomMessage('SpecialAppPath'), [DefaultAppPath, AppPath]), mbInformation, MB_OK);
  end;
end;

function GetDefaultDirName(Param: String): String;
begin
  Result := Format('%s\Bisq', [ExpandConstant('{localappdata}')]);
  if isPathSpecial(Result) then
  begin
    Result := Format('%s\Bisq', [ExpandConstant('{%ProgramW6432}')]);
  end;
end;

;This file will be executed next to the application bundle image
;I.e. current directory will contain folder Bisq with application files
;Note: This file must use UTF-8 encoding with BOM for the unicode custom messages to be displayed properly

#define SourceDir GetEnv('package_dir') + '\windows'
#define AppVersion GetEnv('version')
#define FileVersion GetEnv('file_version')
#define AppCopyrightYear GetDateTimeString('yyyy', '-', ':')

[Setup]
AppId={{bisq}}
AppName=Bisq
AppVersion={#AppVersion}
AppVerName=Bisq v{#AppVersion}
AppPublisher=Bisq
AppComments={cm:AppComments}
AppCopyright=Copyright (C) {#AppCopyrightYear}
AppPublisherURL=https://bisq.network
AppSupportURL=https://bisq.community
;AppUpdatesURL=https://bisq.network/downloads
VersionInfoVersion={#FileVersion}
VersionInfoDescription=Bisq Setup
VersionInfoCopyright=Copyright (C) {#AppCopyrightYear}
DefaultDirName={code:GetDefaultDirName}
DisableStartupPrompt=Yes
DisableDirPage=No
DisableProgramGroupPage=Yes
DisableReadyPage=No
DisableFinishedPage=No
DisableWelcomePage=Yes
DefaultGroupName=Bisq
;Optional License
LicenseFile=
;Windows 7 with Service Pack 1 or above
MinVersion=0,6.1.7601
OutputBaseFilename=Bisq-{#AppVersion}
Compression=lzma
SolidCompression=yes
PrivilegesRequired=lowest
SetupIconFile=Bisq\Bisq.ico
UninstallDisplayIcon={app}\Bisq.ico
UninstallDisplayName=Bisq
WizardImageFile={#SourceDir}\Bisq-setup-image.bmp
WizardImageStretch=No
WizardSmallImageFile=Bisq-setup-icon.bmp
ArchitecturesInstallIn64BitMode=x64
ShowLanguageDialog=No

[Languages]
Name: en; MessagesFile: "compiler:Default.isl"
Name: de; MessagesFile: "compiler:Languages\German.isl"
Name: fr; MessagesFile: "compiler:Languages\French.isl"
Name: sp; MessagesFile: "compiler:Languages\Spanish.isl"

[CustomMessages]
en.AppComments=The decentralized exchange network
en.AppIsRunning=Bisq is running, please close it and run setup again.
en.SpecialAppPath=Your default install path appears to have special characters: %1%n%nThis may prevent Bisq from starting. See https://github.com/bisq-network/bisq/issues/3605 for more information.%n%nYou can either cancel this installation and install as a user without special characters in the username, or proceed with this installation using a different install path that does not contain special characters (e.g. %2).
de.AppComments=Das dezentrale Austauschnetzwerk
de.AppIsRunning=Bisq läuft, bitte schließen Sie es und führen Sie das Setup erneut aus.
de.SpecialAppPath=Ihr Standardinstallationspfad scheint Sonderzeichen zu enthalten: %1%n%nDies kann den Start von Bisq verhindern. Weitere Informationen finden Sie unter https://github.com/bisq-network/bisq/issues/3605.%n%nSie können diese Installation abbrechen und als Benutzer ohne Sonderzeichen im Benutzernamen installieren oder mit dieser Installation fortfahren, indem Sie einen anderen Installationspfad verwenden, der keine Sonderzeichen enthält (z. B. %2).
fr.AppComments=Le réseau d'échange décentralisé
fr.AppIsRunning=Bisq est en cours d'exécution, fermez-le et exécutez à nouveau le programme d'installation.
fr.SpecialAppPath=Votre chemin d'installation par défaut semble comporter des caractères spéciaux: %1%n%nCela peut empêcher le démarrage de Bisq. Voir https://github.com/bisq-network/bisq/issues/3605 pour plus d'informations.%n%nVous pouvez annuler cette installation et l'installer en tant qu'utilisateur sans caractères spéciaux dans le nom d'utilisateur ou procéder à cette installation en utilisant un chemin d'installation différent ne contenant pas de caractères spéciaux (par exemple, %2).
sp.AppComments=La red de intercambio descentralizado
sp.AppIsRunning=Bisq se está ejecutando, ciérrelo y vuelva a ejecutar la configuración.
sp.SpecialAppPath=Su ruta de instalación predeterminada parece tener caracteres especiales: %1%n%nEsto puede evitar que Bisq se inicie. Consulte https://github.com/bisq-network/bisq/issues/3605 para obtener más información.%n%nPuede cancelar esta instalación e instalar como usuario sin caracteres especiales en el nombre de usuario, o continuar con esta instalación utilizando una ruta de instalación diferente que no contenga caracteres especiales (por ejemplo, %2).

[Files]
Source: "Bisq\Bisq.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "Bisq\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs

[Icons]
Name: "{group}\Bisq"; Filename: "{app}\Bisq.exe"; IconFilename: "{app}\Bisq.ico"
Name: "{userdesktop}\Bisq"; Filename: "{app}\Bisq.exe"; IconFilename: "{app}\Bisq.ico"

[Run]
Filename: "{app}\Bisq.exe"; Description: "{cm:LaunchProgram,Bisq}"; Flags: nowait postinstall skipifsilent

[Code]
procedure DirectoryCopy(SourcePath, DestPath: string);
var
  FindRec: TFindRec;
  SourceFilePath: string;
  DestFilePath: string;
begin
  if FindFirst(SourcePath + '\*', FindRec) then
  begin
    try
      repeat
        if (FindRec.Name <> '.') and (FindRec.Name <> '..') then
        begin
          SourceFilePath := SourcePath + '\' + FindRec.Name;
          DestFilePath := DestPath + '\' + FindRec.Name;
          if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
          begin
            if FileCopy(SourceFilePath, DestFilePath, False) then
            begin
              Log(Format('Copied %s to %s', [SourceFilePath, DestFilePath]));
            end
              else
            begin
              Log(Format('Failed to copy %s to %s', [SourceFilePath, DestFilePath]));
            end;
          end
            else
          begin
            if DirExists(DestFilePath) or CreateDir(DestFilePath) then
            begin
              Log(Format('Created %s', [DestFilePath]));
              DirectoryCopy(SourceFilePath, DestFilePath);
            end
              else
            begin
              Log(Format('Failed to create %s', [DestFilePath]));
            end;
          end;
        end;
      until not FindNext(FindRec);
    finally
      FindClose(FindRec);
    end;
  end
    else
  begin
    Log(Format('Failed to list %s', [SourcePath]));
  end;
end;

//Delete old app directory to prevent issues during update
procedure DeleteOldAppDataDirectory;
var
  entry: String;
begin
  entry := ExpandConstant('{localappdata}') + '\Bisq\';
  if DirExists(entry) then begin
    DelTree(entry, true, true, true);
  end;
end;

procedure DeleteTorFiles;
var
  mainnetDir: String;
  torDir: String;
  hiddenServiceDir: String;
  hiddenServiceBackupDir : String;
begin
  mainnetDir := ExpandConstant('{userappdata}') + '\Bisq\btc_mainnet';
  torDir := mainnetDir + '\tor\*';
  hiddenServiceDir := mainnetDir + '\tor\hiddenservice';
  hiddenServiceBackupDir := mainnetDir + '\hiddenservice_backup';
  if DirExists(hiddenServiceDir) then begin
    if DirExists(hiddenServiceBackupDir) then begin
      DelTree(hiddenServiceBackupDir, true, true, true);
    end;
    CreateDir(hiddenServiceBackupDir);
    DirectoryCopy(hiddenServiceDir, hiddenServiceBackupDir);
    DelTree(torDir, false, true, true);
    CreateDir(hiddenServiceDir);
    DirectoryCopy(hiddenServiceBackupDir, hiddenServiceDir);
  end;
end;

function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
  DeleteOldAppDataDirectory;
  DeleteTorFiles;
  Result := '';
end;

function IsAppRunning(): Boolean;
var
  FSWbemLocator : Variant;
  FWMIService : Variant;
  FWbemObjectSet : Variant;
  ExecutablePath : String;
begin
  Result := False;
  ExecutablePath := Format('%s\Bisq\Bisq.exe', [ExpandConstant('{localappdata}')])
  StringChangeEx(ExecutablePath, '\', '\\', True);
  try
    FSWbemLocator := CreateOleObject('WBEMScripting.SWBEMLocator');
    FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
    FWbemObjectSet := FWMIService.ExecQuery(Format('SELECT Name FROM Win32_Process Where ExecutablePath="%s"', [ExecutablePath]));
    Result := (FWbemObjectSet.Count > 0);
    FWbemObjectSet := Unassigned;
    FWMIService := Unassigned;
    FSWbemLocator := Unassigned;
  except
  end;
end;

function isPathSpecial(Path : String): Boolean;
var
  I : Integer;
begin
  Result := not
    ((Length(Path) >= 3) and
    (Path[1] >= 'A') and (Path[1] <= 'Z') and
    (Path[2] = ':') and
    (Path[3] = '\'));
  if not Result then
  begin
    for I := 4 to Length(Path) do
    begin
      case Path[I] of
        '0'..'9', 'A'..'Z', 'a'..'z', '\', ' ', '.', '-', '_', '(', ')':
      else
        begin
          Result := True;
          Break;
        end;
      end;
    end;
  end;
end;

function InitializeSetup(): Boolean;
begin
  Result := True;
  if IsAppRunning() then begin
    MsgBox(ExpandConstant('{cm:AppIsRunning}'), mbCriticalError, MB_OK);
    Result := False;
  end;
end;

function InitializeUninstall(): Boolean;
begin
  Result := True;
  if IsAppRunning() then
  begin
    MsgBox(ExpandConstant('{cm:AppIsRunning}'), mbCriticalError, MB_OK);
    Result := False;
  end;
end;

procedure CurPageChanged(CurPageID: Integer);
var
  DefaultAppPath : String;
  AppPath : String;
begin
  DefaultAppPath := ExpandConstant('{localappdata}');
  if (CurPageID = wpSelectDir) and isPathSpecial(DefaultAppPath) then
  begin
    AppPath := ExpandConstant('{code:GetDefaultDirName}');
    MsgBox(FmtMessage(CustomMessage('SpecialAppPath'), [DefaultAppPath, AppPath]), mbInformation, MB_OK);
  end;
end;

function GetDefaultDirName(Param: String): String;
begin
  Result := Format('%s\Bisq', [ExpandConstant('{localappdata}')]);
  if isPathSpecial(Result) then
  begin
    Result := Format('%s\Bisq', [ExpandConstant('{%ProgramW6432}')]);
  end;
end;


update Translations.iss

update Translations.iss

;Defaults (English)
CreateStartShortcut=Create a Start Menu shortcut
NoKaM=The installation wizard detected that you do not have Knights and Merchants: The Peasants Rebellion installed. You must have the original game installed in order to play the KaM Remake.%n%nThe installation will be aborted.
SteamFirstRun=Original KaM installed from Steam needs to be started at least once on the system, in order for KMR installer to be able to detect and verify it.
CantUpdate=The installation wizard was unable to find an existing version of the KaM Remake to be updated. Please download and install the complete installer instead.%n%nThe installation will be aborted.
OpenAL=Do you want the installation wizard to install OpenAL? (Strongly recommended) It is required for sounds to work in the KaM Remake
ViewReadme=View the Readme
DeleteSaves=Do you want to delete all your saved games and the progress of all campaigns as well?
DeleteMaps=Do you want to delete all Maps and Campaigns as well?

;Dutch
dut.CreateStartShortcut=Aanmaken van een start menu snelkoppeling
dut.NoKaM=De installatie wizard heeft gedetecteerd dat Knights and Merchants: The Peasants Rebellion niet is geïnstalleerd. Je moet het originele spel hebben geïnstalleerd om KaM Remake te kunnen spelen.%n%nDe installatie is afgebroken.
dut.SteamFirstRun=Originele KaM geïnstalleerd vanaf Steam moet minstens één keer worden gestart op deze computer, zodat het KMR-installatieprogramma het spel kan detecteren en verifiëren.
dut.CantUpdate=De installatie wizard kon geen bestaande versie vinden van de KaM Remake om deze bij te werken naar de nieuwste versie. Download en installeer de complete versie.%n%nDe installatie is afgebroken
dut.OpenAL=Wil je dat de installatie wizard OpenAL installeerd? (Aan te raden) OpenAL is nodig voor de werking van het geluid in KaM Remake
dut.ViewReadme=Lees de Readme
dut.DeleteSaves=Wil je ook alle opgeslagen spellen en voortgang in de campagnes verwijderen?
dut.DeleteMaps=Wil je ook alle Kaarten en Campagnes verwijderen?

;Swedish
swe.CreateStartShortcut=Skapa en genväg i startmenyn
swe.NoKaM=Det verkar som att du inte har Knights and Merchants: The Peasants Rebellion installerat på din dator.%n%nInstallationen kommer att avbrytas.
swe.CantUpdate=Kunde inte hitta en redan installerad version av KaM Remake att uppdatera. Ladda ner och installera den kompletta versionen istället.%n%nInstallationen kommer att avbrytas.
swe.OpenAL=Vill du även installera OpenAL? (Rekommenderas starkt) Det krävs för att ljud ska fungera i KaM Remake
swe.ViewReadme=Visa Readme-filen

;German
ger.CreateStartShortcut=Verknüpfung im Startmenü erstellen
ger.NoKaM=Setup hat ermittelt, dass Knights and Merchants: The Peasants Rebellion nicht installiert ist.
ger.CantUpdate=Setup war nicht in der Lage eine installierte Version von KaM Remake zu aktualisieren. Bitte lade die Vollversion von KaM Remake herunter und führe das Setup erneut aus.
ger.OpenAL=Soll Setup auch OpenAl installieren (empfohlen)? Es wird für die Soundwiedergabe von KaM Remake benötigt.
ger.ViewReadme=Readme anzeigen

;Polish
pol.CreateStartShortcut=Stwórz skrót w Menu Start
pol.NoKaM=Kreator instalacji wykrył że nie masz zainstalowanego Knights and Merchants: The Peasants Rebellion.%n%nInstalacja zostanie przerwana.
pol.CantUpdate=Kreator instalacji nie był w stanie znaleźć istniejącej wersji KaM Remake do zaktualizowania. Proszę pobrać i zainstalować kompletny instalator.%n%nInstalacja zostanie przerwana.
pol.OpenAL=Czy chcesz aby kreator instalacji zainstalował OpenAL? (Zalecane) Jest on wymagany by działały dźwięki w KaM Remake.
pol.ViewReadme=Zobacz plik Readme

;Hungarian
hun.CreateStartShortcut=Start Menü ikon létrehozása
hun.NoKaM=A telepítő nem észlelte a Knights and Merchants: A Parasztfelkelést telepítve.%n%nA telepítés megszakításra kerül.
hun.CantUpdate=A telepítő nem talált KaM Remake verziót a számítógépen, hogy frissítse. Kérem töltse le és használja a teljes telepítőt.%n%nA telepítés megszakításra kerül.
hun.OpenAL=Szeretnéd, hogy a telepítő telepítse az OpenAL-t? (Erősen ajánlott) A hangok működéséhez szükséges a KaM Remake-ben
hun.ViewReadme=Olvass el fájl megtekintése

;French
fre.CreateStartShortcut=Créer un raccourci dans le menu Démarrer
fre.NoKaM=L'assistant d'installation n'a détecté aucune installation de Knights and Merchants : The Peasants Rebellion.%n%nL'installation sera interrompue.
fre.CantUpdate=L'assistant d'installation n'a détecté aucune version existante de KaM Remake à mettre à jour. Veuillez télécharger et utiliser l'installateur complet.%n%nL'installation sera interrompue.
fre.OpenAL=Voulez-vous que l'assistant d'installation installe OpenAL ? (fortement recommandé) OpenAL est requis pour le fonctionnement audio de KaM Remake.
fre.ViewReadme=Voir le lisez-moi

;Czech
cze.CreateStartShortcut=Vytvořit zástupce v nabídce Start
cze.NoKaM=Instalátor zjistil, že hra Knights and Merchants: The Peasants Rebellion není nainstalována. Instalace bude nyní ukončena.
cze.SteamFirstRun=Knights and Merchants na Steamu je potřeba pustit alespoň jednou, aby mohla instalace pokračovat.
cze.CantUpdate=Instalátor nenalezl na vašem počítači KaM Remake. Nejprve si stáhněte kompletní KaM Remake, poté můžete aktualizovat. Instalace bude nyní ukončena.
cze.OpenAL=Chcete nainstalovat OpenAL? (Doporučeno) OpenAL je vyžadováno pro správnou funkci zvuku v KaM Remake
cze.ViewReadme=Otevřít Readme
cze.DeleteSaves=Chcete také smazat všechny uložené hry a postup v kampani?
cze.DeleteMaps=Chcete také smazat všechny mapy a kampaně?

;Russian
rus.CreateStartShortcut=Создать ярлык в меню Пуск
rus.NoKaM=Мастер установки не обнаружил установленной игры Knights and Merchants: The Peasants Rebellion. Оригинальная игра необходима для установки КаМ Ремейк.%n%nУстановка будет отменена.
rus.SteamFirstRun=Оригинальная игра, установленная из Steam должна быть запущена хотя бы 1 раз, чтобы данный установщик КаМ Ремейк смог ее обнаружить и проверить.
rus.CantUpdate=Мастер установки не смог обнаружить версию КаМ Ремейк для обновления. Пожалуйста скачайте и запустите полную версию установщика.%n%nУстановка будет отменена.
rus.OpenAL=Установить OpenAL? (рекоммендуется) Необходимо для работы звука в КаМ Ремейк
rus.ViewReadme=Показать Readme
rus.DeleteSaves=Вы хотите также удалить все сохраненные игры и прогресс всех кампаний?
rus.DeleteMaps=Вы хотите также удалить все карты и кампании?

;Brazilian Portuguese
ptb.CreateStartShortcut=Criar um atalho no menu Iniciar
ptb.NoKaM=O assistente de instalação detectou que você não tem Knights and Merchants: The Peasants Rebellion instalado.%n%nA instalação será abortada.
ptb.CantUpdate=O assistente de instalação foi incapaz de encontrar uma versão existente do KaM Remake para atualizar. Por favor, baixe e instale através do instalador completo.%n%nA instalação será abortada.
ptb.OpenAL=Você deseja que o assistente de instalação instale o OpenAL? (Altamente recomendado) É necessário para o funcionamento dos sons no KaM Remake
ptb.ViewReadme=Ver o Readme

;Italian
ita.CreateStartShortcut=Crea collegamento nel Menu Avvio
ita.NoKaM=La procedura guidata di installazione non ha rilevato alcuna copia di "Knights and Merchants: The Peasants Rebellion". È necessaria l'installazione del gioco originale per poter utilizzare "KaM Remake".%n%nLa procedura di installazione verrà ora annullata.
ita.CantUpdate=La procedura guidata di installazione non ha rilevato alcuna versione di "KaM Remake" da aggiornare. Si prega di scaricare e utilizzare invece il programma di installazione completo.%n%nLa procedura di installazione verrà ora annullata.
ita.OpenAL=Vuoi procedere all'installazione di OpenAL? (Fortemente raccomandata) È necessaria per il corretto funzionamento dell'audio in "KaM Remake"
ita.ViewReadme=Visualizza il file Readme

;Spanish
spa.CreateStartShortcut=Crea un acceso directo en el menú de inicio
spa.NoKaM=El asistente de instalación ha detectado que no tienes Knights and Merchants: The Peasants Rebellion instalado. Usted debe tener instalado el juego original para poder jugar el remake de Kam.%n%nLa instalación se interrumpirá
spa.CantUpdate=El asistente de instalación no ha podido encontrar la versión Kam Remake para poder actualizar. Por favor, descarga y instala la versión completa.%n%nLa instalación se interrumpirá.
spa.OpenAL=¿Quieres que el asistente de instalación instale OpenAL? (Muy recomendable) se requiere para el sonido del juego Kam Remake
spa.ViewReadme=Ver el archivo Readme

;Bulgarian
bul.CreateStartShortcut=Създай пряк път
bul.NoKaM=Инсталацията откри, че нямате инсталирана Knights and Merchants: The Peasants Rebellion. Вие трябва да имате Knights and Merchants: The Peasants Rebellion, за да играете KaM Remake.%n%nИнсталацията се прекратява.
bul.CantUpdate=Инсталацията не успя да намери съществуваща версия на KaM Remake, за да бъде подобрена. Моля изтеглете и инсталирайте пълния инсталатор.%n%nИнсталацията ще се прекрати.
bul.OpenAL=Искате ли инсталацията да инсталира OpenAL? (Силно се препоръчва) Нужно е, за да работи звука в играта.
bul.ViewReadme=Виж "Прочети ме"

;Estonian
est.CreateStartShortcut=Loo start menüü otsetee
est.NoKaM=Paigaldamise programm on avastanud, et Teil ei ole paigaldatud Knights and Merchants: The Peasants Rebellion. Teil peab olema paigaldatud originaal mäng, et mängida mängu KaM Remake.%n%nPaigaldamine katkestakase.
est.CantUpdate=Paigaldamise programm ei leidnud olemas olevat KaM Remake versiooni, mida uuendada. Palun laadige internetist alla täis versioon mängust KaM Remake.%n%nPaigaldamine katkestatakse.
est.OpenAL=Kas te soovite paigaldada programmi OpenAL? (Tungivalt soovitatav) See on vajalik, et helid töötaksid mängus KaM Remake.
est.ViewReadme=Vaadake faili Readme

;Slovak
svk.CreateStartShortcut=Vytvoriť zástupcu v ponuke Štart
svk.NoKaM=Sprievodca inštaláciou zistil, že nemáte nainštalovaný Knight & Merchants: The Peasants Rebellion. Musíte mať nainštalovanú originálnu hru, aby ste mohli hrať KaM Remake.%n%nInštalácia bude prerušená.
svk.CantUpdate=Sprievodca inštaláciou nemohol nájsť existujúcu verziu KaM Remake, je ju potrebné aktualizovať. Prosím, stiahnite a nainštalujte kompletnú inštaláciu.%n%nInštalácia bude prerušená.
svk.OpenAL=Chcete použiť spriveodcu na inštaláciu OpenAL? (Dôrazne odporúčané). Je to potrebné pre zvuky v hre v KAM Remake.
svk.ViewReadme=Pozri súbor Readme

;Romanian
rom.CreateStartShortcut=Creează o scurtătura în meniul de Start
rom.NoKaM=Instalarea a detectat ca nu ai instalat Knights and Merchants: The Peasants Rebellion. Trebuie să ai instalat jocul original pentru a putea juca KaM Remake.%n%nInstalarea se va întrerupe.
rom.CantUpdate=Instalarea nu a putut găsi o versiune care va putea fi updată. Te rog să downloadezi fisierul de instalare complet.%n%nInstalarea se va întrerupe.
rom.OpenAL=Vrei să instalezi OpenAL?(Recomandat) Este necesar pentru sunetele din KaM Remake
rom.ViewReadme=Vizualizeazp fisierul Citeste-ma

;Ukrainian
ukr.CreateStartShortcut=Створити ярлик стартового меню
ukr.NoKaM=Майстер встановлення программи не знайшов оригіналу Knights and Merchants: The Peasants Rebellion на вашому комп`ютері. Ви маєте встановити оригінал для того , щоб грат в KaM Remake.%n%nІнсталяцію скасовано.
ukr.CantUpdate=Майстер встановлення програми не зміг знайти KaM Remake на компютері для того, щоб оновити його. Будь ласка , в першу чергу , завантажте і встановіть повну версію перш ніж встановлювати апдейт.%n%nІнсталяцію скасовано.
ukr.OpenAL=Чи хочете ви щоби майстер встановив OpenAL? (Дуже рекомендується) Він необхідний для роботи звуку у KaM Remake
ukr.ViewReadme=Відкрити Readme

;Norwegian
nor.CreateStartShortcut=Legg til snarvei i Start-menyen
nor.NoKaM=Installasjonsveiviseren oppdaget at du ikke har Knights and Merchants: The Peasants Rebellion installert. Du må ha det originale spillet installert for å spille KaM Remake.%n%nInstallasjonen vil bli avbrutt.
nor.CantUpdate=Installasjonen kunne ikke finne en eksisterende versjon av KaM Remake å oppdatere. Vennligst last ned og installer det fullstendige installasjonsprogrammet i stedet.%n%nInstallasjonen vil bli avbrutt.
nor.OpenAL=Ønsker du at installasjonsveiviseren skal installere OpenAL? (Anbefales sterkt) Det er nødvendig for at lyder skal fungere i KaM Remake
nor.ViewReadme=Vis Readme

;Belarusian
bel.CreateStartShortcut=Стварыць цэтлік ў меню "Пуск"
bel.NoKaM=Майстар ўстаноўкі выявіў што ў вас няма ўсталяванай iгры Knights and Merchants: The Peasants Rebellion. Вы павінны ўсталяваць арыгінальную iгру каб іграць ў KaM Remake.%n%nУстаноўка будзе спынена.
bel.CantUpdate=Майстру ўстаноўкі не ўдаецца знайсці версію KaM Remake для абнаўлення. Калі ласка загрузіце поўны пакет ўстаноўкі.%n%nУстаноўка будзе спынена.
bel.OpenAL=Вы хочаце ўсталяваць OpenAL? (настойліва рэкамендуецца) Гэта неабходна для работы гуку ў KaM Remake
bel.ViewReadme=Адкрыць Readme

;Japanese
jpn.CreateStartShortcut=スタートメニューのショートカットが作成されます。
jpn.NoKaM=インストールウィザードが"Knights and Merchants: The Peasants Rebellion"をインストールしていないの検出されました。KAM リメイクがフレーされるにはオリジナルのゲームはインストールしてはいけません。インストールは中止されました。
jpn.CantUpdate=インストールウィザードは既存のKAMリメイクバージョンが見つかりませんでした。その代わりに全部のインストーラはダウンロートしてインストールしてください。インストールは中止されました。
jpn.OpenAL=インストールウィザードがOpenALをインストールしたいですか「強い推奨」。KAM リメイクの音楽などを聞くと必要です。
jpn.ViewReadme=Readmeが表示されます。

;Turkish
tur.CreateStartShortcut=Başlat menüsü kısayolu oluştur.
tur.NoKaM=Kurulum sihirbazı orijinal Knights and Merchants: The Peasants Rebellion oyununun kurulu olmadığını tespit etti. KaM Remake modunu oynayabilmek için orijinal oyuna sahip olmanız gerekmektedir.%n%nKurulum sihirbazı kapanacaktır.
tur.CantUpdate=Kurulum sihirbazı herhangi bir kurulu KaM Remake versiyonu bulamadı. Lütfen complete installer indirerek kurulum yapınız.%n%nKurulum sihirbazı kapanacaktır.
tur.OpenAL=Kurulum sihirbazının OpenAL kurmasını ister misiniz? (Tavsiye edilir) Seslerin oyun içinde çalışması için gereklidir.
tur.ViewReadme=Beni oku dosyasını aç

;Korean
kor.CreateStartShortcut=시작 메뉴 단축 아이콘 만들기
kor.NoKaM=설치 마법사가 '기사와 상인:농민의 반란'이 설치가 안된것으로 확인되었습니다. '기사와 상인 다시만듬'을 실행하기 위해서는 반드시 원본 게임이 설치되어 있어야 합니다. 설치가 중단 됩니다.
kor.CantUpdate=설치 마법사가 갱신할 '기사와 상인 다시만듬'의 기존 버전을 찾을 수 없습니다. 전체 설치 프로그램 대신에 다운로드하여 설치 해주십시오. 설치가 중단 됩니다.
kor.OpenAL=OpenAL을 설치하기위해 설치 마법사가 필요합니까? (강력하게 추천함) '기사와 상인 다시만듬'에서 소리를 작동하는데 필요합니다.
kor.ViewReadme=읽어보기

;Serbian
srb.CreateStartShortcut=Направите Старт Мену Пречицу
srb.NoKaM=Инсталациони чаробњак је приметио да немате Knights and Merchants: The Peasants Rebellion инсталирано.Морате имати оригиналну игру инсталирану да бисте играли KaM Remake.%n%nИнсталације ће престати са радом.
srb.CantUpdate=Инсталациони чаробњак није могао да нађе постојећу верзију KaM Remake да се усавремени.Молимо вас скините и инсталирајте комплетан инсталер уместо тога.%n%nИнсталација ће престати са радом.
srb.OpenAL=Да ли желите да вам инсталациони чаробњакисталира OpenAL? (Врло препоручљиво) Потребно је да бих ѕвукови радили у KaM Remake.
srb.ViewReadme=Прочитајте Реадме

;Chinese
chn.CreateStartShortcut=创建开始菜单快捷方式
chn.NoKaM=安装向导检测到没有《骑士与商人之农民起义》的安装。为了能玩重制版游戏，必须先安装原版游戏。本安装程序将被终止。
chn.CantUpdate=安装向导无法找到一个存在的重制版能够被升级。请重新下载并安装完整的安装包。本安装程序将被终止。
chn.OpenAL=你想用安装向导来安装OpenAL吗？（强烈推荐）这是音效文件运行的必需程序。
chn.ViewReadme=查看自述文件

;Slovenian
slv.CreateStartShortcut=Ustvari bljižnico na meniju
slv.NoKaM=Čarovnik za namestitev je zaznal da nimate nameščeno igro Knights and Merchants: The Peasants Rebellion. Morate imeti nameščeno originalno igro če želite igrati KaM Remake.%n%nNamestitev bo prekinjena
slv.OpenAL=Ali želite namestiti OpenAL? (Močno priporočeno) potrebno je za elovanje zvokov v igri KaM Remake.
slv.ViewReadme=Poglej si opis

;Defaults (English)
CreateStartShortcut=Create a Start Menu shortcut
NoKaM=The installation wizard detected that you do not have Knights and Merchants: The Peasants Rebellion installed. You must have the original game installed in order to play the KaM Remake.%n%nThe installation will be aborted.
SteamFirstRun=Original KaM installed from Steam needs to be started at least once on the system, in order for KMR installer to be able to detect and verify it.
CantUpdate=The installation wizard was unable to find an existing version of the KaM Remake to be updated. Please download and install the complete installer instead.%n%nThe installation will be aborted.
OpenAL=Do you want the installation wizard to install OpenAL? (Strongly recommended) It is required for sounds to work in the KaM Remake
ViewReadme=View the Readme
DeleteSaves=Do you want to delete all your saved games and the progress of all campaigns as well?
DeleteMaps=Do you want to delete all Maps and Campaigns as well?

;Dutch
dut.CreateStartShortcut=Aanmaken van een start menu snelkoppeling
dut.NoKaM=De installatie wizard heft gedetecteerd dat Knights and Merchants: Te Peasants Rebellion niet is geinstalleerd.%n%nDe installatie is afgebroken
dut.SteamFirstRun=Originele KaM geïnstalleerd vanaf Steam moet minstens één keer worden gestart op deze computer, zodat het KMR-installatieprogramma het spel kan detecteren en verifiëren.
dut.CantUpdate=De installatie wizard kon geen bestaande versie vinden van de KaM Remake om deze bij te werken naar de nieuwste versie. Download en installeer de complete versie.%n%nDe installatie is afgebroken
dut.OpenAL=Wil je dat de installatie wizard OpenAL installeerd? (Aan te raden) OpenAL is nodig voor de werking van het geluid in KaM Remake
dut.ViewReadme=Lees de Readme
dut.DeleteSaves=Wil je ook alle opgeslagen spellen en voortgang in de campagnes verwijderen?
dut.DeleteMaps=Wil je ook alle Kaarten en Campagnes verwijderen?

;Swedish
swe.CreateStartShortcut=Skapa en genväg i startmenyn
swe.NoKaM=Det verkar som att du inte har Knights and Merchants: The Peasants Rebellion installerat på din dator.%n%nInstallationen kommer att avbrytas.
swe.CantUpdate=Kunde inte hitta en redan installerad version av KaM Remake att uppdatera. Ladda ner och installera den kompletta versionen istället.%n%nInstallationen kommer att avbrytas.
swe.OpenAL=Vill du även installera OpenAL? (Rekommenderas starkt) Det krävs för att ljud ska fungera i KaM Remake
swe.ViewReadme=Visa Readme-filen

;German
ger.CreateStartShortcut=Verknüpfung im Startmenü erstellen
ger.NoKaM=Setup hat ermittelt, dass Knights and Merchants: The Peasants Rebellion nicht installiert ist.
ger.CantUpdate=Setup war nicht in der Lage eine installierte Version von KaM Remake zu aktualisieren. Bitte lade die Vollversion von KaM Remake herunter und führe das Setup erneut aus.
ger.OpenAL=Soll Setup auch OpenAl installieren (empfohlen)? Es wird für die Soundwiedergabe von KaM Remake benötigt.
ger.ViewReadme=Readme anzeigen

;Polish
pol.CreateStartShortcut=Stwórz skrót w Menu Start
pol.NoKaM=Kreator instalacji wykrył że nie masz zainstalowanego Knights and Merchants: The Peasants Rebellion.%n%nInstalacja zostanie przerwana.
pol.CantUpdate=Kreator instalacji nie był w stanie znaleźć istniejącej wersji KaM Remake do zaktualizowania. Proszę pobrać i zainstalować kompletny instalator.%n%nInstalacja zostanie przerwana.
pol.OpenAL=Czy chcesz aby kreator instalacji zainstalował OpenAL? (Zalecane) Jest on wymagany by działały dźwięki w KaM Remake.
pol.ViewReadme=Zobacz plik Readme

;Hungarian
hun.CreateStartShortcut=Start Menü ikon létrehozása
hun.NoKaM=A telepítő nem észlelte a Knights and Merchants: A Parasztfelkelést telepítve.%n%nA telepítés megszakításra kerül.
hun.CantUpdate=A telepítő nem talált KaM Remake verziót a számítógépen, hogy frissítse. Kérem töltse le és használja a teljes telepítőt.%n%nA telepítés megszakításra kerül.
hun.OpenAL=Szeretnéd, hogy a telepítő telepítse az OpenAL-t? (Erősen ajánlott) A hangok működéséhez szükséges a KaM Remake-ben
hun.ViewReadme=Olvass el fájl megtekintése

;French
fre.CreateStartShortcut=Créer un raccourci dans le menu Démarrer
fre.NoKaM=L'assistant d'installation n'a détecté aucune installation de Knights and Merchants : The Peasants Rebellion.%n%nL'installation sera interrompue.
fre.CantUpdate=L'assistant d'installation n'a détecté aucune version existante de KaM Remake à mettre à jour. Veuillez télécharger et utiliser l'installateur complet.%n%nL'installation sera interrompue.
fre.OpenAL=Voulez-vous que l'assistant d'installation installe OpenAL ? (fortement recommandé) OpenAL est requis pour le fonctionnement audio de KaM Remake.
fre.ViewReadme=Voir le lisez-moi

;Czech
cze.CreateStartShortcut=Vytvořit zástupce v nabídce Start
cze.NoKaM=Instalátor zjistil, že hra Knights and Merchants: The Peasants Rebellion není nainstalována. Instalace bude nyní ukončena.
cze.SteamFirstRun=Knights and Merchants na Steamu je potřeba pustit alespoň jednou, aby mohla instalace pokračovat.
cze.CantUpdate=Instalátor nenalezl na vašem počítači KaM Remake. Nejprve si stáhněte kompletní KaM Remake, poté můžete aktualizovat. Instalace bude nyní ukončena.
cze.OpenAL=Chcete nainstalovat OpenAL? (Doporučeno) OpenAL je vyžadováno pro správnou funkci zvuku v KaM Remake
cze.ViewReadme=Otevřít Readme
cze.DeleteSaves=Chcete také smazat všechny uložené hry a postup v kampani?
cze.DeleteMaps=Chcete také smazat všechny mapy a kampaně?

;Russian
rus.CreateStartShortcut=Создать ярлык в меню Пуск
rus.NoKaM=Мастер установки не обнаружил установленной игры Knights and Merchants: The Peasants Rebellion. Оригинальная игра необходима для установки КаМ Ремейк.%n%nУстановка будет отменена.
rus.SteamFirstRun=Оригинальная игра, установленная из Steam должна быть запущена хотя бы 1 раз, чтобы данный установщик КаМ Ремейк смог ее обнаружить и проверить.
rus.CantUpdate=Мастер установки не смог обнаружить версию КаМ Ремейк для обновления. Пожалуйста скачайте и запустите полную версию установщика.%n%nУстановка будет отменена.
rus.OpenAL=Установить OpenAL? (рекоммендуется) Необходимо для работы звука в КаМ Ремейк
rus.ViewReadme=Показать Readme
rus.DeleteSaves=Вы хотите также удалить все сохраненные игры и прогресс всех кампаний?
rus.DeleteMaps=Вы хотите также удалить все карты и кампании?

;Brazilian Portuguese
ptb.CreateStartShortcut=Criar um atalho no menu Iniciar
ptb.NoKaM=O assistente de instalação detectou que você não tem Knights and Merchants: The Peasants Rebellion instalado.%n%nA instalação será abortada.
ptb.CantUpdate=O assistente de instalação foi incapaz de encontrar uma versão existente do KaM Remake para atualizar. Por favor, baixe e instale através do instalador completo.%n%nA instalação será abortada.
ptb.OpenAL=Você deseja que o assistente de instalação instale o OpenAL? (Altamente recomendado) É necessário para o funcionamento dos sons no KaM Remake
ptb.ViewReadme=Ver o Readme

;Italian
ita.CreateStartShortcut=Crea collegamento nel Menu Avvio
ita.NoKaM=La procedura guidata di installazione non ha rilevato alcuna copia di "Knights and Merchants: The Peasants Rebellion". È necessaria l'installazione del gioco originale per poter utilizzare "KaM Remake".%n%nLa procedura di installazione verrà ora annullata.
ita.CantUpdate=La procedura guidata di installazione non ha rilevato alcuna versione di "KaM Remake" da aggiornare. Si prega di scaricare e utilizzare invece il programma di installazione completo.%n%nLa procedura di installazione verrà ora annullata.
ita.OpenAL=Vuoi procedere all'installazione di OpenAL? (Fortemente raccomandata) È necessaria per il corretto funzionamento dell'audio in "KaM Remake"
ita.ViewReadme=Visualizza il file Readme

;Spanish
spa.CreateStartShortcut=Crea un acceso directo en el menú de inicio
spa.NoKaM=El asistente de instalación ha detectado que no tienes Knights and Merchants: The Peasants Rebellion instalado. Usted debe tener instalado el juego original para poder jugar el remake de Kam.%n%nLa instalación se interrumpirá
spa.CantUpdate=El asistente de instalación no ha podido encontrar la versión Kam Remake para poder actualizar. Por favor, descarga y instala la versión completa.%n%nLa instalación se interrumpirá.
spa.OpenAL=¿Quieres que el asistente de instalación instale OpenAL? (Muy recomendable) se requiere para el sonido del juego Kam Remake
spa.ViewReadme=Ver el archivo Readme

;Bulgarian
bul.CreateStartShortcut=Създай пряк път
bul.NoKaM=Инсталацията откри, че нямате инсталирана Knights and Merchants: The Peasants Rebellion. Вие трябва да имате Knights and Merchants: The Peasants Rebellion, за да играете KaM Remake.%n%nИнсталацията се прекратява.
bul.CantUpdate=Инсталацията не успя да намери съществуваща версия на KaM Remake, за да бъде подобрена. Моля изтеглете и инсталирайте пълния инсталатор.%n%nИнсталацията ще се прекрати.
bul.OpenAL=Искате ли инсталацията да инсталира OpenAL? (Силно се препоръчва) Нужно е, за да работи звука в играта.
bul.ViewReadme=Виж "Прочети ме"

;Estonian
est.CreateStartShortcut=Loo start menüü otsetee
est.NoKaM=Paigaldamise programm on avastanud, et Teil ei ole paigaldatud Knights and Merchants: The Peasants Rebellion. Teil peab olema paigaldatud originaal mäng, et mängida mängu KaM Remake.%n%nPaigaldamine katkestakase.
est.CantUpdate=Paigaldamise programm ei leidnud olemas olevat KaM Remake versiooni, mida uuendada. Palun laadige internetist alla täis versioon mängust KaM Remake.%n%nPaigaldamine katkestatakse.
est.OpenAL=Kas te soovite paigaldada programmi OpenAL? (Tungivalt soovitatav) See on vajalik, et helid töötaksid mängus KaM Remake.
est.ViewReadme=Vaadake faili Readme

;Slovak
svk.CreateStartShortcut=Vytvoriť zástupcu v ponuke Štart
svk.NoKaM=Sprievodca inštaláciou zistil, že nemáte nainštalovaný Knight & Merchants: The Peasants Rebellion. Musíte mať nainštalovanú originálnu hru, aby ste mohli hrať KaM Remake.%n%nInštalácia bude prerušená.
svk.CantUpdate=Sprievodca inštaláciou nemohol nájsť existujúcu verziu KaM Remake, je ju potrebné aktualizovať. Prosím, stiahnite a nainštalujte kompletnú inštaláciu.%n%nInštalácia bude prerušená.
svk.OpenAL=Chcete použiť spriveodcu na inštaláciu OpenAL? (Dôrazne odporúčané). Je to potrebné pre zvuky v hre v KAM Remake.
svk.ViewReadme=Pozri súbor Readme

;Romanian
rom.CreateStartShortcut=Creează o scurtătura în meniul de Start
rom.NoKaM=Instalarea a detectat ca nu ai instalat Knights and Merchants: The Peasants Rebellion. Trebuie să ai instalat jocul original pentru a putea juca KaM Remake.%n%nInstalarea se va întrerupe.
rom.CantUpdate=Instalarea nu a putut găsi o versiune care va putea fi updată. Te rog să downloadezi fisierul de instalare complet.%n%nInstalarea se va întrerupe.
rom.OpenAL=Vrei să instalezi OpenAL?(Recomandat) Este necesar pentru sunetele din KaM Remake
rom.ViewReadme=Vizualizeazp fisierul Citeste-ma

;Ukrainian
ukr.CreateStartShortcut=Створити ярлик стартового меню
ukr.NoKaM=Майстер встановлення программи не знайшов оригіналу Knights and Merchants: The Peasants Rebellion на вашому комп`ютері. Ви маєте встановити оригінал для того , щоб грат в KaM Remake.%n%nІнсталяцію скасовано.
ukr.CantUpdate=Майстер встановлення програми не зміг знайти KaM Remake на компютері для того, щоб оновити його. Будь ласка , в першу чергу , завантажте і встановіть повну версію перш ніж встановлювати апдейт.%n%nІнсталяцію скасовано.
ukr.OpenAL=Чи хочете ви щоби майстер встановив OpenAL? (Дуже рекомендується) Він необхідний для роботи звуку у KaM Remake
ukr.ViewReadme=Відкрити Readme

;Norwegian
nor.CreateStartShortcut=Legg til snarvei i Start-menyen
nor.NoKaM=Installasjonsveiviseren oppdaget at du ikke har Knights and Merchants: The Peasants Rebellion installert. Du må ha det originale spillet installert for å spille KaM Remake.%n%nInstallasjonen vil bli avbrutt.
nor.CantUpdate=Installasjonen kunne ikke finne en eksisterende versjon av KaM Remake å oppdatere. Vennligst last ned og installer det fullstendige installasjonsprogrammet i stedet.%n%nInstallasjonen vil bli avbrutt.
nor.OpenAL=Ønsker du at installasjonsveiviseren skal installere OpenAL? (Anbefales sterkt) Det er nødvendig for at lyder skal fungere i KaM Remake
nor.ViewReadme=Vis Readme

;Belarusian
bel.CreateStartShortcut=Стварыць цэтлік ў меню "Пуск"
bel.NoKaM=Майстар ўстаноўкі выявіў што ў вас няма ўсталяванай iгры Knights and Merchants: The Peasants Rebellion. Вы павінны ўсталяваць арыгінальную iгру каб іграць ў KaM Remake.%n%nУстаноўка будзе спынена.
bel.CantUpdate=Майстру ўстаноўкі не ўдаецца знайсці версію KaM Remake для абнаўлення. Калі ласка загрузіце поўны пакет ўстаноўкі.%n%nУстаноўка будзе спынена.
bel.OpenAL=Вы хочаце ўсталяваць OpenAL? (настойліва рэкамендуецца) Гэта неабходна для работы гуку ў KaM Remake
bel.ViewReadme=Адкрыць Readme

;Japanese
jpn.CreateStartShortcut=スタートメニューのショートカットが作成されます。
jpn.NoKaM=インストールウィザードが"Knights and Merchants: The Peasants Rebellion"をインストールしていないの検出されました。KAM リメイクがフレーされるにはオリジナルのゲームはインストールしてはいけません。インストールは中止されました。
jpn.CantUpdate=インストールウィザードは既存のKAMリメイクバージョンが見つかりませんでした。その代わりに全部のインストーラはダウンロートしてインストールしてください。インストールは中止されました。
jpn.OpenAL=インストールウィザードがOpenALをインストールしたいですか「強い推奨」。KAM リメイクの音楽などを聞くと必要です。
jpn.ViewReadme=Readmeが表示されます。

;Turkish
tur.CreateStartShortcut=Başlat menüsü kısayolu oluştur.
tur.NoKaM=Kurulum sihirbazı orijinal Knights and Merchants: The Peasants Rebellion oyununun kurulu olmadığını tespit etti. KaM Remake modunu oynayabilmek için orijinal oyuna sahip olmanız gerekmektedir.%n%nKurulum sihirbazı kapanacaktır.
tur.CantUpdate=Kurulum sihirbazı herhangi bir kurulu KaM Remake versiyonu bulamadı. Lütfen complete installer indirerek kurulum yapınız.%n%nKurulum sihirbazı kapanacaktır.
tur.OpenAL=Kurulum sihirbazının OpenAL kurmasını ister misiniz? (Tavsiye edilir) Seslerin oyun içinde çalışması için gereklidir.
tur.ViewReadme=Beni oku dosyasını aç

;Korean
kor.CreateStartShortcut=시작 메뉴 단축 아이콘 만들기
kor.NoKaM=설치 마법사가 '기사와 상인:농민의 반란'이 설치가 안된것으로 확인되었습니다. '기사와 상인 다시만듬'을 실행하기 위해서는 반드시 원본 게임이 설치되어 있어야 합니다. 설치가 중단 됩니다.
kor.CantUpdate=설치 마법사가 갱신할 '기사와 상인 다시만듬'의 기존 버전을 찾을 수 없습니다. 전체 설치 프로그램 대신에 다운로드하여 설치 해주십시오. 설치가 중단 됩니다.
kor.OpenAL=OpenAL을 설치하기위해 설치 마법사가 필요합니까? (강력하게 추천함) '기사와 상인 다시만듬'에서 소리를 작동하는데 필요합니다.
kor.ViewReadme=읽어보기

;Serbian
srb.CreateStartShortcut=Направите Старт Мену Пречицу
srb.NoKaM=Инсталациони чаробњак је приметио да немате Knights and Merchants: The Peasants Rebellion инсталирано.Морате имати оригиналну игру инсталирану да бисте играли KaM Remake.%n%nИнсталације ће престати са радом.
srb.CantUpdate=Инсталациони чаробњак није могао да нађе постојећу верзију KaM Remake да се усавремени.Молимо вас скините и инсталирајте комплетан инсталер уместо тога.%n%nИнсталација ће престати са радом.
srb.OpenAL=Да ли желите да вам инсталациони чаробњакисталира OpenAL? (Врло препоручљиво) Потребно је да бих ѕвукови радили у KaM Remake.
srb.ViewReadme=Прочитајте Реадме

;Chinese
chn.CreateStartShortcut=创建开始菜单快捷方式
chn.NoKaM=安装向导检测到没有《骑士与商人之农民起义》的安装。为了能玩重制版游戏，必须先安装原版游戏。本安装程序将被终止。
chn.CantUpdate=安装向导无法找到一个存在的重制版能够被升级。请重新下载并安装完整的安装包。本安装程序将被终止。
chn.OpenAL=你想用安装向导来安装OpenAL吗？（强烈推荐）这是音效文件运行的必需程序。
chn.ViewReadme=查看自述文件

;Slovenian
slv.CreateStartShortcut=Ustvari bljižnico na meniju
slv.NoKaM=Čarovnik za namestitev je zaznal da nimate nameščeno igro Knights and Merchants: The Peasants Rebellion. Morate imeti nameščeno originalno igro če želite igrati KaM Remake.%n%nNamestitev bo prekinjena
slv.OpenAL=Ali želite namestiti OpenAL? (Močno priporočeno) potrebno je za elovanje zvokov v igri KaM Remake.
slv.ViewReadme=Poglej si opis