File size: 13,249 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
 *  MSI Builder Script - สร้างไฟล์ติดตั้ง Windows
 *  Chahua Development Thailand
 *  CEO: Saharath C.
 * 
 *  Purpose: สร้าง Windows Installer (.msi) สำหรับ deployment
 */

const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

class MSIBuilder {
    constructor() {
        this.config = {
            productName: 'Chahuadev Framework',
            productVersion: '1.0.0',
            manufacturer: 'Chahua Development Thailand',
            description: 'Universal Execution Framework by CEO Saharath C.',
            outputDir: './chahuadev-framework/build',
            tempDir: './chahuadev-framework/build/temp',
            //  Logo and Icon Configuration
            iconConfig: {
                iconFile: 'icon.png',
                logoFile: 'logo.png',
                splashIcon: 'splash.html'
            }
        };
        
        console.log(' MSI Builder initialized');
        console.log(' Logo system enabled');
    }

    async buildMSI() {
        try {
            console.log(' Starting MSI build process...');
            
            // Step 1: Prepare build directory
            await this.prepareBuildDirectory();
            
            // Step 2: Copy application files
            await this.copyApplicationFiles();
            
            // Step 3: Generate WiX configuration
            await this.generateWiXConfig();
            
            // Step 4: Build MSI (requires WiX Toolset)
            await this.compileMSI();
            
            console.log(' MSI build completed successfully!');
            
        } catch (error) {
            console.error(' MSI build failed:', error.message);
            throw error;
        }
    }

    async prepareBuildDirectory() {
        console.log(' Preparing build directories...');
        
        // Create directories
        const dirs = [
            this.config.outputDir,
            this.config.tempDir,
            path.join(this.config.tempDir, 'app'),
            path.join(this.config.tempDir, 'resources')
        ];
        
        for (const dir of dirs) {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        }
    }

    async copyApplicationFiles() {
        console.log(' Copying application files...');
        
        const filesToCopy = [
            'main.js',
            'preload.js',
            'index.html',
            'splash.html',
            'validation_gateway.js',
            'package.json',
            //  Logo and Assets (Essential for Splash Screen)
            'icon.png',
            'logo.png',
            'logo.ico',
            //  Additional logo formats (optional)
            'logo.svg',
            'app-icon.png',
            'app-icon.ico',
            //  User Guides
            'USER_GUIDE_TH.md',
            'USER_GUIDE_EN.md',
            'modules/',
            'strategies/',
            'plugins/',
            'config/'
        ];
        
        // แก้ไขเส้นทางให้ถูกต้อง - ใช้ root directory แทน subdirectory
        const sourceBase = '.'; // ใช้ current directory
        const destBase = path.join(this.config.tempDir, 'app');
        
        for (const file of filesToCopy) {
            const sourcePath = path.join(sourceBase, file);
            const destPath = path.join(destBase, file);
            
            if (fs.existsSync(sourcePath)) {
                this.copyRecursive(sourcePath, destPath);
                console.log(`    Copied: ${file}`);
            } else if (file.includes('.png') || file.includes('.ico')) {
                console.log(`    Logo file missing: ${file} - will use fallback`);
            }
        }
        
        //  Copy logo to resources directory
        await this.copyLogoAssets();
    }

    copyRecursive(src, dest) {
        const stat = fs.statSync(src);
        
        if (stat.isDirectory()) {
            if (!fs.existsSync(dest)) {
                fs.mkdirSync(dest, { recursive: true });
            }
            
            const files = fs.readdirSync(src);
            for (const file of files) {
                this.copyRecursive(
                    path.join(src, file),
                    path.join(dest, file)
                );
            }
        } else {
            fs.copyFileSync(src, dest);
        }
    }

