Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gulpfile.js - github.com/betaflight/betaflight-configurator.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ae7ac4e2962173fbf6607b140d0127465ce25e2a (plain)
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
'use strict';

const child_process = require('child_process');
const fs = require('fs');
const fse = require('fs-extra');
const https = require('follow-redirects').https;
const path = require('path');

const zip = require('gulp-zip');
const del = require('del');
const NwBuilder = require('nw-builder');
const innoSetup = require('@quanle94/innosetup');
const deb = require('gulp-debian');
const buildRpm = require('rpm-builder');
const commandExistsSync = require('command-exists').sync;
const targz = require('targz');

const gulp = require('gulp');
const rollup = require('rollup');
const concat = require('gulp-concat');
const yarn = require("gulp-yarn");
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const jeditor = require("gulp-json-editor");
const xmlTransformer = require("gulp-xml-transformer");
const os = require('os');
const git = require('simple-git')();
const source = require('vinyl-source-stream');
const stream = require('stream');
const prompt = require('gulp-prompt');
const less = require('gulp-less');
const sourcemaps = require('gulp-sourcemaps');

const cordova = require("cordova-lib").cordova;

const browserify = require('browserify');
const glob = require('glob');

const DIST_DIR = './dist/';
const APPS_DIR = './apps/';
const DEBUG_DIR = './debug/';
const RELEASE_DIR = './release/';
const CORDOVA_DIR = './cordova/';
const CORDOVA_DIST_DIR = './dist_cordova/';

const LINUX_INSTALL_DIR = '/opt/betaflight';

const NODE_ENV = process.env.NODE_ENV || 'production';

const NAME_REGEX = /-/g;

const nwBuilderOptions = {
    version: '0.67.1',
    files: `${DIST_DIR}**/*`,
    macIcns: './src/images/bf_icon.icns',
    macPlist: { 'CFBundleDisplayName': 'Betaflight Configurator'},
    winIco: './src/images/bf_icon.ico',
    zip: false,
};

const nwArmVersion = 'nw60-arm64_2022-01-08';

let metadata = {};

let cordovaDependencies = true;


//-----------------
//Pre tasks operations
//-----------------

const SELECTED_PLATFORMS = getInputPlatforms();


//-----------------
//Tasks
//-----------------

gulp.task('clean', gulp.parallel(clean_dist, clean_apps, clean_debug, clean_release, clean_cordova));

gulp.task('clean-dist', clean_dist);

gulp.task('clean-apps', clean_apps);

gulp.task('clean-debug', clean_debug);

gulp.task('clean-release', clean_release);

gulp.task('clean-cache', clean_cache);

gulp.task('clean-cordova', clean_cordova);

gulp.task('test-cordova', cordova_browserify);


// Function definitions are processed before function calls.

function process_package_release(done) {
    getGitRevision(done, processPackage, true);
}

function process_package_debug(done) {
    getGitRevision(done, processPackage, false);
}

// dist_yarn MUST be done after dist_src

const distCommon = gulp.series(dist_src, dist_less, dist_changelog, dist_yarn, dist_locale, dist_libraries, dist_resources, dist_rollup, gulp.series(cordova_dist()));

const distBuild = gulp.series(process_package_release, distCommon);

const debugDistBuild = gulp.series(process_package_debug, distCommon);

const distRebuild = gulp.series(clean_dist, distBuild);
gulp.task('dist', distRebuild);

const appsBuild = gulp.series(gulp.parallel(clean_apps, distRebuild), apps, gulp.series(cordova_apps(true)), gulp.parallel(listPostBuildTasks(APPS_DIR)));
gulp.task('apps', appsBuild);

const debugAppsBuild = gulp.series(gulp.parallel(clean_debug, gulp.series(clean_dist, debugDistBuild)), debug, gulp.series(cordova_apps(false)), gulp.parallel(listPostBuildTasks(DEBUG_DIR)));

const debugBuildNoStart = gulp.series(debugDistBuild, debug, gulp.parallel(listPostBuildTasks(DEBUG_DIR)));
const debugBuild = gulp.series(debugBuildNoStart, start_debug);
gulp.task('debug', debugBuild);
gulp.task('debug-no-start', debugBuildNoStart);

const releaseBuild = gulp.series(gulp.parallel(clean_release, appsBuild), gulp.parallel(listReleaseTasks(true, APPS_DIR)));
gulp.task('release', releaseBuild);

const debugReleaseBuild = gulp.series(gulp.parallel(clean_release, debugAppsBuild), gulp.parallel(listReleaseTasks(false, DEBUG_DIR)));
gulp.task('debug-release', debugReleaseBuild);

gulp.task('default', debugBuild);


// -----------------
// Helper functions
// -----------------

