-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbuild.ts
1272 lines (1053 loc) · 38.5 KB
/
build.ts
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
/// <reference path="./ambient.d.ts" />
import * as Chalk from 'chalk';
import { exec } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as readline from 'readline';
import { Key } from 'readline';
import { asLines, isFunction, isNumber, isObject, isString, processMillis, toBoolean, toNumber } from '@tubular/util';
import * as path from 'path';
import { convertPinToGpio } from './server/src/rpi-pin-conversions';
import { ErrorMode, getSudoUser, getUserHome, monitorProcess, monitorProcessLines, sleep, spawn } from './server/src/process-util';
import { promisify } from 'util';
const enoughRam = os.totalmem() / 0x40000000 > 1.5;
// Deal with weird issue where 'copyfiles' gets imported in an inconsistent manner.
let copyfiles: any = require('copyfiles');
if (copyfiles.default)
copyfiles = copyfiles.default;
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
const CHECK_MARK = '\u2714';
const FAIL_MARK = '\u2718';
const SPIN_CHARS = '|/-\\';
const SPIN_DELAY = 100;
const isWindows = (process.platform === 'win32');
let spinStep = 0;
let lastSpin = 0;
let doUpdateUpgrade = true;
let doNpmI = true;
let npmInitDone = false;
let doAcu = false;
let clearAcu = false;
let doAdmin: boolean;
let doDht = false;
let clearDht = false;
let doKiosk = true;
let clearKiosk = false;
let doStdDeploy = false;
let doDedicated = false;
let doLaunch = false;
let doReboot = false;
let noStop = false;
let prod = false;
let viaBash = false;
let interactive = false;
let treatAsRaspberryPi = process.argv.includes('--tarp');
let isRaspberryPi = false;
let spin = (): void => {
const now = processMillis();
if (lastSpin < now - SPIN_DELAY) {
lastSpin = now;
write(backspace + SPIN_CHARS.charAt(spinStep));
spinStep = (spinStep + 1) % 4;
}
};
interface ExtendedChalk extends Chalk.Chalk {
mediumGray: (s: string) => string;
paleBlue: (s: string) => string;
paleYellow: (s: string) => string;
}
const chalk = new Chalk.Instance() as ExtendedChalk;
chalk.mediumGray = chalk.hex('#808080');
chalk.paleBlue = chalk.hex('#66CCFF');
chalk.paleYellow = chalk.hex('#FFFFAA');
let backspace = '\x08';
let sol = '\x1B[1G';
let trailingSpace = ' '; // Two spaces
let totalSteps = 2;
let currentStep = 0;
const settings: Record<string, string> = {
AWC_ALLOW_ADMIN: 'false',
AWC_ALLOW_CORS: 'true',
AWC_KIOSK_MODE: 'true',
AWC_LOG_CACHE_ACTIVITY: 'false',
AWC_NTP_SERVERS: '',
AWC_PORT: '8080',
AWC_PREFERRED_WS: 'wunderground',
AWC_WIRED_TH_GPIO: '17',
AWC_WIRELESS_TH_GPIO: '27'
};
const userHome = getUserHome();
const sudoUser = getSudoUser();
const user = process.env.SUDO_USER || process.env.USER || 'pi';
let uid: number;
const cpuPath = '/proc/cpuinfo';
const cpuPath2 = '/sys/firmware/devicetree/base/model';
const settingsPath = '/etc/default/weatherService';
const rpiSetupStuff = path.join(__dirname, 'raspberry_pi_setup');
const serviceSrc = rpiSetupStuff + '/weatherService';
const serviceDst = '/etc/init.d/.';
const serviceDstFull = '/etc/init.d/weatherService';
const fontSrc = rpiSetupStuff + '/fonts/';
const fontDst = '/usr/local/share/fonts/';
let chromium = 'chromium';
let autostartDst = '.config/lxsession/LXDE';
const lxdePiCheck = '.config/lxpanel/LXDE-pi';
let nodePath = process.env.PATH;
if (process.platform === 'linux') {
try {
if (fs.existsSync(cpuPath)) {
const lines = asLines(fs.readFileSync(cpuPath).toString());
if (fs.existsSync(cpuPath2))
lines.push(...asLines(fs.readFileSync(cpuPath2).toString()));
for (const line of lines) {
if (/\b(Raspberry Pi|BCM\d+)\b/i.test(line)) {
isRaspberryPi = treatAsRaspberryPi = true;
autostartDst += '-pi';
chromium += '-browser';
break;
}
}
}
}
catch (err) {
console.error(chalk.redBright('Raspberry Pi check failed'));
}
}
if ((isRaspberryPi || treatAsRaspberryPi) && !process.env.DISPLAY) {
process.env.DISPLAY = ':0.0';
}
let launchChromium = chromium + ' http://localhost:8080/';
const launchChromiumPattern = new RegExp(`^@${chromium}\\b.*\\bhttp:\\/\\/localhost:\\d+\\/$`);
// Remove extraneous command line args, if present.
if (/\b(ts-)?node\b/.test(process.argv[0] ?? ''))
process.argv.splice(0, 1);
if (/\bbuild(\.[jt]s)?\b/.test(process.argv[0] ?? ''))
process.argv.splice(0, 1);
if (process.argv.length === 0 && treatAsRaspberryPi && !viaBash) {
console.warn(chalk.yellow('Warning: no build options specified.'));
console.warn(chalk.yellow('This could be OK, or this could mean you forgot the leading ') +
chalk.white('--') + chalk.yellow(' before your options.'));
}
const onlyOnRaspberryPi: string[] = [];
const onlyDedicated: string[] = [];
let helpMsg: string;
let getPathArg = false;
process.argv.forEach(arg => {
if (getPathArg) {
process.env.NODE_PATH = arg.trim();
process.env.PATH = nodePath = arg.trim() + (nodePath ? ':' + nodePath : nodePath);
getPathArg = false;
return;
}
switch (arg) {
case '--':
break;
case '--acu':
doAcu = true;
break;
case '--acu-':
doAcu = false;
clearAcu = true;
break;
case '--admin':
doAdmin = true;
break;
case '--admin-':
doAdmin = false;
break;
case '--bash':
viaBash = true;
delete process.env.SHLVL;
break;
case '--ddev':
doDedicated = doStdDeploy = true;
onlyOnRaspberryPi.push(arg);
break;
case '--dht':
doDht = true;
onlyOnRaspberryPi.push(arg);
break;
case '--dht-':
doDht = false;
clearDht = true;
break;
case '-i':
interactive = doStdDeploy = doDedicated = true;
onlyOnRaspberryPi.push(arg);
delete process.env.SHLVL;
break;
case '--kiosk':
doKiosk = true;
clearKiosk = false;
break;
case '--kiosk-':
doKiosk = false;
clearKiosk = true;
break;
case '--launch':
doLaunch = true;
onlyOnRaspberryPi.push(arg);
onlyDedicated.push(arg);
break;
case '--nostop':
noStop = true;
break;
case '-p':
prod = true;
break;
case '--path':
getPathArg = true;
break;
case '--pt':
spin = undefined;
chalk.level = 0;
backspace = '';
sol = '';
trailingSpace = ' ';
break;
case '--reboot':
doReboot = true;
doLaunch = false;
onlyOnRaspberryPi.push(arg);
onlyDedicated.push(arg);
break;
case '--sd':
doStdDeploy = true;
onlyOnRaspberryPi.push(arg);
break;
case '--skip-upgrade':
doUpdateUpgrade = false;
onlyOnRaspberryPi.push(arg);
break;
case '--skip-npm-i':
doNpmI = false;
break;
case '--tarp':
break; // ignore - already handled
default:
{
helpMsg =
'Usage: sudo ./build.sh [--acu] [--admin] [--ddev] [--dht] [--gps] [--help] [-i]\n' +
' [--launch] [--kiosk] [-p] [--pt] [--reboot] [--sd]\n' +
' [--skip-upgrade] [--tarp]\n\n' +
'The options --acu, --admin, --dht, and --kiosk can be followed by an extra\n' +
'dash (e.g. --acu-) to clear a previously enabled option.';
if (!viaBash)
helpMsg = helpMsg.replace('sudo ./build.sh', 'npm run build').replace(/\n {2}/g, '\n');
if (arg !== '--help' && arg !== '-h')
console.error('Unrecognized option "' + chalk.redBright(arg) + '"');
console.log(helpMsg);
process.exit(1);
}
}
});
if (noStop)
doReboot = doLaunch = false;
if (!treatAsRaspberryPi && onlyOnRaspberryPi.length > 0) {
onlyOnRaspberryPi.forEach(opt =>
console.error(chalk.redBright(opt) + ' option is only valid on Raspberry Pi'));
process.exit(1);
}
if (!doDedicated && onlyDedicated.length > 0) {
onlyDedicated.forEach(opt =>
console.error(chalk.redBright(opt) + ' option is only valid when used with the --ddev or -i options'));
process.exit(1);
}
if (treatAsRaspberryPi) {
try {
if (fs.existsSync(settingsPath)) {
const lines = asLines(fs.readFileSync(settingsPath).toString());
const oldSettings: Record<string, string> = {};
lines.forEach(line => {
const $ = /^\s*(\w+)\s*=\s*(\S+)/.exec(line);
if ($)
oldSettings[$[1]] = settings[$[1]] = $[2];
});
if (doAdmin === undefined)
doAdmin = toBoolean(oldSettings.AWC_ALLOW_ADMIN);
else
settings.AWC_ALLOW_ADMIN = doAdmin?.toString();
// Convert deprecated environment variables
if (!oldSettings.AWC_WIRED_TH_GPIO && toBoolean(oldSettings.AWC_HAS_INDOOR_SENSOR))
oldSettings.AWC_WIRED_TH_GPIO = settings.AWC_WIRED_TH_GPIO =
settings.AWC_TH_SENSOR_GPIO || '4';
if (!clearDht && oldSettings.AWC_WIRED_TH_GPIO)
doDht = true;
if (!settings.AWC_WIRELESS_TH_GPIO && oldSettings.AWC_WIRELESS_TEMP)
oldSettings.AWC_WIRELESS_TH_GPIO = settings.AWC_WIRELESS_TH_GPIO = settings.AWC_WIRELESS_TEMP;
if (!clearAcu && oldSettings.AWC_WIRELESS_TH_GPIO)
doAcu = true;
if (!settings.AWC_NTP_SERVERS) {
if (oldSettings.AWC_NTP_SERVER === 'pool.ntp.org')
settings.AWC_NTP_SERVERS = '';
else if (oldSettings.AWC_NTP_SERVER)
settings.AWC_NTP_SERVERS = oldSettings.AWC_NTP_SERVER;
}
delete settings.AWC_HAS_INDOOR_SENSOR;
delete settings.AWC_TH_SENSOR_GPIO;
delete settings.AWC_WIRELESS_TEMP;
delete settings.AWC_NTP_SERVER;
if (clearKiosk)
doKiosk = false;
else
doKiosk = toBoolean(oldSettings.AWC_KIOSK_MODE, doKiosk);
settings.AWC_KIOSK_MODE = doKiosk.toString();
}
}
catch (err) {
console.warn(chalk.yellow('Existing settings check failed. Defaults will be used.'));
}
}
if (!isRaspberryPi && doAcu)
console.warn(chalk.yellow('Warning: this setup will only generate fake wireless sensor data'));
async function readUserInput(): Promise<string> {
return new Promise<string>(resolve => {
let buffer = '';
let length = 0;
const clearLine = (): void => write('\x08 \x08'.repeat(length));
const callback = (ch: string, key: Key): void => {
if (ch === '\x03') { // ctrl-C
write('^C\n');
process.exit(130);
}
else if (ch === '\x15') { // ctrl-U
clearLine();
length = 0;
}
else if (key.name === 'enter' || key.name === 'return') {
write('\n');
process.stdin.off('keypress', callback);
resolve(buffer.substr(0, length).trim());
}
else if (key.name === 'backspace' || key.name === 'left') {
if (length > 0) {
write('\x08 \x08');
--length;
}
}
else if (key.name === 'delete') {
if (length > 0) {
write('\x08 \x08');
buffer = buffer.substr(0, --length) + buffer.substr(length + 1);
}
}
else if (key.name === 'up') {
clearLine();
write('\n');
process.stdin.off('keypress', callback);
resolve('\x18');
}
else if (key.name === 'right') {
if (length < buffer.length) {
write(buffer.charAt(length++));
}
}
else if (ch != null && ch >= ' ' && !key.ctrl && !key.meta) {
write(ch);
buffer = buffer.substr(0, length) + ch + buffer.substr(length++);
}
};
process.stdin.on('keypress', callback);
});
}
function write(s: string): void {
process.stdout.write(s);
}
function stepDone(): void {
console.log(backspace + chalk.green(CHECK_MARK));
}
async function isInstalled(command: string): Promise<boolean> {
return !!(await monitorProcess(spawn('command', ['-v', command], { shell: true }), null, ErrorMode.ANY_ERROR))?.trim();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function install(cmdPkg: string, viaNpm = false, realOnly = false, quiet = false): Promise<boolean> {
let packageArgs = [cmdPkg];
let name = cmdPkg;
if (!quiet)
showStep();
if (realOnly && !isRaspberryPi) {
console.log(`${chalk.bold(cmdPkg)} won't be installed (not real Raspberry Pi)` +
trailingSpace + backspace + chalk.green(CHECK_MARK));
return false;
}
if (cmdPkg === 'pigpio') {
packageArgs = ['pigpio', 'python-pigpio', 'python3-pigpio'];
name = 'pigpiod';
}
if (await isInstalled(name)) {
if (quiet)
stepDone();
else
console.log(`${chalk.bold(cmdPkg)} already installed` + trailingSpace + backspace + chalk.green(CHECK_MARK));
return false;
}
else {
if (!quiet)
write(`Installing ${chalk.bold(cmdPkg)}` + trailingSpace);
if (viaNpm)
await monitorProcess(spawn('npm', ['install', '-g', ...packageArgs]), spin, ErrorMode.ANY_ERROR);
else
await monitorProcess(spawn('apt-get', ['install', '-y', ...packageArgs]), spin, ErrorMode.ANY_ERROR);
stepDone();
return true;
}
}
function getWebpackSummary(s: string): string {
const lines = asLines(s);
const summary: string[] = [];
for (let line of lines) {
if (/(^(hash|version|time|built at):)|by path assets\/ |runtime modules|javascript modules|compiled successfully in/i.test(line)) {
line = line.trim();
summary.push(line.substr(0, 72) + (line.length > 72 ? '...' : ''));
}
}
return ' ' + summary.join('\n ');
}
async function npmInit(): Promise<void> {
if (!npmInitDone) {
const file = path.join(__dirname, 'server', 'dist', 'package.json');
const packageJson = {
name: 'aw-clock-server',
version: '0.0.0',
description: 'AW-Clock Server',
main: 'app.js',
license: 'MIT',
dependencies: {}
};
fs.writeFileSync(file, JSON.stringify(packageJson, null, 2));
await monitorProcess(spawn('chown', [user, file]), spin, ErrorMode.ANY_ERROR);
npmInitDone = true;
}
}
enum RepoStatus { CLEAN, PACKAGE_LOCK_CHANGES_ONLY, DIRTY }
async function getRepoStatus(): Promise<RepoStatus> {
const lines = asLines((await monitorProcess(spawn('git', ['status', '--porcelain', '-b']))).trim());
let status = RepoStatus.CLEAN;
if (lines.length > 0)
lines.splice(0, 1);
for (const line of lines) {
if (/\bpackage-lock.json$/.test(line))
status = RepoStatus.PACKAGE_LOCK_CHANGES_ONLY;
else {
status = RepoStatus.DIRTY;
break;
}
}
return status;
}
function showStep(): void {
write(`Step ${++currentStep} of ${totalSteps}: `);
}
function chalkUp(s: string, currentStyle = (s: string): string => s): string {
const closed = /(.*?)(\[([a-z]+)])(.*?)(\[\/\3])(.*)/.exec(s);
const open = /(.*?)(\[([a-z]+)])(.*)/.exec(s);
if (!closed && !open)
return s;
let $: RegExpMatchArray;
if (closed && open)
$ = open[1].length < closed[1].length ? open : closed;
else
$ = closed ?? open;
let chalked = $[4];
let end = $[6] ?? '';
if (!$[5]) {
chalked += end;
end = '';
}
let style: (s: string) => string;
switch ($[3]) {
case 'pb': style = chalk.paleBlue; break;
case 'w': style = chalk.whiteBright; break;
}
return $[1] + chalkUp(style(chalked), style) + currentStyle(chalkUp(end));
}
async function checkForGps(): Promise<void> {
console.log(chalk.cyan('- GPS test -'));
const hasGpsTools = (await isInstalled('gpsd')) && (await isInstalled('gpspipe'));
const hasNtpTools = (await isInstalled('ntpd')) && (await isInstalled('ntpq'));
const hasPpsTools = await isInstalled('ppstest');
let gpsLocationIsWorking = false;
let gpsTimeIsWorking = false;
if (hasGpsTools) {
const gpsInfo = await new Promise<string[]>((resolve, reject) => {
const proc = spawn('gpspipe', ['-w', '-n', '12']);
let finished = false;
monitorProcessLines(proc, null, ErrorMode.NO_ERRORS)
.then(lines => { finished = true; resolve(lines); })
.catch(err => { finished = true; reject(err); });
setTimeout(() => {
if (!finished) {
proc.kill();
console.warn(chalk.yellow('Warning: gpspipe timed out.'));
resolve([]);
}
}, 10000);
});
for (const line of gpsInfo) {
try {
const obj = JSON.parse(line);
if (isObject(obj) && isNumber(obj.lat) && isNumber(obj.lon)) {
gpsLocationIsWorking = true;
break;
}
}
catch {}
}
}
if (hasNtpTools) {
const ntpInfo = await new Promise<string[]>((resolve, reject) => {
const proc = spawn('ntpq', ['-p']);
let finished = false;
monitorProcessLines(proc, null, ErrorMode.NO_ERRORS)
.then(lines => { finished = true; resolve(lines); })
.catch(err => { finished = true; reject(err); });
setTimeout(() => {
if (!finished) {
proc.kill();
console.warn(chalk.yellow('Warning: ntpq timed out.'));
resolve([]);
}
}, 10000);
});
for (const line of ntpInfo) {
if (/^\*SHM\b.+\.PPS\.\s+0\s+l\s+.+?\s[-+]?[.\d]+\s+[.\d]+\s*$/.test(line)) {
gpsTimeIsWorking = true;
break;
}
}
}
if (!gpsLocationIsWorking || !gpsTimeIsWorking) {
const hasChrony = await isInstalled('chrony');
console.log(chalk.yellow('GPS time and/or location services not found'));
console.log(chalk.yellow('The following updates/changes are suggested if GPS support is desired:'));
if (hasChrony)
console.log(chalkUp(' [pb]• Remove [w]chrony[/w] package to avoid conflict with ntpd.'));
if (hasGpsTools)
console.log(chalkUp(' [pb]• Check [w]gpsd[/w] configuration'));
else
console.log(chalkUp(' [pb]• Install [w]gpsd[/w] and [w]gpspipe[/w]'));
if (hasNtpTools)
console.log(chalkUp(' [pb]• Check [w]ntpd[/w] configuration'));
else
console.log(chalkUp(' [pb]• Install [w]ntpd[/w] and [w]ntpq[/w]'));
if (!hasPpsTools)
console.log(chalkUp(' [pb]• Install [w]ppstest[/w]'));
}
else
console.log('GPS time and location services found ' + chalk.green(CHECK_MARK));
}
function portValidate(s: string): boolean {
const port = Number(s);
if (isNaN(port) || port < 1 || port > 65535) {
console.log(chalk.redBright('Port must be a number from 1 to 65535'));
return false;
}
return true;
}
const DOMAIN_PATTERN =
/^(((?!-))(xn--|_)?[-a-z\d]{0,61}[a-z\d]\.)*(xn--)?([a-z\d][-a-z\d]{0,60}|[-a-z\d]{1,30}\.[a-z]{2,})(:\d{1,5})?$/i;
function ntpValidate(s: string): boolean {
const domains = s.split(',').map(d => d.trim());
if (s.trim() === '' || (domains.length > 0 && domains.findIndex(d => !DOMAIN_PATTERN.test(d)) < 0))
return true;
console.log(chalk.redBright('NTP servers must be a valid domain names (with optional port numbers)'));
return false;
}
// Change out-of-date preference to default.
if (process.env.AWC_PREFERRED_WS === 'darksky')
process.env.AWC_PREFERRED_WS = 'wunderground';
function wsValidate(s: string): boolean | string {
if (/^w[-b]*$/i.test(s))
return 'wunderground';
else if (/b/i.test(s))
return 'weatherbit';
else if (/^v/i.test(s))
return 'visual_x';
console.log(chalk.redBright('Weather service must be either (w)underground, weather(b)it, or (v)isual crossing'));
return false;
}
function wsAfter(s: string): void {
if (/^w[-b]*$/i.test(s)) {
console.log(chalk.paleBlue(' Weather Underground chosen, but Weatherbit.io or Visual Crossing can be used'));
console.log(chalk.paleBlue(' as fallback weather services.'));
}
else if (/b/i.test(s)) {
console.log(chalk.paleBlue(' Weatherbit.io chosen, but Weather Underground will be used'));
console.log(chalk.paleBlue(' as a fallback weather service.'));
}
else if (/^v/i.test(s)) {
console.log(chalk.paleBlue(' Visual Crossing chosen, but Weather Underground will be used'));
console.log(chalk.paleBlue(' as a fallback weather service.'));
}
}
function yesOrNo(s: string, assign: (isYes: boolean) => void): boolean {
if (/^[yn]/i.test(s)) {
assign(/^y/i.test(s));
return true;
}
console.log(chalk.redBright('Response must be (y)es or (n)o'));
return false;
}
function adminValidate(s: string): boolean {
return yesOrNo(s, isYes => settings.AWC_ALLOW_ADMIN = isYes ? 'true' : 'false');
}
function upgradeValidate(s: string): boolean {
return yesOrNo(s, isYes => doUpdateUpgrade = isYes);
}
function npmIValidate(s: string): boolean {
return yesOrNo(s, isYes => doNpmI = isYes);
}
function acuValidate(s: string): boolean {
return yesOrNo(s, isYes => doAcu = isYes);
}
function dhtValidate(s: string): boolean {
return yesOrNo(s, isYes => doDht = isYes);
}
function kioskValidate(s: string): boolean {
return yesOrNo(s, isYes => doKiosk = isYes);
}
function pinValidate(s: string): boolean {
if (convertPinToGpio(s) < 0) {
console.log(chalk.redBright(s + ' is not a valid pin number'));
return false;
}
return true;
}
function finalActionValidate(s: string): boolean {
let $: string[];
if (($ = /^([lrn])/i.exec(s.toLowerCase()))) {
if ($[1] === 'l') {
doLaunch = true;
doReboot = false;
}
else if ($[1] === 'r') {
doLaunch = false;
doReboot = true;
}
else
doLaunch = doReboot = false;
return true;
}
console.log(chalk.redBright('Response must be (l)aunch, (r)eboot, or (n)o action'));
return false;
}
const finalAction = (doReboot ? 'R' : doLaunch ? 'L' : '#');
const finalOptions = '(l/r/n)'.replace(finalAction.toLowerCase(), finalAction);
let questions = [
{ prompt: 'Perform initial update/upgrade?', ask: true, yn: true, deflt: doUpdateUpgrade ? 'Y' : 'N', validate: upgradeValidate },
{ prompt: 'Perform npm install? (N option for debug only)', ask: true, yn: true, deflt: doNpmI ? 'Y' : 'N', validate: npmIValidate },
{ name: 'AWC_PORT', prompt: 'HTTP server port.', ask: true, validate: portValidate },
{ prompt: 'Allow user to reboot, shutdown, update, etc.?', ask: true, yn: true, deflt: doAdmin ? 'Y' : 'N', validate: adminValidate },
{ name: 'AWC_NTP_SERVERS', prompt: 'time servers (comma-separated domains, blank for defaults)', ask: true, validate: ntpValidate },
{
name: 'AWC_GOOGLE_API_KEY',
prompt: 'Optional Google geocoding API key (for city names from\n GPS coordinates).' +
(settings.AWC_GOOGLE_API_KEY ? '\n Enter - (dash) to remove old API key' : ''),
ask: true
},
{ // #5
name: 'AWC_PREFERRED_WS',
prompt: 'preferred weather service, (w)underground, weather(b)it,\n or (v)isual crossing).',
ask: true,
validate: wsValidate,
after: wsAfter
},
{
name: 'AWC_WEATHERBIT_API_KEY',
prompt: 'Optional Weatherbit.io (via RapidAPI) key, for\n weather and geocoding.' +
(settings.AWC_WEATHERBIT_API_KEY ? '\n Enter - (dash) to remove old API key' : ''),
ask: true
},
{ // #7
name: 'AWC_VISUAL_CROSSING_API_KEY',
prompt: 'Optional Visual Crossing weather API key.' +
(settings.AWC_VISUAL_CROSSING_API_KEY ? '\n Enter - (dash) to remove old API key' : ''),
ask: true
},
{ prompt: 'Use wired DHT temperature/humidity sensor?', ask: true, yn: true, deflt: doDht ? 'Y' : 'N', validate: dhtValidate },
{ name: 'AWC_WIRED_TH_GPIO', prompt: 'GPIO pin number for wired temp/humidity sensor', ask: (): boolean => doDht, validate: pinValidate },
{ prompt: 'Use wireless temperature/humidity sensors?', ask: true, yn: true, deflt: doAcu ? 'Y' : 'N', validate: acuValidate },
{ name: 'AWC_WIRELESS_TH_GPIO', prompt: 'GPIO pin number for wireless temp/humidity sensors', ask: (): boolean => doAcu, validate: pinValidate },
{
prompt: `When finished, (l)aunch A/W clock, (r)eboot, or (n)o action ${finalOptions}?`,
ask: true,
deflt: finalAction,
validate: finalActionValidate
}
];
if (doDedicated) {
questions.splice(questions.length - 1, 0,
{ prompt: 'Launch browser in kiosk mode?', ask: true, yn: true, deflt: doKiosk ? 'Y' : 'N', validate: kioskValidate }
);
}
if (noStop)
questions = questions.slice(0, -1);
async function promptForConfiguration(): Promise<void> {
console.log(chalk.cyan(sol + '- Configuration -'));
for (let i = 0; i < questions.length; ++i) {
const q = questions[i];
if (!(isFunction(q.ask) ? q.ask() : q.ask))
continue;
if (q.name) {
write(chalk.bold(q.name) + ' - ' + q.prompt + '\n ' +
(settings[q.name] ? '(default: ' + chalk.paleYellow(settings[q.name]) + ')' : '') + ': ');
}
else {
write(q.prompt);
if (q.yn)
write(q.deflt === 'Y' ? ' (Y/n)' : ' (y/N)');
write(': ');
}
const response = await readUserInput();
if (response === '\x18') {
i = Math.max(i - 2, -1);
continue;
}
else if (response) {
const validation = q.validate ? q.validate(response) : true;
if (isString(validation))
settings[q.name] = validation;
else if (!validation) {
--i;
continue;
}
else if (q.name) {
if (response === '-')
delete settings[q.name];
else
settings[q.name] = response;
}
}
else if (!response && q.deflt === '#') {
--i;
console.log(chalk.redBright('Response required'));
}
if (q.after)
q.after(settings[q.name]);
}
}
async function installFonts(): Promise<void> {
showStep();
const fonts = fs.readdirSync(fontSrc).filter(name => /.\.ttf/i.test(name));
const fontsToAdd = fonts.filter(font => !fs.existsSync(fontDst + font));
if (fontsToAdd.length > 0) {
write('Installing fonts' + trailingSpace);
for (const font of fontsToAdd)
await monitorProcess(spawn('cp', [fontSrc + font, fontDst + font]), spin, ErrorMode.ANY_ERROR);
await monitorProcess(spawn('fc-cache', ['-f']), spin, ErrorMode.ANY_ERROR);
}
else
write('Fonts already installed' + trailingSpace);
stepDone();
}
async function disableScreenSaver(uid: number): Promise<void> {
const screenSaverJustInstalled = await install('xscreensaver');
const settingsFile = `${userHome}/.xscreensaver`;
showStep();
write('Disabling screen saver' + trailingSpace);
if (screenSaverJustInstalled || !fs.existsSync(settingsFile)) {
const procList = await monitorProcess(spawn('ps', ['-ax']), spin);
const saverRunning = /\d\s+xscreensaver\b/.test(procList);
if (!saverRunning) {
spawn('xscreensaver', [], { uid, detached: true, env: process.env });
await sleep(500);
}
const settingsProcess = spawn('xscreensaver-demo', [], { uid, env: process.env });
await sleep(3000, spin);
settingsProcess.kill('SIGTERM');
await sleep(500, spin);
}
await monitorProcess(spawn('sed',
['-i', '-r', "'s/^(mode:\\s+)\\w+$/\\1off/'", settingsFile],
{ uid, shell: true }), spin, ErrorMode.ANY_ERROR);
// Stop and restart screen saver to make sure modified settings are read
const procList = await monitorProcess(spawn('ps', ['-ax']), spin);
const ssProcessNo = (/^(\d+)\s+.*\d\s+xscreensaver\b/.exec(procList) ?? [])[1];
if (ssProcessNo)
await monitorProcess(spawn('kill', [ssProcessNo]), spin);
spawn('xscreensaver', [], { uid, detached: true });
stepDone();
}
async function doClientBuild(): Promise<void> {
if (doNpmI || !fs.existsSync('node_modules') || !fs.existsSync('package-lock.json')) {
showStep();
write('Updating client' + trailingSpace);
await monitorProcess(spawn('npm', uid, ['i', '--no-save']), spin);
stepDone();
}
showStep();
write('Building client' + trailingSpace);
if (fs.existsSync('dist'))
await monitorProcess(spawn('rm', uid, ['-Rf', 'dist']), spin);
const opts = { shell: true, env: process.env };
const args = ['run', 'build:client' + (enoughRam ? '' : ':tiny')];
if (prod)
args.push('--', '--env', 'mode=prod');
const output = getWebpackSummary(await monitorProcess(spawn('npm', uid, args, opts), spin));
stepDone();
if (output?.trim())
console.log(chalk.mediumGray(output));
}
async function doServerBuild(): Promise<void> {
if (doNpmI || !fs.existsSync('server/node_modules') || !fs.existsSync('server/package-lock.json')) {
showStep();
write('Updating server' + trailingSpace);
await monitorProcess(spawn('npm', uid, ['i', '--no-save'], { cwd: path.join(__dirname, 'server') }), spin);
stepDone();
}
showStep();
write('Building server' + trailingSpace);
if (fs.existsSync('server/dist'))
await monitorProcess(spawn('rm', uid, ['-Rf', 'server/dist']), spin);
const opts = { shell: true, cwd: path.join(__dirname, 'server'), env: process.env };
const output = getWebpackSummary(await monitorProcess(spawn('npm', uid,
['run', isWindows ? 'build-win' : 'build' + (enoughRam ? '' : ':tiny')], opts), spin));
stepDone();
if (output?.trim())
console.log(chalk.mediumGray(output));
if (doAcu || doDht) {
showStep();
const args = ['i', '-P', 'rpi-acu-rite-temperature@2', '[email protected]'];
if (doAcu && doDht)
write('Adding wireless and wired temp/humidity sensor support' + trailingSpace);
else if (doAcu) {
args.splice(3, 1);
write('Adding Acu-Rite wireless temperature/humidity sensor support' + trailingSpace);
}
else {
args.splice(2, 1);
write('Adding DHT wired temperature/humidity sensor support' + trailingSpace);
}
await npmInit();
await monitorProcess(spawn('npm', uid, args, { cwd: path.join(__dirname, 'server', 'dist') }), spin);
stepDone();
}
}
async function doServiceDeployment(): Promise<void> {
let autostartDir = path.join(userHome, autostartDst);
let morePi_ish = false;
if (!autostartDir.endsWith('-pi')) {
const lxdePiCheckDir = path.join(userHome, lxdePiCheck);