    //  NEW METHOD: Copy logo assets for installer
    async copyLogoAssets() {
        console.log(' Copying logo assets...');
        
        const resourcesDir = path.join(this.config.tempDir, 'resources');
        const logoAssets = [
            { src: 'icon.png', dest: 'app-icon.png' },
            { src: 'logo.png', dest: 'logo.png' },
            { src: 'logo.ico', dest: 'app-icon.ico' }
        ];
        
        for (const asset of logoAssets) {
            // แก้ไขเส้นทาง source ให้ถูกต้อง
            const srcPath = path.join('.', asset.src); // ใช้ current directory
            const destPath = path.join(resourcesDir, asset.dest);
            
            if (fs.existsSync(srcPath)) {
                fs.copyFileSync(srcPath, destPath);
                console.log(`    Logo copied: ${asset.src}  ${asset.dest}`);
            } else {
                // Create a simple fallback icon
                await this.createFallbackIcon(destPath, asset.dest);
            }
        }
    }

    //  NEW METHOD: Create fallback logo if original missing
    async createFallbackIcon(destPath, filename) {
        if (filename.endsWith('.png')) {
            // Create a simple SVG-based PNG fallback (text representation)
            const fallbackContent = `<!-- Chahuadev Framework Logo Fallback -->\n<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg">\n  <rect width="128" height="128" fill="#1a1a2e" rx="18"/>\n  <text x="64" y="75" font-family="Arial" font-size="48" font-weight="bold" text-anchor="middle" fill="#00ff88">C</text>\n</svg>`;
            fs.writeFileSync(destPath.replace('.png', '.svg'), fallbackContent);
            console.log(`    Created fallback logo: ${filename}`);
        }
    }

    async generateWiXConfig() {
        console.log(' Generating WiX configuration...');
        
        const wixConfig = `<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" 
           Name="${this.config.productName}" 
           Language="1033" 
           Version="${this.config.productVersion}" 
           Manufacturer="${this.config.manufacturer}" 
           UpgradeCode="12345678-1234-1234-1234-123456789012">
    
    <Package InstallerVersion="200" 
             Compressed="yes" 
             InstallScope="perMachine" 
             Description="${this.config.description}" />

    <MajorUpgrade DowngradeErrorMessage="A newer version is already installed." />
    <MediaTemplate EmbedCab="yes" />

    <!--  Icon Configuration -->
    <Icon Id="ProductIcon" SourceFile="$(var.SourceDir)\\resources\\app-icon.ico" />
    <Property Id="ARPPRODUCTICON" Value="ProductIcon" />

    <Feature Id="ProductFeature" Title="Chahuadev Framework" Level="1">
      <ComponentGroupRef Id="ProductComponents" />
      <ComponentGroupRef Id="LogoComponents" />
      <ComponentGroupRef Id="UserGuideComponents" />
    </Feature>
  </Product>

  <Fragment>
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder">
        <Directory Id="INSTALLFOLDER" Name="Chahuadev Framework" />
      </Directory>
    </Directory>
  </Fragment>

  <Fragment>
    <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
      <Component Id="MainExecutable" Guid="*">
        <File Id="main.js" Source="$(var.SourceDir)\\app\\main.js" KeyPath="yes" />
        <File Id="app.js" Source="$(var.SourceDir)\\app\\app.js" />
        <File Id="cli.js" Source="$(var.SourceDir)\\app\\cli.js" />
        <File Id="package.json" Source="$(var.SourceDir)\\app\\package.json" />
        <File Id="index.html" Source="$(var.SourceDir)\\app\\index.html" />
        <File Id="splash.html" Source="$(var.SourceDir)\\app\\splash.html" />
      </Component>
    </ComponentGroup>
    
    <!--  Logo Components -->
    <ComponentGroup Id="LogoComponents" Directory="INSTALLFOLDER">
      <Component Id="LogoAssets" Guid="*">
        <File Id="icon.png" Source="$(var.SourceDir)\\app\\icon.png" />
        <File Id="logo.png" Source="$(var.SourceDir)\\app\\logo.png" />
      </Component>
    </ComponentGroup>
    
    <!--  User Guide Components -->
    <ComponentGroup Id="UserGuideComponents" Directory="INSTALLFOLDER">
      <Component Id="UserGuides" Guid="*">
        <File Id="USER_GUIDE_TH.md" Source="$(var.SourceDir)\\app\\USER_GUIDE_TH.md" />
        <File Id="USER_GUIDE_EN.md" Source="$(var.SourceDir)\\app\\USER_GUIDE_EN.md" />
      </Component>
    </ComponentGroup>
  </Fragment>
</Wix>`;

        const wixPath = path.join(this.config.tempDir, 'chahuadev.wxs');
        fs.writeFileSync(wixPath, wixConfig);
        
        console.log('    WiX configuration generated');
        console.log('    Logo integration included');
    }