// Get platform from commandline args
// #
// # gulp <task> [<platform>]+        Run only for platform(s) (with <platform> one of --linux64, --linux32, --armv8, --osx64, --win32, --win64, or --android)
// #
function getInputPlatforms() {
    const supportedPlatforms = ['linux64', 'linux32', 'armv8', 'osx64', 'win32', 'win64', 'android'];
    const platforms = [];
    const regEx = /--(\w+)/;

    for (let i = 3; i < process.argv.length; i++) {
        const arg = process.argv[i].match(regEx)[1];
        if (supportedPlatforms.indexOf(arg) > -1) {
            platforms.push(arg);
        } else if (arg === 'nowinicon') {
            console.log('ignoring winIco');
            delete nwBuilderOptions['winIco'];
        } else if (arg === 'skipdep') {
            console.log('ignoring cordova dependencies');
            cordovaDependencies = false;
        } else {
            console.log(`Unknown platform: ${arg}`);
            process.exit();
        }
    }

    if (platforms.length === 0) {
        const defaultPlatform = getDefaultPlatform();
        if (supportedPlatforms.indexOf(defaultPlatform) > -1) {
            platforms.push(defaultPlatform);
        } else {
            console.error(`Your current platform (${os.platform()}) is not a supported build platform. Please specify platform to build for on the command line.`);
            process.exit();
        }
    }

    if (platforms.length > 0) {
        console.log(`Building for platform(s): ${platforms}.`);
    } else {
        console.error('No suitables platforms found.');
        process.exit();
    }

    return platforms;
}

// Gets the default platform to be used
function getDefaultPlatform() {
    let defaultPlatform;
    switch (os.platform()) {
    case 'darwin':
        defaultPlatform = 'osx64';

        break;
    case 'linux':
        defaultPlatform = 'linux64';

        break;
    case 'win32':
        defaultPlatform = 'win64';

        break;

    default:
        defaultPlatform = '';

        break;
    }
    return defaultPlatform;
}


function getPlatforms() {
    return SELECTED_PLATFORMS.slice();
}

function removeItem(platforms, item) {
    const index = platforms.indexOf(item);
    if (index >= 0) {
        platforms.splice(index, 1);
    }
}

function getRunDebugAppCommand(arch) {

    let command;

    switch (arch) {
    case 'osx64':
        const packageName = `${metadata.name}.app`;
        command = `open ${path.join(DEBUG_DIR, metadata.name, arch, packageName)}`;

        break;

    case 'linux64':
    case 'linux32':
    case 'armv8':
        command = path.join(DEBUG_DIR, metadata.name, arch, metadata.name);

        break;

    case 'win32':
    case 'win64':
        command = path.join(DEBUG_DIR, metadata.name, arch, `${metadata.name}.exe`);

        break;

    default:
        command =  '';

        break;
    }

    return command;
}

function getReleaseFilename(platform, ext, portable = false) {
    return `${metadata.name}_${metadata.version}_${platform}${portable ? "-portable" : ""}.${ext}`;
}

function clean_dist() {
    return del([`${DIST_DIR}**`], { force: true });
}

function clean_apps() {
    return del([`${APPS_DIR}**`], { force: true });
}

function clean_debug() {
    return del([`${DEBUG_DIR}**`], { force: true });
}

function clean_release() {
    return del([`${RELEASE_DIR}**`], { force: true });
}

function clean_cache() {
    return del(['./cache/**'], { force: true });
}

// Real work for dist task. Done in another task to call it via
// run-sequence.

function processPackage(done, gitRevision, isReleaseBuild) {
    const metadataKeys = [ 'name', 'productName', 'description', 'author', 'license', 'version' ];

    const pkg = require('./package.json');

    // remove gulp-appdmg from the package.json we're going to write
    delete pkg.optionalDependencies['gulp-appdmg'];

    pkg.gitRevision = gitRevision;
    if (!isReleaseBuild) {
        pkg.productName = `${pkg.productName} (Debug Build)`;
        pkg.description = `${pkg.description} (Debug Build)`;
        pkg.version = `${pkg.version}-debug-${gitRevision}`;

        metadata.packageId = `${pkg.name}-debug`;
    } else {
        metadata.packageId = pkg.name;
    }

    function version_prompt() {
        return gulp.src('.')
            .pipe(prompt.prompt([{
                type: 'input',
                name: 'version',
                message: `Package version (default: ${pkg.version}):`,
            }, {
                type: 'input',
                name: 'storeVersion',
                message: 'Google Play store version (<x.y.z>, default: package version):',
            }], function(res) {
                if (res.version) {
                    pkg.version = res.version;
                }
                if (res.storeVersion) {
                    metadata.storeVersion = res.storeVersion;
                }
            }));
    }

    function write_package_file() {
        Object.keys(pkg)
            .filter(key => metadataKeys.includes(key))
            .forEach((key) => {
                metadata[key] = pkg[key];
            });

        const packageJson = new stream.Readable;
        packageJson.push(JSON.stringify(pkg, undefined, 2));
        packageJson.push(null);

        return packageJson
            .pipe(source('package.json'))
            .pipe(gulp.dest(DIST_DIR));
    }

    const platforms = getPlatforms();
    if (platforms.indexOf('android') !== -1 && isReleaseBuild) {
        gulp.series(version_prompt, write_package_file)(done);
    } else {
        gulp.series(write_package_file)(done);
    }
}

