; ShopfloorConnect MTC Service Installer - Enhanced Version
; Automated installation with comprehensive error handling and logging
; Version 2.0

[Setup]
AppId={{F8A3B2C1-D4E5-6F7A-8B9C-0D1E2F3A4B5C}
AppName=WJDT ShopfloorConnect MTC Service
AppVersion=2.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_v2
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 to C:\ShopFloorConnect%n  2. Set TCFITDIR environment variable%n  3. Run Ant build to create FIT-MI_Server%n  4. Register Windows service (SFCMTCService)%n  5. Configure West Jefferson CA-LR connection%n%nConfiguration:%n  - Teamcenter Server: 10.233.113.141%n  - Shop Floor PC FQDN: Auto-detected%n  - Site: West Jefferson CA-LR%n%nInstallation log will be saved to:%n  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; 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.txt');

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

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

  LogMessage('Result Code: ' + IntToStr(ResultCode));
  LogMessage('Success: ' + BoolToStr(Success));

  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;
  JavaVersion: String;
  TempOutput: 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 2.0' + #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 5: Verifying Java installation...', '');
      ProgressPage.SetProgress(10, 100);
      LogMessage('========== STEP 1: Verify Java ==========');

      if not FileExists(ExpandConstant('{app}\Java\j2sdk\jre\bin\java.exe')) then
      begin
        ErrorMsg := 'Java runtime not found!' + #13#10#13#10 +
                    'Expected location:' + #13#10 +
                    ExpandConstant('{app}\Java\j2sdk\jre\bin\java.exe') + #13#10#13#10 +
                    'Installation cannot continue.';
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      // Test Java
      if Exec(ExpandConstant('{app}\Java\j2sdk\jre\bin\java.exe'),
              '-version', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
      begin
        LogMessage('Java verification successful');
      end
      else
      begin
        LogMessage('WARNING: Java verification failed, but continuing...');
      end;

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

      if not ExecWithLog('setx', '/m TCFITDIR "C:\ShopFloorConnect"', '', SW_HIDE, 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 (install.bat)
      // ============================================
      ProgressPage.SetText('Step 3 of 5: Running Ant build script...',
                           'This may take 2-3 minutes. Please wait...');
      ProgressPage.SetProgress(40, 100);
      LogMessage('========== STEP 3: Run install.bat ==========');

      // Change to MachineToolClient_Service directory and run install.bat
      // Using echo | to bypass the pause command
      if not ExecWithLog('cmd.exe',
                         '/c cd /d "C:\ShopFloorConnect\MachineToolClient_Service" && echo. | call install.bat',
                         '', SW_SHOW, ResultCode) then
      begin
        ErrorMsg := 'Failed to execute install.bat!' + #13#10#13#10 +
                    'The Ant build script 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('install.bat completed with code: ' + IntToStr(ResultCode));

      // 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 (install.bat) did not create the expected folder.' + #13#10#13#10 +
                    'Common causes:' + #13#10 +
                    '  - Ant build failed (check console output)' + #13#10 +
                    '  - TCFITDIR not recognized (needs system reboot?)' + #13#10 +
                    '  - Insufficient permissions' + #13#10 +
                    '  - Java runtime issue' + #13#10#13#10 +
                    'Installation log: ' + InstallLog + #13#10#13#10 +
                    'You can try running install.bat manually:' + #13#10 +
                    'C:\ShopFloorConnect\MachineToolClient_Service\install.bat';
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('FIT-MI_Server folder verified');

      // Check for critical files
      if not FileExists('C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini') then
      begin
        LogMessage('WARNING: mi_server.ini not found - will be created by config script');
      end
      else
      begin
        LogMessage('mi_server.ini template found');
      end;

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

      Sleep(2000); // Give service registration time to complete

      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 + #13#10#13#10 +
                    'You can try manually registering the service:' + #13#10 +
                    'C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin\SFC_MTC_Tomcat_service.bat install';
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('Windows service SFCMTCService verified');

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

      if not ExecWithLog('cmd.exe',
                         '/c cd /d "C:\ShopFloorConnect" && call "3 - West_Jeff_CA_LR_Update_ini_File.bat"',
                         '', SW_SHOW, ResultCode) or (ResultCode <> 0) then
      begin
        ErrorMsg := 'Failed to configure site settings!' + #13#10 +
                    'Error Code: ' + IntToStr(ResultCode) + #13#10#13#10 +
                    'The service is installed but configuration script failed.' + #13#10#13#10 +
                    'Installation log: ' + InstallLog + #13#10#13#10 +
                    'You can manually run:' + #13#10 +
                    'C:\ShopFloorConnect\3 - West_Jeff_CA_LR_Update_ini_File.bat';
        LogMessage('ERROR: ' + ErrorMsg);
        MsgBox(ErrorMsg, mbError, MB_OK);
        Exit;
      end;

      LogMessage('Site configuration completed');

      // ============================================
      // STEP 4a: Verify Config File
      // ============================================
      ProgressPage.SetText('Step 4a: Verifying configuration file...', '');
      ProgressPage.SetProgress(95, 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 +
                    'The configuration batch file did not create this file.' + #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"
