; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName           "폰트바다 매니저"
#define MyAppVersion        "3.0"
#define MyAppVerName        "36.MR"
#define MyAppBuildData      "B23022301.W10DNF4"
#define MyAppPublisher      "(주)한양정보통신"
#define MyAppURL            "http://www.fontbada.co.kr/"
#define MyAppFolderName     "FontbadaManager"
#define MyAppDataName       "fontbada3"
#define MyAppProcessName    "FontManager"
#define MyAppRootPath       "{localappdata}\hanyang"
#define MyAppWindowName     "FontbadaManager"
#define MyAppFilter         "fontmanager.exe"
#define MyAppMinOS          10


[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                       = {{A2670E5F-4D34-4042-A9C5-5A3BC9547B37}
AppName                     = {#MyAppName}
AppVersion                  = {#MyAppVersion}
AppVerName                  = {#MyAppName}
AppPublisher                = {#MyAppPublisher}
CreateAppDir                = no
OutputDir                   = ./Output
OutputBaseFilename          = FontBada3_Manager_Setup-{#MyAppVersion}.{#MyAppVerName}{#MyAppBuildData}
Compression                 = lzma
SolidCompression            = yes
DisableProgramGroupPage     = yes
SetupIconFile               = fontmanager.ico
LicenseFile                 = License.txt
WizardImageFile             = wizard.bmp
DisableReadyPage            = yes
AppCopyright                = Copyright ⓒ 2017 by (주)한양정보통신 All Rights Reserved.
VersionInfoVersion          = 1.0.0.0
Uninstallable               = true
;PrivilegesRequired         = admin


[Messages]


[Languages]
Name: Korean; MessagesFile: "Korean.isl";


[Files]
; 실행 파일
Source: "FontManager/FontManager.exe";                              DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/FontManager.exe.config";                       DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/MicrosoftEdgeWebview2Setup.exe";               DestDir: "{#MyAppRootPath}\{#MyAppDataName}\";                              Flags: ignoreversion


; 추가 라이브러리
Source: "FontManager/Newtonsoft.Json.dll";                          DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/Microsoft.Web.WebView2.Core.dll";              DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/Microsoft.Web.WebView2.WinForms.dll";          DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/Microsoft.Web.WebView2.Wpf.dll";               DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\";                            Flags: ignoreversion
Source: "FontManager/runtimes\win-arm64\native\WebView2Loader.dll"; DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\runtimes\win-arm64\native\";  Flags: ignoreversion
Source: "FontManager/runtimes\win-x64\native\WebView2Loader.dll";   DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\runtimes\win-x64\native\";    Flags: ignoreversion
Source: "FontManager/runtimes\win-x86\native\WebView2Loader.dll";   DestDir: "{#MyAppRootPath}\{#MyAppFolderName}\runtimes\win-x86\native\";    Flags: ignoreversion


[Code]
type
    TProcessEntry = record
        PID:    DWORD;
        Name:   string;
    end;
    TProcessEntryList = array of TProcessEntry;

var
    ExitCode: Boolean;


function GetProcessList(const Filter: string; out List: TProcessEntryList): Integer;
var
    I:              Integer;
    WQLQuery:       string;
    WbemLocator:    Variant;
    WbemServices:   Variant;
    WbemObject:     Variant;
    WbemObjectSet:  Variant;
begin
    Result          := 0;
    WbemLocator     := CreateOleObject('WbemScripting.SWbemLocator');
    WbemServices    := WbemLocator.ConnectServer('localhost', 'root\CIMV2');
    WQLQuery        := 'SELECT ProcessId, Name FROM Win32_Process WHERE Name LIKE "%' + Filter +'%"';
    WbemObjectSet   := WbemServices.ExecQuery(WQLQuery);
    if not VarIsNull(WbemObjectSet) and (WbemObjectSet.Count > 0) then
    begin
        Result := WbemObjectSet.Count;
        SetArrayLength(List, WbemObjectSet.Count);
        for I := 0 to WbemObjectSet.Count - 1 do
        begin
            WbemObject := WbemObjectSet.ItemIndex(I);
            if not VarIsNull(WbemObject) then
            begin
                List[I].PID := WbemObject.ProcessId;
                List[I].Name := WbemObject.Name;
            end;
        end;
    end;
end;


function IsFontManagerProcesss: Boolean;
var
    I:              Integer;
    Filter:         string;
    ProcessList:    TProcessEntryList;
begin
    Filter  := '{#MyAppFilter}';
    Result  := false;
    if GetProcessList(Filter, ProcessList) > 0 then
        for I := 0 to (GetArrayLength(ProcessList) - 1) do
        begin
            if CompareText(Filter, ProcessList[I].Name) = 0 then
            begin
                Result := True;
                Exit;
            end
        end;
end;


function IsFontbadaManagerWindow: Boolean;
begin
    Result := (FindWindowByWindowName('{#MyAppWindowName}') <> 0);
end;


function GetUninstallString: string;
var
    sUnInstPath:        string;
    sUnInstallString:   string;
begin
    Result := '';
    sUnInstPath := ExpandConstant('Software\Microsoft\Windows\CurrentVersion\Uninstall\{{A2670E5F-4D34-4042-A9C5-5A3BC9547B37}_is1');
    sUnInstallString := '';
    if not RegQueryStringValue(HKLM, sUnInstPath, 'UninstallString', sUnInstallString) then
        RegQueryStringValue(HKCU, sUnInstPath, 'UninstallString', sUnInstallString);
    Result := sUnInstallString;
end;


function IsWindowsVersionOrNewer(Major, Minor: Integer): Boolean;
var
    Version: TWindowsVersion;
begin
    GetWindowsVersionEx(Version);
    Result := (Version.Major > Major) or ((Version.Major = Major) and (Version.Minor >= Minor));
end;


procedure DeinitializeSetup();
var
    ResultCode: Integer;
begin
    // Log(Format('DeinitializeSetup ExitCode -> [ %d ]', [ExitCode]));
    if ExitCode = True then
    begin
        Exec(ExpandConstant('{#MyAppRootPath}\{#MyAppDataName}\MicrosoftEdgeWebview2Setup.exe'), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode);
        MsgBox('설치가 모두 완료되었습니다. 폰트바다 매니저를 시작합니다.', mbInformation, MB_OK);
        Exec(ExpandConstant('{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe'), '', '', SW_SHOW, ewNoWait, ResultCode);
    end;
end;


procedure CancelButtonClick(CurPageID: Integer; var Cancel, Confirm: Boolean);
begin
    ExitCode  := False;
end;


procedure CurStepChanged(CurStep: TSetupStep);
begin
    if CurStep = ssInstall then
    begin
        // Log(Format('CurStepChanged CurStep -> [ %d ]', [CurStep]));
        ExitCode := True;
    end
    else if CurStep = ssDone then
    begin
        // Log(Format('CurStepChanged CurStep -> [ %d ]', [CurStep]));
        ExitCode := True;
    end;
end;


procedure InitializeWizard;
begin
    with TNewStaticText.Create(WizardForm) do
    begin
        Left    := WizardForm.FilenameLabel.Left;
        Top     := WizardForm.FilenameLabel.Top;
        Width   := WizardForm.FilenameLabel.Width;
        Height  := WizardForm.FilenameLabel.Height;
        Caption := ExpandConstant('폰트바다3 설치중...');
    end;
    WizardForm.FilenameLabel.Visible := False;
end;


function CheckOSVersion: Boolean;
begin
    Result := True;
    if not IsWindowsVersionOrNewer({#MyAppMinOS}, 0) then
    begin
        MsgBox('이 프로그램은 Windows 10 이상을 지원합니다. 설치를 종료합니다.', mbCriticalError, MB_OK);
        Result := False;
    end;
end;


function CheckRunProcess: Boolean;
begin
    Result := True;
    if IsFontManagerProcesss and IsFontbadaManagerWindow then
    begin
        MsgBox('폰트바다 매니저({#MyAppWindowName})가 실행 중입니다. 정상 종료(로그 아웃) 후 다시 실행해 주세요.', mbCriticalError, MB_OK);
        Result := False;
    end;
end;


function InitializeSetup: Boolean;
var
    ResultCode:         Integer;
    UnInstallString:    string;
begin
    ExitCode  := False;
    Result    := False;

    // 윈도우 버전 체크
    if CheckOSVersion = False then
    begin
        Exit;
    end

    // 폰트바다 매니저 실행 상태 확인
    if CheckRunProcess = False then
    begin
        Exit;
    end

    // 언인스톨러 확인
    if RegValueExists(HKEY_LOCAL_MACHINE,'Software\Microsoft\Windows\CurrentVersion\Uninstall\{A2670E5F-4D34-4042-A9C5-5A3BC9547B37}_is1', 'UninstallString') then
    begin
        MsgBox(ExpandConstant('이전 버전 폰트바다 매니저가 존재합니다. 삭제 후 설치를 진행합니다.'), mbInformation, MB_OK);
        UnInstallString := GetUninstallString();
        UnInstallString := RemoveQuotes(UnInstallString);
        Exec(ExpandConstant(UnInstallString), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode);
        // Log(Format('UnInstall ResultCode -> [ %d ]', [ResultCode]));
        if ResultCode > 0 then
        begin
            Exit;
        end;
    end;
    Result := True;
end;


[Icons]
Name: {userdesktop}\폰트바다; Filename: {#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe; WorkingDir: {#MyAppRootPath}\{#MyAppFolderName}\; Comment: "폰트바다 매니저"; IconFilename: {#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe;
Name: {userstartup}\폰트바다; Filename: {#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe; workingdir: {#MyAppRootPath}\{#MyAppFolderName}\;


[Run]
Filename: "schtasks";Parameters: "/create /sc onLogon /tn FontManager /tr /f ""'{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe'"" /RL HIGHEST /DELAY 0000:10"; Flags:ShellExec;


[Registry]
; keys for 32-bit systems
Root: HKCU32; \
    Subkey: "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"; ValueType: String; \
    ValueName: "{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe"; ValueData: "RUNASADMIN"; Flags: uninsdeletekeyifempty uninsdeletevalue; Check: not IsWin64
Root: HKLM32; \
    Subkey: "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"; ValueType: String; \
    ValueName: "{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe"; ValueData: "RUNASADMIN"; Flags: uninsdeletekeyifempty uninsdeletevalue; Check: not IsWin64

; keys for 64-bit systems
Root: HKCU64; \
    Subkey: "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"; ValueType: String; \
    ValueName: "{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe"; ValueData: "RUNASADMIN"; Flags: uninsdeletekeyifempty uninsdeletevalue; Check: IsWin64
Root: HKLM64; \
    Subkey: "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"; ValueType: String; \
    ValueName: "{#MyAppRootPath}\{#MyAppFolderName}\{#MyAppProcessName}.exe"; ValueData: "RUNASADMIN"; Flags: uninsdeletekeyifempty uninsdeletevalue; Check: IsWin64
