; ShopfloorConnect MTC Service Installer - Batch-Free Version
; All batch file logic converted to ISS Pascal and PowerShell
; Version 3.0

[Setup]
AppId={{F8A3B2C1-D4E5-6F7A-8B9C-0D1E2F3A4B5C}
AppName=WJDT ShopfloorConnect MTC Service
AppVersion=3.0
AppPublisher=WJDT
AppPublisherURL=http://tsgwp00524.logon.ds.ge.com
AppSupportURL=http://tsgwp00524.logon.ds.ge.com
AppUpdatesURL=http://tsgwp00524.logon.ds.ge.com
DefaultDirName=C:\ShopFloorConnect
CreateAppDir=yes
ChangesAssociations=no
PrivilegesRequired=admin
OutputDir=.\Output
OutputBaseFilename=ShopfloorConnect_Installer_v3
SolidCompression=yes
WizardStyle=modern
SetupIconFile=gea-logo.ico
WizardImageFile=patrick.bmp
WizardSmallImageFile=patrick-sm.bmp
UninstallDisplayIcon={app}\Java\j2sdk\jre\bin\java.exe
DisableWelcomePage=no

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

[Messages]
WelcomeLabel2=This will install the ShopfloorConnect MTC Service on this machine.%n%nThe installer will:%n  1. Copy all required files%n  2. Set TCFITDIR environment variable%n  3. Run Ant build (creates FIT-MI_Server)%n  4. Register Windows service%n  5. Configure site settings (West Jefferson CA-LR)%n%nAll batch file logic has been integrated into this installer for better reliability.%n%nInstallation log: C:\ShopFloorConnect\install.log

[Files]
; Copy ALL files from ShopFloorConnect folder
Source: "ShopFloorConnect\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs

[Dirs]
Name: "{app}\Log"

[Code]
var
  InstallLog: String;
  ProgressPage: TOutputProgressWizardPage;

// Write to installation log file
procedure LogMessage(Msg: String);
var
  LogFile: String;
begin
  LogFile := ExpandConstant('{app}\install.log');
  SaveStringToFile(LogFile, '[' + GetDateTimeString('yyyy-mm-dd hh:nn:ss', #0, #0) + '] ' + Msg + #13#10, True);
end;

// Execute command with output capture and logging
function ExecWithLog(Command, Params, WorkDir: String; ShowWindow: Integer; Wait: TExecWait; var ResultCode: Integer): Boolean;
var
  TempFile: String;
  Output: AnsiString;
  Success: Boolean;
begin
  LogMessage('Executing: ' + Command + ' ' + Params);

  // Create temp file for output
  TempFile := ExpandConstant('{tmp}\output_' + IntToStr(Random(99999)) + '.txt');

  // Execute and capture output to temp file
  Success := Exec('cmd.exe', '/c "' + Command + ' ' + Params + ' > "' + TempFile + '" 2>&1"',
                  WorkDir, ShowWindow, Wait, ResultCode);

  // Read output from temp file
  if FileExists(TempFile) then
  begin
    if LoadStringFromFile(TempFile, Output) then
    begin
      LogMessage('Output:' + #13#10 + String(Output));
    end;
    DeleteFile(TempFile);
  end;

  LogMessage('Result Code: ' + IntToStr(ResultCode));
  if Success then
    LogMessage('Success: True')
  else
    LogMessage('Success: False');

  Result := Success;
end;

procedure InitializeWizard();
begin
  ProgressPage := CreateOutputProgressPage('Installing ShopfloorConnect',
    'Please wait while the MTC Service is being installed and configured.');
end;

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  Result := True;
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  ResultCode: Integer;
  ErrorMsg: String;
  JavaExe: String;
  AntCP: String;
  AntCommand: String;
  ConfigScript: String;
  ScriptPath: String;
begin
  if CurStep = ssPostInstall then
  begin
    // Initialize log file
    InstallLog := ExpandConstant('{app}\install.log');
    SaveStringToFile(InstallLog,
                     '========================================' + #13#10 +
                     'ShopfloorConnect MTC Service Installation' + #13#10 +
                     'Version 3.0 (Batch-Free)' + #13#10 +
                     'Date: ' + GetDateTimeString('yyyy-mm-dd hh:nn:ss', #0, #0) + #13#10 +
                     '========================================' + #13#10#13#10, False);

    ProgressPage.SetText('Installing ShopfloorConnect MTC Service...', '');
    ProgressPage.SetProgress(0, 100);
    ProgressPage.Show;

    try
      // ============================================
      // STEP 1: Verify Java Installation
      // ============================================
      ProgressPage.SetText('Step 1 of 6: Verifying Java installation...', '');
      ProgressPage.SetProgress(10, 100);
      LogMessage('========== STEP 1: Verify Java ==========');

      JavaExe := ExpandConstant('{app}\Java\j2sdk\jre\bin\java.exe');

      if not FileExists(JavaExe) then
      begin
        ErrorMsg := 'Java runtime not found!' + #13#10#13#10 +
                    'Expected location:' + #13#10 + JavaExe + #13#10#13#10 +
                    'Installation cannot continue.';
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      // Test Java version
      if ExecWithLog(JavaExe, '-version', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
      begin
        LogMessage('Java verification successful');
      end
      else
      begin
        LogMessage('WARNING: Java verification failed');
      end;

      // ============================================
      // STEP 2: Set Environment Variable
      // ============================================
      ProgressPage.SetText('Step 2 of 6: Setting TCFITDIR environment variable...', '');
      ProgressPage.SetProgress(20, 100);
      LogMessage('========== STEP 2: Set TCFITDIR ==========');

      if not ExecWithLog('setx', '/m TCFITDIR "C:\ShopFloorConnect"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) or (ResultCode <> 0) then
      begin
        ErrorMsg := 'Failed to set TCFITDIR environment variable!' + #13#10 +
                    'Error Code: ' + IntToStr(ResultCode) + #13#10#13#10 +
                    'You must run this installer as Administrator.' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('TCFITDIR set successfully');
      Sleep(1000);

      // ============================================
      // STEP 3: Run Ant Build Directly
      // ============================================
      ProgressPage.SetText('Step 3 of 6: Running Ant build to create FIT-MI_Server...',
                           'This may take 2-3 minutes. Please wait...');
      ProgressPage.SetProgress(30, 100);
      LogMessage('========== STEP 3: Run Ant Build ==========');

      // Build the Ant command exactly as install.bat does (line 90 of install.bat)
      AntCP := ExpandConstant('{app}\MachineToolClient_Service\install\ant-launcher.jar');

      AntCommand := '-cp "' + AntCP + '" ' +
                    '-Dj.home="C:\ShopFloorConnect\java\j2sdk" ' +
                    '-DSERVICENAME="SFCMTCService" ' +
                    '-DINST_SYS=fit4tc ' +
                    '-DINST_OS=msw ' +
                    '-DINST_DIR="C:\ShopFloorConnect\MachineToolClient_Service" ' +
                    '-DDST_DIR="C:\ShopFloorConnect\FIT-MI_Server" ' +
                    '-DBASE_DIR="C:\ShopFloorConnect" ' +
                    '-Dant.home="C:\ShopFloorConnect\MachineToolClient_Service\install" ' +
                    'org.apache.tools.ant.launch.Launcher ' +
                    '-buildfile "C:\ShopFloorConnect\MachineToolClient_Service\install\ant_install.xml" ' +
                    'doinstall';

      LogMessage('Ant Command: ' + JavaExe + ' ' + AntCommand);

      if not ExecWithLog(JavaExe, AntCommand, 'C:\ShopFloorConnect\MachineToolClient_Service',
                         SW_SHOW, ewWaitUntilTerminated, ResultCode) then
      begin
        ErrorMsg := 'Failed to execute Ant build!' + #13#10#13#10 +
                    'The Java Ant launcher did not run.' + #13#10#13#10 +
                    'Check the installation log for details:' + #13#10 +
                    InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('Ant build completed with exit code: ' + IntToStr(ResultCode));

      if ResultCode <> 0 then
      begin
        LogMessage('WARNING: Ant build returned non-zero exit code');
      end;

      // Give the Ant build time to complete file operations
      ProgressPage.SetText('Waiting for Ant build to finalize...', '');
      Sleep(5000);

      // ============================================
      // STEP 3a: Verify FIT-MI_Server Created
      // ============================================
      ProgressPage.SetText('Step 3a: Verifying FIT-MI_Server folder...', '');
      ProgressPage.SetProgress(55, 100);
      LogMessage('========== STEP 3a: Verify FIT-MI_Server ==========');

      if not DirExists('C:\ShopFloorConnect\FIT-MI_Server') then
      begin
        ErrorMsg := 'Installation Error: FIT-MI_Server folder not created!' + #13#10#13#10 +
                    'The Ant build script did not create the expected folder.' + #13#10#13#10 +
                    'Ant exit code was: ' + IntToStr(ResultCode) + #13#10#13#10 +
                    'Common causes:' + #13#10 +
                    '  - Ant build failed (check log for Java exceptions)' + #13#10 +
                    '  - TCFITDIR not recognized' + #13#10 +
                    '  - Insufficient permissions' + #13#10 +
                    '  - Missing Server package files' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('FIT-MI_Server folder verified');

      // ============================================
      // STEP 3b: Verify Windows Service
      // ============================================
      ProgressPage.SetText('Step 3b: Verifying Windows service registration...', '');
      ProgressPage.SetProgress(70, 100);
      LogMessage('========== STEP 3b: Verify Service ==========');

      Sleep(2000);

      if not Exec('cmd.exe', '/c sc query SFCMTCService', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
      begin
        ErrorMsg := 'Unable to query Windows service!' + #13#10#13#10 +
                    'Could not check if SFCMTCService was registered.' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: Cannot query service');
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      if ResultCode <> 0 then
      begin
        ErrorMsg := 'Service Registration Failed!' + #13#10#13#10 +
                    'The Windows service "SFCMTCService" was not created.' + #13#10 +
                    'SC Query Error Code: ' + IntToStr(ResultCode) + #13#10#13#10 +
                    'The Ant build may have failed during service registration.' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('Windows service SFCMTCService verified');

      // ============================================
      // STEP 4: Configure Site Settings (PowerShell)
      // ============================================
      ProgressPage.SetText('Step 4 of 6: Configuring West Jefferson settings...', '');
      ProgressPage.SetProgress(80, 100);
      LogMessage('========== STEP 4: Configure Site ==========');

      // Build PowerShell script to replace the batch file logic
      ConfigScript :=
        '# ShopfloorConnect INI Configuration Script' + #13#10 +
        '$ErrorActionPreference = "Stop"' + #13#10 +
        '' + #13#10 +
        '$iniFile = "C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini"' + #13#10 +
        '$tempFile = "$iniFile.tmp"' + #13#10 +
        '$fsw_ip = "10.233.113.141"' + #13#10 +
        '$fsw_port = "8080/tcdnc/services"' + #13#10 +
        '' + #13#10 +
        'Write-Host "Getting computer FQDN..."' + #13#10 +
        'try {' + #13#10 +
        '    $fqdn = [System.Net.Dns]::GetHostEntry("localhost").HostName' + #13#10 +
        '    Write-Host "Computer FQDN: $fqdn"' + #13#10 +
        '} catch {' + #13#10 +
        '    Write-Host "ERROR: Could not determine FQDN: $_"' + #13#10 +
        '    exit 1' + #13#10 +
        '}' + #13#10 +
        '' + #13#10 +
        'if (-not (Test-Path $iniFile)) {' + #13#10 +
        '    Write-Host "ERROR: INI file not found: $iniFile"' + #13#10 +
        '    exit 1' + #13#10 +
        '}' + #13#10 +
        '' + #13#10 +
        'Write-Host "Updating INI file..."' + #13#10 +
        '' + #13#10 +
        '# Read and update the INI file' + #13#10 +
        '$content = Get-Content $iniFile' + #13#10 +
        '$updatedContent = @()' + #13#10 +
        '' + #13#10 +
        'foreach ($line in $content) {' + #13#10 +
        '    if ($line -match "^\s*local_ip\s*=") {' + #13#10 +
        '        $updatedContent += "local_ip = $fqdn"' + #13#10 +
        '        Write-Host "  Updated: local_ip = $fqdn"' + #13#10 +
        '    } elseif ($line -match "^\s*fsw_ip\s*=") {' + #13#10 +
        '        $updatedContent += "fsw_ip = $fsw_ip"' + #13#10 +
        '        Write-Host "  Updated: fsw_ip = $fsw_ip"' + #13#10 +
        '    } elseif ($line -match "^\s*fsw_port\s*=") {' + #13#10 +
        '        $updatedContent += "fsw_port = $fsw_port"' + #13#10 +
        '        Write-Host "  Updated: fsw_port = $fsw_port"' + #13#10 +
        '    } elseif ($line -match "^\s*RxEndTimeout\s*=") {' + #13#10 +
        '        $updatedContent += "RxEndTimeout = 6000"' + #13#10 +
        '        $updatedContent += ""' + #13#10 +
        '        Write-Host "  Updated: RxEndTimeout = 6000"' + #13#10 +
        '    } else {' + #13#10 +
        '        $updatedContent += $line' + #13#10 +
        '    }' + #13#10 +
        '}' + #13#10 +
        '' + #13#10 +
        '# Write to temp file first' + #13#10 +
        'try {' + #13#10 +
        '    $updatedContent | Out-File -FilePath $tempFile -Encoding UTF8 -Force' + #13#10 +
        '    Write-Host "Temp file created successfully"' + #13#10 +
        '} catch {' + #13#10 +
        '    Write-Host "ERROR: Failed to create temp file: $_"' + #13#10 +
        '    exit 1' + #13#10 +
        '}' + #13#10 +
        '' + #13#10 +
        '# Replace original with updated file' + #13#10 +
        'try {' + #13#10 +
        '    Move-Item -Path $tempFile -Destination $iniFile -Force' + #13#10 +
        '    Write-Host "INI file updated successfully"' + #13#10 +
        '    exit 0' + #13#10 +
        '} catch {' + #13#10 +
        '    Write-Host "ERROR: Failed to replace INI file: $_"' + #13#10 +
        '    exit 1' + #13#10 +
        '}';

      // Save PowerShell script to temp file
      ScriptPath := ExpandConstant('{tmp}\config_ini.ps1');
      SaveStringToFile(ScriptPath, ConfigScript, False);
      LogMessage('PowerShell script saved to: ' + ScriptPath);

      // Execute PowerShell script
      if not ExecWithLog('powershell.exe',
                         '-NoProfile -ExecutionPolicy Bypass -File "' + ScriptPath + '"',
                         '', SW_SHOW, ewWaitUntilTerminated, ResultCode) or (ResultCode <> 0) then
      begin
        ErrorMsg := 'Failed to configure site settings!' + #13#10 +
                    'PowerShell Exit Code: ' + IntToStr(ResultCode) + #13#10#13#10 +
                    'The service is installed but configuration failed.' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        DeleteFile(ScriptPath);
        Exit;
      end;

      DeleteFile(ScriptPath);
      LogMessage('Site configuration completed successfully');

      // ============================================
      // STEP 4a: Verify Config File
      // ============================================
      ProgressPage.SetText('Step 4a: Verifying configuration file...', '');
      ProgressPage.SetProgress(90, 100);
      LogMessage('========== STEP 4a: Verify Config ==========');

      if not FileExists('C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini') then
      begin
        ErrorMsg := 'Configuration Error: mi_server.ini not found!' + #13#10#13#10 +
                    'Expected file:' + #13#10 +
                    'C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini' + #13#10#13#10 +
                    'Installation log: ' + InstallLog;
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('Configuration file verified');

      // ============================================
      // STEP 5: Installation Complete
      // ============================================
      ProgressPage.SetProgress(100, 100);
      LogMessage('========== INSTALLATION COMPLETE ==========');
      LogMessage('All steps completed successfully');

      Sleep(1000);

    finally
      ProgressPage.Hide;
    end;

    // Show success message
    MsgBox('Installation Complete!' + #13#10#13#10 +
           'The ShopfloorConnect MTC Service has been installed and configured.' + #13#10#13#10 +
           'Details:' + #13#10 +
           '  • Windows Service: SFCMTCService (Registered)' + #13#10 +
           '  • Startup Type: Delayed Automatic' + #13#10 +
           '  • Site: West Jefferson CA-LR' + #13#10 +
           '  • Teamcenter Server: 10.233.113.141' + #13#10 +
           '  • Shop Floor PC FQDN: Auto-detected' + #13#10#13#10 +
           'Config file:' + #13#10 +
           'C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini' + #13#10#13#10 +
           'Installation log:' + #13#10 +
           InstallLog + #13#10#13#10 +
           'To start the service:' + #13#10 +
           '  1. Open Services (services.msc)' + #13#10 +
           '  2. Find "SFCMTCService"' + #13#10 +
           '  3. Right-click → Start' + #13#10#13#10 +
           'Or run: sc start SFCMTCService',
           mbInformation, MB_OK);
  end;
end;

[UninstallDelete]
Type: filesandordirs; Name: "{app}\Log\*"
Type: filesandordirs; Name: "{app}\FIT-MI_Server\webapps\wut\WEB-INF\conf\*.tmp"
Type: files; Name: "{app}\install.log"