function dist_src() {
    const distSources = [
        './src/**/*',
        '!./src/css/dropdown-lists/LICENSE',
        '!./src/support/**',
        '!./src/**/*.less',
    ];

    return gulp.src(distSources, { base: 'src' })
        .pipe(gulp.src('yarn.lock'))
        .pipe(gulp.dest(DIST_DIR));
}

function dist_less() {
    return gulp.src('./src/**/*.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(`${DIST_DIR}`));
}

function dist_changelog() {
    return gulp.src('changelog.html')
        .pipe(gulp.dest(`${DIST_DIR}tabs/`));
}

// This function relies on files from the dist_src function
function dist_yarn() {
    return gulp.src([`${DIST_DIR}package.json`, `${DIST_DIR}yarn.lock`])
        .pipe(gulp.dest(DIST_DIR))
        .pipe(yarn({
            production: true,
        }));
}

function dist_locale() {
    return gulp.src('./locales/**/*', { base: 'locales'})
        .pipe(gulp.dest(`${DIST_DIR}locales`));
}

function dist_libraries() {
    return gulp.src('./libraries/**/*', { base: '.'})
        .pipe(gulp.dest(`${DIST_DIR}js`));
}

function dist_resources() {
    return gulp.src(['./resources/**/*', '!./resources/osd/**/*.png'], { base: '.'})
        .pipe(gulp.dest(DIST_DIR));
}

function dist_rollup() {
    const commonjs = require('@rollup/plugin-commonjs');
    const resolve = require('@rollup/plugin-node-resolve').default;
    const alias = require('@rollup/plugin-alias');
    const vue = require('rollup-plugin-vue');
    const rollupReplace = require('@rollup/plugin-replace');

    return rollup
        .rollup({
            input: {
                // For any new file migrated to modules add the output path
                // in dist on the left, on the right it's input file path.
                // If all the things used by other files are importing
                // it with `import/export` file doesn't have to be here.
                // I will be picked up by rollup and bundled accordingly.
                'js/main_cordova': 'src/js/main_cordova.js',
                'js/utils/common': 'src/js/utils/common.js',
                'js/main': 'src/js/main.js',
            },
            plugins: [
                alias({
                    entries: {
                        vue: require.resolve('vue/dist/vue.esm.js'),
                    },
                }),
                rollupReplace({
                    'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
                }),
                resolve(),
                commonjs(),
                vue(),
            ],
        })
        .then(bundle =>
            bundle.write({
                format: 'esm',
                // rollup is smart about how `name` is treated.
                // so `input` you create file like `components/init`
                // `[name]` will be replaced with it creating directories
                // accordingly inside of `dist`
                entryFileNames: '[name].js',
                dir: DIST_DIR,
            }),
        );
}

// Create runable app directories in ./apps
function apps(done) {
    const platforms = getPlatforms();
    removeItem(platforms, 'android');

    buildNWAppsWrapper(platforms, 'normal', APPS_DIR, done);
}

function listPostBuildTasks(folder) {

    const platforms = getPlatforms();

    const postBuildTasks = [];

    if (platforms.indexOf('linux32') !== -1) {
        postBuildTasks.push(function post_build_linux32(done) {
            return post_build('linux32', folder, done);
        });
    }

    if (platforms.indexOf('linux64') !== -1) {
        postBuildTasks.push(function post_build_linux64(done) {
            return post_build('linux64', folder, done);
        });
    }

    if (platforms.indexOf('armv8') !== -1) {
        postBuildTasks.push(function post_build_armv8(done) {
            return post_build('armv8', folder, done);
        });
    }

    // We need to return at least one task, if not gulp will throw an error
    if (postBuildTasks.length === 0) {
        postBuildTasks.push(function post_build_none(done) {
            done();
        });
    }
    return postBuildTasks;
}

function post_build(arch, folder, done) {

    if ((arch === 'linux32') || (arch === 'linux64')) {
        // Copy Ubuntu launcher scripts to destination dir
        const launcherDir = path.join(folder, metadata.name, arch);
        console.log(`Copy Ubuntu launcher scripts to ${launcherDir}`);
        return gulp.src('assets/linux/**')
                   .pipe(gulp.dest(launcherDir));
    }

    if (arch === 'armv8') {
        console.log('Moving armv8 build from "linux32" to "armv8" directory...');
        fse.moveSync(path.join(folder, metadata.name, 'linux32'), path.join(folder, metadata.name, 'armv8'));
    }

    return done();
}

// Create debug app directories in ./debug
function debug(done) {
    const platforms = getPlatforms();
    removeItem(platforms, 'android');

    buildNWAppsWrapper(platforms, 'sdk', DEBUG_DIR, done);
}

function injectARMCache(flavor, done) {
    const flavorPostfix = `-${flavor}`;
    const flavorDownloadPostfix = flavor !== 'normal' ? `-${flavor}` : '';
    clean_cache().then(function() {
        if (!fs.existsSync('./cache')) {
            fs.mkdirSync('./cache');
        }
        fs.closeSync(fs.openSync('./cache/_ARMv8_IS_CACHED', 'w'));
        const versionFolder = `./cache/${nwBuilderOptions.version}${flavorPostfix}`;
        if (!fs.existsSync(versionFolder)) {
            fs.mkdirSync(versionFolder);
        }
        const linux32Folder = `${versionFolder}/linux32`;
        if (!fs.existsSync(linux32Folder)) {
            fs.mkdirSync(linux32Folder);
        }
        const downloadedArchivePath = `${versionFolder}/nwjs${flavorPostfix}-v${nwArmVersion}-linux-arm.tar.gz`;
        const downloadUrl = `https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases/download/${nwArmVersion}/${nwArmVersion}.tar.gz`;
        if (fs.existsSync(downloadedArchivePath)) {
            console.log('Prebuilt ARMv8 binaries found in /tmp');
            downloadDone(flavorDownloadPostfix, downloadedArchivePath, versionFolder);
        } else {
            console.log(`Downloading prebuilt ARMv8 binaries from "${downloadUrl}"...`);
            process.stdout.write('> Starting download...\r');
            const armBuildBinary = fs.createWriteStream(downloadedArchivePath);
            https.get(downloadUrl, function(res) {
                const totalBytes = res.headers['content-length'];
                let downloadedBytes = 0;
                res.pipe(armBuildBinary);
                res.on('data', function (chunk) {
                    downloadedBytes += chunk.length;
                    process.stdout.write(`> ${parseInt((downloadedBytes * 100) / totalBytes)}% done             \r`);
                });
                armBuildBinary.on('finish', function() {
                    process.stdout.write('> 100% done             \n');
                    armBuildBinary.close(function() {
                        downloadDone(flavorDownloadPostfix, downloadedArchivePath, versionFolder);
                    });
                });
            });
        }
    });

    function downloadDone(flavorDownload, downloadedArchivePath, versionFolder) {
        console.log('Injecting prebuilt ARMv8 binaries into Linux32 cache...');
        targz.decompress({
            src: downloadedArchivePath,
            dest: versionFolder,
        }, function(err) {
            if (err) {
                console.log(err);
                clean_debug();
                process.exit(1);
            } else {
                fs.rename(
                    `${versionFolder}/nwjs${flavorDownload}-v${nwArmVersion}-linux-arm`,
                    `${versionFolder}/linux32`,
                    (renameErr) => {
                        if (renameErr) {
                            console.log(renameErr);
                            clean_debug();
                            process.exit(1);
                        }
                        done();
                    },
                );
            }
        });
    }
}

function buildNWAppsWrapper(platforms, flavor, dir, done) {
    function buildNWAppsCallback() {
        buildNWApps(platforms, flavor, dir, done);
    }

    if (platforms.indexOf('armv8') !== -1) {
        if (platforms.indexOf('linux32') !== -1) {
            console.log('Cannot build ARMv8 and Linux32 versions at the same time!');
            clean_debug();
            process.exit(1);
        }
        removeItem(platforms, 'armv8');
        platforms.push('linux32');

        if (!fs.existsSync('./cache/_ARMv8_IS_CACHED', 'w')) {
            console.log('Purging cache because it needs to be overwritten...');
            clean_cache().then(() => {
                injectARMCache(flavor, buildNWAppsCallback);
            });
        } else {
            buildNWAppsCallback();
        }
    } else {
        if (platforms.indexOf('linux32') !== -1 && fs.existsSync('./cache/_ARMv8_IS_CACHED')) {
            console.log('Purging cache because it was previously overwritten...');
            clean_cache().then(buildNWAppsCallback);
        } else {
            buildNWAppsCallback();
        }
    }
}

function buildNWApps(platforms, flavor, dir, done) {
    if (platforms.length > 0) {
        const builder = new NwBuilder(Object.assign({
            buildDir: dir,
            platforms,
            flavor,
        }, nwBuilderOptions));
        builder.on('log', console.log);
        builder.build(function (err) {
            if (err) {
                console.log(`Error building NW apps: ${err}`);
                clean_debug();
                process.exit(1);
            }
            done();
        });
    } else {
        console.log('No platform suitable for NW Build');
        done();
    }
}

function getGitRevision(done, callback, isReleaseBuild) {
    let gitRevision = 'norevision';
    git.diff([ '--shortstat' ], function (err1, diff) {
        if (!err1 && !diff) {
            git.log([ '-1', '--pretty=format:%h' ], function (err2, rev) {
                if (!err2) {
                    gitRevision = rev.latest.hash;
                }

                callback(done, gitRevision, isReleaseBuild);
            });
        } else {
            callback(done, gitRevision, isReleaseBuild);
        }
    });
}

function start_debug(done) {
    const platforms = getPlatforms();

    if (platforms.length === 1) {
        if (platforms[0] === 'android') {
            cordova_debug();
        } else {
            const run = getRunDebugAppCommand(platforms[0]);
            console.log(`Starting debug app (${run})...`);
            child_process.exec(run);
        }
    } else {
        console.log('More than one platform specified, not starting debug app');
    }
    done();
}

// Create installer package for windows platforms
function release_win(arch, appDirectory, done) {

    // Parameters passed to the installer script
    const parameters = [];

    // Extra parameters to replace inside the iss file
    parameters.push(`/Dversion=${metadata.version}`);
    parameters.push(`/DarchName=${arch}`);
    parameters.push(`/DarchAllowed=${(arch === 'win32') ? 'x86 x64' : 'x64'}`);
    parameters.push(`/DarchInstallIn64bit=${(arch === 'win32') ? '' : 'x64'}`);
    parameters.push(`/DsourceFolder=${appDirectory}`);
    parameters.push(`/DtargetFolder=${RELEASE_DIR}`);

    // Show only errors in console
    parameters.push(`/Q`);

    // Script file to execute
    parameters.push("assets/windows/installer.iss");

    innoSetup(parameters, {},
    function(error) {
        if (error != null) {
            console.error(`Installer for platform ${arch} finished with error ${error}`);
        } else {
            console.log(`Installer for platform ${arch} finished`);
        }
        done();
    });
}

// Create distribution package (zip) for windows and linux platforms
function release_zip(arch, appDirectory) {
    const src = path.join(appDirectory, metadata.name, arch, '**');
    const output = getReleaseFilename(arch, 'zip', true);
    const base = path.join(appDirectory, metadata.name, arch);

    return compressFiles(src, base, output, 'Betaflight Configurator');
}

// Compress files from srcPath, using basePath, to outputFile in the RELEASE_DIR
function compressFiles(srcPath, basePath, outputFile, zipFolder) {
    return gulp.src(srcPath, { base: basePath })
               .pipe(rename(function(actualPath) {
                   actualPath.dirname = path.join(zipFolder, actualPath.dirname);
               }))
               .pipe(zip(outputFile))
               .pipe(gulp.dest(RELEASE_DIR));
}

function release_deb(arch, appDirectory, done) {

    // Check if dpkg-deb exists
    if (!commandExistsSync('dpkg-deb')) {
        console.warn(`dpkg-deb command not found, not generating deb package for ${arch}`);
        done();
        return null;
    }

    return gulp.src([path.join(appDirectory, metadata.name, arch, '*')])
        .pipe(deb({
            package: metadata.name,
            version: metadata.version,
            section: 'base',
            priority: 'optional',
            architecture: getLinuxPackageArch('deb', arch),
            maintainer: metadata.author,
            description: metadata.description,
            preinst: [`rm -rf ${LINUX_INSTALL_DIR}/${metadata.name}`],
            postinst: [
                `chown root:root ${LINUX_INSTALL_DIR}`,
                `chown -R root:root ${LINUX_INSTALL_DIR}/${metadata.name}`,
                `xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${metadata.name}/${metadata.name}.desktop`,
                `chmod +xr ${LINUX_INSTALL_DIR}/${metadata.name}/chrome_crashpad_handler`,
                `chmod +xr ${LINUX_INSTALL_DIR}/${metadata.name}/${metadata.name}`,
                `chmod -R +Xr ${LINUX_INSTALL_DIR}/${metadata.name}/`,
            ],
            prerm: [`xdg-desktop-menu uninstall ${metadata.name}.desktop`],
            depends: ['libgconf-2-4', 'libatomic1'],
            changelog: [],
            _target: `${LINUX_INSTALL_DIR}/${metadata.name}`,
            _out: RELEASE_DIR,
            _copyright: 'assets/linux/copyright',
            _clean: true,
    }));
}

function release_rpm(arch, appDirectory, done) {

    // Check if rpmbuild exists
    if (!commandExistsSync('rpmbuild')) {
        console.warn(`rpmbuild command not found, not generating rpm package for ${arch}`);
        done();
        return;
    }

    // The buildRpm does not generate the folder correctly, manually
    createDirIfNotExists(RELEASE_DIR);

    const options = {
            name: metadata.name,
            version: metadata.version.replace(NAME_REGEX, '_'), // RPM does not like release candidate versions
            buildArch: getLinuxPackageArch('rpm', arch),
            vendor: metadata.author,
            summary: metadata.description,
            license: 'GNU General Public License v3.0',
            requires: ['GConf2', 'libatomic'],
            prefix: '/opt',
            files: [{
                cwd: path.join(appDirectory, metadata.name, arch),
                src: '*',
                dest: `${LINUX_INSTALL_DIR}/${metadata.name}`,
            }],
            postInstallScript: [`xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${metadata.name}/${metadata.name}.desktop`],
            preUninstallScript: [`xdg-desktop-menu uninstall ${metadata.name}.desktop`],
            tempDir: path.join(RELEASE_DIR, `tmp-rpm-build-${arch}`),
            keepTemp: false,
            verbose: false,
            rpmDest: RELEASE_DIR,
            execOpts: { maxBuffer: 1024 * 1024 * 16 },
    };

    buildRpm(options, function(err) {
        if (err) {
          console.error(`Error generating rpm package: ${err}`);
        }
        done();
    });
}

function getLinuxPackageArch(type, arch) {
    let packArch;

    switch (arch) {
    case 'linux32':
        packArch = 'i386';
        break;
    case 'linux64':
        if (type === 'rpm') {
            packArch = 'x86_64';
        } else {
            packArch = 'amd64';
        }
        break;
    default:
        console.error(`Package error, arch: ${arch}`);
        process.exit(1);
        break;
    }

    return packArch;
}
// Create distribution package for macOS platform
function release_osx64(appDirectory) {
    const appdmg = require('./gulp-appdmg');

    // The appdmg does not generate the folder correctly, manually
    createDirIfNotExists(RELEASE_DIR);

    // The src pipe is not used
    return gulp.src(['.'])
        .pipe(appdmg({
            target: path.join(RELEASE_DIR, getReleaseFilename('macOS', 'dmg')),
            basepath: path.join(appDirectory, metadata.name, 'osx64'),
            specification: {
                title: 'Betaflight Configurator',
                contents: [
                    { 'x': 448, 'y': 342, 'type': 'link', 'path': '/Applications' },
                    { 'x': 192, 'y': 344, 'type': 'file', 'path': `${metadata.name}.app`, 'name': 'Betaflight Configurator.app' },
                ],
                background: path.join(__dirname, 'assets/osx/dmg-background.png'),
                format: 'UDZO',
                window: {
                    size: {
                        width: 638,
                        height: 479,
                    },
                },
            },
        }),
    );
}

// Create the dir directory, with write permissions
function createDirIfNotExists(dir) {
    fs.mkdir(dir, '0775', function(err) {
        if (err && err.code !== 'EEXIST') {
            throw err;
        }
    });
}

// Create a list of the gulp tasks to execute for release
function listReleaseTasks(isReleaseBuild, appDirectory) {

    const platforms = getPlatforms();

    const releaseTasks = [];

    if (platforms.indexOf('linux64') !== -1) {
        releaseTasks.push(function release_linux64_zip() {
            return release_zip('linux64', appDirectory);
        });
        releaseTasks.push(function release_linux64_deb(done) {
            return release_deb('linux64', appDirectory, done);
        });
        releaseTasks.push(function release_linux64_rpm(done) {
            return release_rpm('linux64', appDirectory, done);
        });
    }

    if (platforms.indexOf('linux32') !== -1) {
        releaseTasks.push(function release_linux32_zip() {
            return release_zip('linux32', appDirectory);
        });
        releaseTasks.push(function release_linux32_deb(done) {
            return release_deb('linux32', appDirectory, done);
        });
        releaseTasks.push(function release_linux32_rpm(done) {
            return release_rpm('linux32', appDirectory, done);
        });
    }

    if (platforms.indexOf('armv8') !== -1) {
        releaseTasks.push(function release_armv8_zip() {
            return release_zip('armv8', appDirectory);
        });
    }

    if (platforms.indexOf('osx64') !== -1) {
        releaseTasks.push(function () {
            return release_osx64(appDirectory);
        });
    }

    if (platforms.indexOf('win32') !== -1) {
        releaseTasks.push(function release_win32_zip() {
            return release_zip('win32', appDirectory);
        });
        releaseTasks.push(function release_win32(done) {
            return release_win('win32', appDirectory, done);
        });
    }

    if (platforms.indexOf('win64') !== -1) {
        releaseTasks.push(function release_win64_zip() {
            return release_zip('win64', appDirectory);
        });
        releaseTasks.push(function release_win64(done) {
            return release_win('win64', appDirectory, done);
        });
    }

    if (platforms.indexOf('android') !== -1) {
        releaseTasks.push(function release_android() {
            if (isReleaseBuild) {
                return cordova_release();
            } else {
                return cordova_debug_release();
            }
        });
    }

    return releaseTasks;
}

// Cordova
function cordova_dist() {
    const distTasks = [];
    const platforms = getPlatforms();
    if (platforms.indexOf('android') !== -1) {
        distTasks.push(clean_cordova);
        distTasks.push(cordova_copy_www);
        distTasks.push(cordova_resources);
        distTasks.push(cordova_include_www);
        distTasks.push(cordova_copy_src);
        distTasks.push(cordova_rename_src_config);
        distTasks.push(cordova_rename_src_package);
        distTasks.push(cordova_packagejson);
        distTasks.push(cordova_manifestjson);
        distTasks.push(cordova_configxml);
        distTasks.push(cordova_rename_build_json);
        distTasks.push(cordova_browserify);
        distTasks.push(cordova_depedencies);
        if (cordovaDependencies) {
            distTasks.push(cordova_platforms);
        }
    } else {
        distTasks.push(function cordova_dist_none(done) {
            done();
        });
    }
    return distTasks;
}

function cordova_apps(isReleaseBuild) {
    const appsTasks = [];
    const platforms = getPlatforms();
    if (platforms.indexOf('android') !== -1) {
        if (isReleaseBuild) {
            appsTasks.push(cordova_build);
        } else {
            appsTasks.push(cordova_debug_build);
        }
    } else {
        appsTasks.push(function cordova_dist_none(done) {
            done();
        });
    }
    return appsTasks;
}

function clean_cordova() {
    const patterns = [];
    if (cordovaDependencies) {
        patterns.push(`${CORDOVA_DIST_DIR}**`);
    } else {
        patterns.push(`${CORDOVA_DIST_DIR}www/**`);
        patterns.push(`${CORDOVA_DIST_DIR}resources/**`);
    }
    return del(patterns, { force: true });
}

function cordova_copy_www() {
    return gulp.src(`${DIST_DIR}**`, { base: DIST_DIR })
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}www/`));
}

function cordova_resources() {
    return gulp.src('assets/android/**')
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}resources/android/`));
}