    async compileMSI() {
        console.log(' Compiling MSI package...');
        
        return new Promise((resolve, reject) => {
            // Check if WiX Toolset is available
            exec('candle -?', (error) => {
                if (error) {
                    console.warn(' WiX Toolset not found. Installing npm packages instead...');
                    this.createPortablePackage();
                    resolve();
                    return;
                }
                
                // Compile with WiX
                const wixPath = path.join(this.config.tempDir, 'chahuadev.wxs');
                const objPath = path.join(this.config.tempDir, 'chahuadev.wixobj');
                const msiPath = path.join(this.config.outputDir, 'ChahuadevFramework.msi');
                
                // Candle (compile)
                exec(`candle "${wixPath}" -out "${objPath}"`, (error) => {
                    if (error) {
                        reject(new Error(`Candle compilation failed: ${error.message}`));
                        return;
                    }
                    
                    // Light (link)
                    exec(`light "${objPath}" -out "${msiPath}"`, (error) => {
                        if (error) {
                            reject(new Error(`Light linking failed: ${error.message}`));
                            return;
                        }
                        
                        console.log(`    MSI created: ${msiPath}`);
                        resolve();
                    });
                });
            });
        });
    }

    createPortablePackage() {
        console.log(' Creating portable package instead...');
        
        const packageInfo = {
            name: this.config.productName,
            version: this.config.productVersion,
            description: this.config.description,
            author: this.config.manufacturer,
            instructions: [
                '1. Extract this package to desired location',
                '2. Run: npm install',
                '3. Start: node app.js',
                '4. CLI: node cli.js --help',
                '5. For user instructions, see USER_GUIDE_TH.md (Thai) or USER_GUIDE_EN.md (English)'
            ],
            requirements: [
                'Node.js v16.0.0 or higher',
                'npm v7.0.0 or higher'
            ],
            userGuides: [
                'USER_GUIDE_TH.md - Thai language user manual',
                'USER_GUIDE_EN.md - English language user manual'
            ]
        };
        
        const readmePath = path.join(this.config.outputDir, 'INSTALLATION.md');
        const readme = `# ${packageInfo.name} v${packageInfo.version}

${packageInfo.description}

## Requirements
${packageInfo.requirements.map(req => `- ${req}`).join('\n')}

## Installation Instructions
${packageInfo.instructions.map((step, i) => `${i + 1}. ${step}`).join('\n')}

## User Guides
${packageInfo.userGuides.map(guide => `- ${guide}`).join('\n')}

## Support
For support, contact: ${packageInfo.author}
`;

        fs.writeFileSync(readmePath, readme);
        fs.writeFileSync(
            path.join(this.config.outputDir, 'package-info.json'),
            JSON.stringify(packageInfo, null, 2)
        );
        
        console.log('    Portable package created');
    }

    async clean() {
        console.log(' Cleaning temporary files...');
        
        if (fs.existsSync(this.config.tempDir)) {
            fs.rmSync(this.config.tempDir, { recursive: true, force: true });
        }
        
        console.log('    Cleanup completed');
    }
}

// CLI Usage
if (require.main === module) {
    const builder = new MSIBuilder();
    
    builder.buildMSI()
        .then(() => builder.clean())
        .catch((error) => {
            console.error('Build failed:', error);
            process.exit(1);
        });
}

module.exports = MSIBuilder;