function cordova_include_www() {
    return gulp.src(`${CORDOVA_DIST_DIR}www/main.html`)
        .pipe(replace('<!-- CORDOVA_INCLUDE js/cordova_chromeapi.js -->', '<script type="text/javascript" src="./js/cordova_chromeapi.js"></script>'))
        .pipe(replace('<!-- CORDOVA_INCLUDE js/cordova_startup.js -->', '<script type="text/javascript" src="./js/cordova_startup.js"></script>'))
        .pipe(replace('<!-- CORDOVA_INCLUDE cordova.js -->', '<script type="text/javascript" src="cordova.js"></script>'))
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}www`));
}

function cordova_copy_src() {
    return gulp.src([`${CORDOVA_DIR}**`, `!${CORDOVA_DIR}config_template.xml`, `!${CORDOVA_DIR}package_template.json`, `!${CORDOVA_DIR}build_template.json`])
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}`));
}

function cordova_rename_src_config() {
    return gulp.src(`${CORDOVA_DIR}config_template.xml`)
        .pipe(rename('config.xml'))
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}`));
}

function cordova_rename_src_package() {
    return gulp.src(`${CORDOVA_DIR}package_template.json`)
        .pipe(rename('package.json'))
        .pipe(gulp.dest(`${CORDOVA_DIST_DIR}`));
}

function cordova_packagejson() {
    return gulp.src(`${CORDOVA_DIST_DIR}package.json`)
        .pipe(jeditor({
            'name': metadata.name,
            'description': metadata.description,
            'version': metadata.version,
            'author': metadata.author,
            'license': metadata.license,
        }))
        .pipe(gulp.dest(CORDOVA_DIST_DIR))
        .pipe(rename('manifest.json'))
        .pipe(gulp.dest(CORDOVA_DIST_DIR));
}

// Required to make getManifest() work in cordova

function cordova_manifestjson() {
    return gulp.src(`${DIST_DIR}package.json`)
        .pipe(rename('manifest.json'))
        .pipe(gulp.dest(CORDOVA_DIST_DIR));
}

function cordova_configxml() {
    const androidName = metadata.packageId.replace(NAME_REGEX, '_');

    return gulp.src([`${CORDOVA_DIST_DIR}config.xml`])
        .pipe(xmlTransformer([
            { path: '//xmlns:name', text: metadata.productName },
            { path: '//xmlns:description', text: metadata.description },
            { path: '//xmlns:author', text: metadata.author },
        ], 'http://www.w3.org/ns/widgets'))
        .pipe(xmlTransformer([
            { path: '.', attr: { 'id': `com.betaflight.${androidName}` } },
            { path: '.', attr: { 'version': metadata.storeVersion ? metadata.storeVersion : metadata.version } },
        ]))
        .pipe(gulp.dest(CORDOVA_DIST_DIR));
}

function cordova_rename_build_json() {
    return gulp.src(`${CORDOVA_DIR}build_template.json`)
        .pipe(rename('build.json'))
        .pipe(gulp.dest(CORDOVA_DIST_DIR));
}

function cordova_browserify(done) {
    const readFile = function(file) {
        return new Promise(function(resolve) {
            if (!file.includes("node_modules")) {
                fs.readFile(file, 'utf8', async function (err,data) {
                    if (data.match('require\\(.*\\)')) {
                        await cordova_execbrowserify(file);
                    }
                    resolve();
                });
            } else {
                resolve();
            }
        });
    };
    glob(`${CORDOVA_DIST_DIR}www/**/*.js`, {}, function (err, files) {
        const readLoop = function() {
            if (files.length === 0) {
                done();
            } else {
                const file = files.pop();
                readFile(file).then(function() {
                    readLoop();
                });
            }
        };
        readLoop();
    });
}

function cordova_execbrowserify(file) {
    const filename = file.split('/').pop();
    const destpath = file.replace(filename, '');
    console.log(`Include required modules in ${file}`);
    return browserify(file, { ignoreMissing: true })
        .bundle()
        .pipe(source(filename))
        .pipe(gulp.dest(destpath));
}

function cordova_depedencies() {
    process.chdir(CORDOVA_DIST_DIR);
    return gulp.src(['./package.json', './yarn.lock'])
        .pipe(gulp.dest('./'))
        .pipe(yarn({
            production: true,
        }));
}

function cordova_platforms() {
    return cordova.platform('add', ['android']);
}

function cordova_debug() {
    cordova.run();
}

function cordova_debug_build(done) {
    cordova.build({
        'platforms': ['android'],
        'options': {
            release: false,
            buildConfig: 'build.json',
        },
    }).then(function() {
        process.chdir('../');

        console.log(`APK has been generated at ${CORDOVA_DIST_DIR}platforms/android/app/build/outputs/apk/release/app-release.apk`);

        done();
    });
}

function cordova_build(done) {
    let storePassword = '';
    return gulp.series(function password_prompt() {
        return gulp.src('.')
            .pipe(prompt.prompt({
                type: 'password',
                name: 'storePassword',
                message: 'Please enter the keystore password:',
            }, function(res) {
                storePassword = res.storePassword;
            }));
    }, function set_password() {
        return gulp.src(`build.json`)
            .pipe(jeditor({
                'android': {
                    'release' : {
                        'storePassword': storePassword,
                    },
                },
            }))
            .pipe(gulp.dest('./'));
    }, function build(done2) {
        return cordova.build({
            'platforms': ['android'],
            'options': {
                release: true,
                buildConfig: 'build.json',
            },
        }).then(function() {
            // Delete the file containing the store password
            del(['build.json'], { force: true });
            process.chdir('../');

            console.log('AAB has been generated at dist_cordova/platforms/android/app/build/outputs/bundle/release/app.aab');
            done2();
        });
    })(done);
}

async function cordova_debug_release() {
    const filename = getReleaseFilename('android', 'apk');

    console.log(`Release APK : release/${filename}`);

    return gulp.src(`${CORDOVA_DIST_DIR}platforms/android/app/build/outputs/apk/debug/app-debug.apk`)
        .pipe(rename(filename))
        .pipe(gulp.dest(RELEASE_DIR));
}

async function cordova_release() {
    const filename = getReleaseFilename('android', 'aab');

    console.log(`Release AAB : release/${filename}`);

    return gulp.src(`${CORDOVA_DIST_DIR}platforms/android/app/build/outputs/bundle/release/app.aab`)
        .pipe(rename(filename))
        .pipe(gulp.dest(RELEASE_DIR));
}