summaryrefslogtreecommitdiff
path: root/tools/win/vbscript/helpers.vbs
blob: b66bc91a4c4614766eaaa015bdade5f4bd21854f (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
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
' $Id$
'' @file
' Common VBScript helpers used by configure.vbs and later others.
'
' Requires the script including it to define a LogPrint function.
'

'
' Copyright (C) 2006-2023 Oracle and/or its affiliates.
'
' This file is part of VirtualBox base platform packages, as
' available from https://www.virtualbox.org.
'
' This program is free software; you can redistribute it and/or
' modify it under the terms of the GNU General Public License
' as published by the Free Software Foundation, in version 3 of the
' License.
'
' This program is distributed in the hope that it will be useful, but
' WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
' General Public License for more details.
'
' You should have received a copy of the GNU General Public License
' along with this program; if not, see <https://www.gnu.org/licenses>.
'
' SPDX-License-Identifier: GPL-3.0-only
'


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Global Variables                                                                                                              '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
dim g_objShell
Set g_objShell   = WScript.CreateObject("WScript.Shell")

dim g_objFileSys
Set g_objFileSys = WScript.CreateObject("Scripting.FileSystemObject")

'' Whether to ignore (continue) on errors.
dim g_blnContinueOnError
g_blnContinueOnError = False

'' The script's exit code (for ignored errors).
dim g_rcScript
g_rcScript = 0


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Paths                                                                                                                '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Converts to unix slashes
function UnixSlashes(str)
   UnixSlashes = replace(str, "\", "/")
end function


''
' Converts to dos slashes
function DosSlashes(str)
   DosSlashes = replace(str, "/", "\")
end function


''
' Get the path of the parent directory. Returns root if root was specified.
' Expects abs path.
function PathParent(str)
   PathParent = g_objFileSys.GetParentFolderName(DosSlashes(str))
end function


''
' Strips the filename from at path.
function PathStripFilename(str)
   PathStripFilename = g_objFileSys.GetParentFolderName(DosSlashes(str))
end function


''
' Get the abs path, use the short version if necessary.
function PathAbs(str)
   strAbs    = g_objFileSys.GetAbsolutePathName(DosSlashes(str))
   strParent = g_objFileSys.GetParentFolderName(strAbs)
   if strParent = "" then
      PathAbs = strAbs
   else
      strParent = PathAbs(strParent)  ' Recurse to resolve parent paths.
      PathAbs   = g_objFileSys.BuildPath(strParent, g_objFileSys.GetFileName(strAbs))

      dim obj
      set obj = Nothing
      if FileExists(PathAbs) then
         set obj = g_objFileSys.GetFile(PathAbs)
      elseif DirExists(PathAbs) then
         set obj = g_objFileSys.GetFolder(PathAbs)
      end if

      if not (obj is nothing) then
         for each objSub in obj.ParentFolder.SubFolders
            if obj.Name = objSub.Name  or  obj.ShortName = objSub.ShortName then
               if  InStr(1, objSub.Name, " ") > 0 _
                Or InStr(1, objSub.Name, "&") > 0 _
                Or InStr(1, objSub.Name, "$") > 0 _
                  then
                  PathAbs = g_objFileSys.BuildPath(strParent, objSub.ShortName)
                  if  InStr(1, PathAbs, " ") > 0 _
                   Or InStr(1, PathAbs, "&") > 0 _
                   Or InStr(1, PathAbs, "$") > 0 _
                     then
                     MsgFatal "PathAbs(" & str & ") attempted to return filename with problematic " _
                      & "characters in it (" & PathAbs & "). The tool/sdk referenced will probably " _
                      & "need to be copied or reinstalled to a location without 'spaces', '$', ';' " _
                      & "or '&' in the path name. (Unless it's a problem with this script of course...)"
                  end if
               else
                  PathAbs = g_objFileSys.BuildPath(strParent, objSub.Name)
               end if
               exit for
            end if
         next
      end if
   end if
end function


''
' Get the abs path, use the long version.
function PathAbsLong(str)
   strAbs    = g_objFileSys.GetAbsolutePathName(DosSlashes(str))
   strParent = g_objFileSys.GetParentFolderName(strAbs)
   if strParent = "" then
      PathAbsLong = strAbs
   else
      strParent = PathAbsLong(strParent)  ' Recurse to resolve parent paths.
      PathAbsLong = g_objFileSys.BuildPath(strParent, g_objFileSys.GetFileName(strAbs))

      dim obj
      set obj = Nothing
      if FileExists(PathAbsLong) then
         set obj = g_objFileSys.GetFile(PathAbsLong)
      elseif DirExists(PathAbsLong) then
         set obj = g_objFileSys.GetFolder(PathAbsLong)
      end if

      if not (obj is nothing) then
         for each objSub in obj.ParentFolder.SubFolders
            if obj.Name = objSub.Name  or  obj.ShortName = objSub.ShortName then
               PathAbsLong = g_objFileSys.BuildPath(strParent, objSub.Name)
               exit for
            end if
         next
      end if
   end if
end function


''
' Compare two paths w/o abspathing them.
'
' Ignores case, slash direction, multiple slashes and single dot components.
'
function PathMatch(strPath1, strPath2)
   PathMatch = true
   if StrComp(strPath1, strPath2, vbTextCompare) <> 0 then
      strPath1 = DosSlashes(strPath1)
      strPath2 = DosSlashes(strPath2)
      if StrComp(strPath1, strPath2, vbTextCompare) <> 0 then
         ' Compare character by character
         dim off1 : off1 = 1
         dim off2 : off2 = 1

         ' Compare UNC prefix if any, because the code below cannot handle it.  UNC has exactly two slashes.
         if Mid(strPath1, 1, 2) = "\\" and Mid(strPath2, 1, 2) = "\\" then
            if (Mid(strPath1, 3, 1) = "\") <> (Mid(strPath2, 3, 1) = "\") then
               PathMatch = false
               exit function
            end if
            off1 = off1 + 2
            off2 = off2 + 2
            if Mid(strPath1, 3, 1) = "\" then
               off1 = PathMatchSkipSlashesAndSlashDotHelper(strPath1, off1)
               off2 = PathMatchSkipSlashesAndSlashDotHelper(strPath2, off2)
            end if
         end if

         ' Compare the rest.
         dim ch1, ch2
         do while off1 <= Len(strPath1) and off2 <= Len(strPath2)
            ch1 = Mid(strPath1, off1, 1)
            ch2 = Mid(strPath2, off2, 1)
            if StrComp(ch1, ch2, vbTextCompare) = 0 then
               off1 = off1 + 1
               off2 = off2 + 1
               if ch1 = "\" then
                  off1 = PathMatchSkipSlashesAndSlashDotHelper(strPath1, off1)
                  off2 = PathMatchSkipSlashesAndSlashDotHelper(strPath2, off2)
               end if
            else
               PathMatch = False
               exit function
            end if
         loop

         ' One or both of the strings ran out.  That's fine if we've only got slashes
         ' and "." components left in the other.
         if off1 <= Len(strPath1) and Mid(strPath1, off1, 1) = "\" then
            off1 = PathMatchSkipSlashesAndSlashDotHelper(strPath1, off1 + 1)
         end if
         if off2 <= Len(strPath2) and Mid(strPath2, off2, 1) = "\" then
            off2 = PathMatchSkipSlashesAndSlashDotHelper(strPath2, off2 + 1)
         end if
         PathMatch = off1 > Len(strPath1) and off2 > Len(strPath2)
      end if
   end if
end function

'' PathMatch helper
function PathMatchSkipSlashesAndSlashDotHelper(strPath, off)
   dim ch
   do while off <= Len(strPath)
      ch = Mid(strPath, off, 1)
      if ch = "\" then
         off = off + 1
      elseif ch = "." and off = Len(strPath) then
         off = off + 1
      elseif ch = "." and Mid(strPath, off, 2) = ".\" then
         off = off + 2
      else
         exit do
      end if
   loop
   PathMatchSkipSlashesAndSlashDotHelper = off
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Files and Dirs                                                                                                       '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Read a file (typically the tmp file) into a string.
function FileToString(strFilename)
   const ForReading = 1, TristateFalse = 0
   dim objLogFile, str

   set objFile = g_objFileSys.OpenTextFile(DosSlashes(strFilename), ForReading, False, TristateFalse)
   str = objFile.ReadAll()
   objFile.Close()

   FileToString = str
end function


''
' Deletes a file
sub FileDelete(strFilename)
   if g_objFileSys.FileExists(DosSlashes(strFilename)) then
      g_objFileSys.DeleteFile(DosSlashes(strFilename))
   end if
end sub


''
' Appends a line to an ascii file.
sub FileAppendLine(strFilename, str)
   const ForAppending = 8, TristateFalse = 0
   dim objFile

   set objFile = g_objFileSys.OpenTextFile(DosSlashes(strFilename), ForAppending, True, TristateFalse)
   objFile.WriteLine(str)
   objFile.Close()
end sub


''
' Checks if the file exists.
function FileExists(strFilename)
   FileExists = g_objFileSys.FileExists(DosSlashes(strFilename))
   DbgPrint "FileExists(" & strFilename & ") -> " & FileExists
end function


''
' Checks if the directory exists.
function DirExists(strDirectory)
   DirExists = g_objFileSys.FolderExists(DosSlashes(strDirectory))
   DbgPrint "DirExists(" & strDirectory & ") -> " & DirExists
end function


''
' Returns true if there are subfolders starting with the given string.
function HasSubdirsStartingWith(strFolder, strStartingWith)
   HasSubdirsStartingWith = False
   if DirExists(strFolder) then
      dim obj
      set obj = g_objFileSys.GetFolder(strFolder)
      for each objSub in obj.SubFolders
         if StrComp(Left(objSub.Name, Len(strStartingWith)), strStartingWith) = 0 then
            HasSubdirsStartingWith = True
            LogPrint "# HasSubdirsStartingWith(" & strFolder & "," & strStartingWith & ") found " & objSub.Name
            exit for
         end if
      next
   end if
end function


''
' Returns a sorted array of subfolder names that starts with the given string.
function GetSubdirsStartingWith(strFolder, strStartingWith)
   if DirExists(strFolder) then
      dim obj, i
      set obj = g_objFileSys.GetFolder(strFolder)
      i = 0
      for each objSub in obj.SubFolders
         if StrComp(Left(objSub.Name, Len(strStartingWith)), strStartingWith) = 0 then
            i = i + 1
         end if
      next
      if i > 0 then
         redim arrResult(i - 1)
         i = 0
         for each objSub in obj.SubFolders
            if StrComp(Left(objSub.Name, Len(strStartingWith)), strStartingWith) = 0 then
               arrResult(i) = objSub.Name
               i = i + 1
            end if
         next
         GetSubdirsStartingWith = arrResult
      else
         GetSubdirsStartingWith = Array()
      end if
   else
      GetSubdirsStartingWith = Array()
   end if
end function


''
' Returns a sorted array of subfolder names that starts with the given string.
function GetSubdirsStartingWithVerSorted(strFolder, strStartingWith)
   GetSubdirsStartingWithVerSorted = ArrayVerSortStrings(GetSubdirsStartingWith(strFolder, strStartingWith))
end function


''
' Returns a reverse version sorted array of subfolder names that starts with the given string.
function GetSubdirsStartingWithRVerSorted(strFolder, strStartingWith)
   GetSubdirsStartingWithRVerSorted = ArrayRVerSortStrings(GetSubdirsStartingWith(strFolder, strStartingWith))
end function


''
' Try find the specified file in the specified path variable.
function WhichEx(strEnvVar, strFile)
   dim strPath, iStart, iEnd, str

   ' the path
   strPath = EnvGet(strEnvVar)
   iStart = 1
   do while iStart <= Len(strPath)
      iEnd = InStr(iStart, strPath, ";")
      if iEnd <= 0 then iEnd = Len(strPath) + 1
      if iEnd > iStart then
         str = Mid(strPath, iStart, iEnd - iStart) & "/" & strFile
         if FileExists(str) then
            WhichEx = str
            exit function
         end if
      end if
      iStart = iEnd + 1
   loop

   ' registry or somewhere?

   WhichEx = ""
end function


''
' Try find the specified file in the path.
function Which(strFile)
   Which = WhichEx("Path", strFile)
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Processes                                                                                                            '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Checks if this is a WOW64 process.
function IsWow64()
   if g_objShell.Environment("PROCESS")("PROCESSOR_ARCHITEW6432") <> "" then
      IsWow64 = 1
   else
      IsWow64 = 0
   end if
end function


''
' Executes a command in the shell catching output in strOutput
function Shell(strCommand, blnBoth, ByRef strOutput)
   dim strShell, strCmdline, objExec, str

   strShell = g_objShell.ExpandEnvironmentStrings("%ComSpec%")
   if blnBoth = true then
      strCmdline = strShell & " /c " & strCommand & " 2>&1"
   else
      strCmdline = strShell & " /c " & strCommand & " 2>nul"
   end if

   LogPrint "# Shell: " & strCmdline
   Set objExec = g_objShell.Exec(strCmdLine)
   strOutput = objExec.StdOut.ReadAll()
   objExec.StdErr.ReadAll()
   do while objExec.Status = 0
      Wscript.Sleep 20
      strOutput = strOutput & objExec.StdOut.ReadAll()
      objExec.StdErr.ReadAll()
   loop

   LogPrint "# Status: " & objExec.ExitCode
   LogPrint "# Start of Output"
   LogPrint strOutput
   LogPrint "# End of Output"

   Shell = objExec.ExitCode
end function


''
' Gets the SID of the current user.
function GetSid()
   dim objNet, strUser, strDomain, offSlash, objWmiUser
   GetSid = ""

   ' Figure the user + domain
   set objNet = CreateObject("WScript.Network")
   strUser   = objNet.UserName
   strDomain = objNet.UserDomain
   offSlash  = InStr(1, strUser, "\")
   if offSlash > 0 then
      strDomain = Left(strUser, offSlash - 1)
      strUser   = Right(strUser, Len(strUser) - offSlash)
   end if

   ' Lookup the user.
   on error resume next
   set objWmiUser = GetObject("winmgmts:{impersonationlevel=impersonate}!/root/cimv2:Win32_UserAccount." _
                              & "Domain='" & strDomain &"',Name='" & strUser & "'")
   if err.number = 0 then
      GetSid = objWmiUser.SID
   end if
end function


''
' Gets the commandline used to invoke the script.
function GetCommandline()
   dim str, i

   '' @todo find an api for querying it instead of reconstructing it like this...
   GetCommandline = "cscript configure.vbs"
   for i = 1 to WScript.Arguments.Count
      str = WScript.Arguments.Item(i - 1)
      if str = "" then
         str = """"""
      elseif (InStr(1, str, " ")) then
         str = """" & str & """"
      end if
      GetCommandline = GetCommandline & " " & str
   next
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Environment                                                                                                          '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Gets an environment variable.
function EnvGet(strName)
   EnvGet = g_objShell.Environment("PROCESS")(strName)
end function


''
' Gets an environment variable with default value if not found.
function EnvGetDef(strName, strDefault)
   dim strValue
   strValue = g_objShell.Environment("PROCESS")(strName)
   if strValue = "" or IsNull(strValue) or IsEmpty(strValue) then
      EnvGetDef = strDefault
   else
      EnvGetDef = strValue
   end if
end function


''
' Gets an environment variable with default value if not found or not
' in the array of valid values.  Issue warning about invalid values.
function EnvGetDefValid(strName, strDefault, arrValidValues)
   dim strValue
   strValue = g_objShell.Environment("PROCESS")(strName)
   if strValue = "" or IsNull(strValue) or IsEmpty(strValue) then
      EnvGetDefValid = strDefault
   elseif not ArrayContainsString(arrValidValues, strValue) then
      MsgWarning "Invalid value " & strName & " value '" & EnvGetDefValid & "', using '" & strDefault & "' instead."
      EnvGetDefValid = strDefault
   else
      EnvGetDefValid = strValue
   end if
end function


''
' Sets an environment variable.
sub EnvSet(strName, strValue)
   g_objShell.Environment("PROCESS")(strName) = strValue
   LogPrint "EnvSet: " & strName & "=" & strValue
end sub


''
' Prepends a string to an Path-like environment variable.
function EnvPrependItemEx(strName, strItem, strSep, blnKeepEmpty, ByRef fnItemMatcher)
   dim strValue
   strValue = EnvRemoveItemEx(strName, strItem, strSep, blnKeepEmpty, fnItemMatcher, "EnvPrependItemEx")
   if strValue <> "" then
      strValue = strItem & strSep & strValue
   else
      strValue = strItem
   end if
   g_objShell.Environment("PROCESS")(strName) = strValue
   EnvPrependItemEx = strValue
end function


''
' Appends a string to an Path-like environment variable,
function EnvAppendItemEx(strName, strItem, strSep, blnKeepEmpty, ByRef fnItemMatcher)
   dim strValue
   strValue = EnvRemoveItemEx(strName, strItem, strSep, blnKeepEmpty, fnItemMatcher, "EnvAppendItemEx")
   if strValue <> "" then
      strValue = strValue & strSep & strItem
   else
      strValue = strItem
   end if
   g_objShell.Environment("PROCESS")(strName) = strValue
   EnvAppendItemEx = strValue
end function


''
' Generic item remover.
'
' fnItemMatcher(strItem1, strItem2)
'
function EnvRemoveItemEx(strName, strItem, strSep, blnKeepEmpty, ByRef fnItemMatcher, strCaller)
   dim strValue, off
   strValue = g_objShell.Environment("PROCESS")(strName)
   EnvRemoveItemEx = strValue
   if strValue <> "" then
      ' Split it up into an array of items
      dim   arrItems    : arrItems    = Split(strValue, strSep, -1, vbTextCompare)

      ' Create an array of matching indexes that we should remove.
      dim   cntToRemove : cntToRemove = 0
      redim arrIdxToRemove(ArraySize(arrItems) - 1)
      dim   i, strCur
      for i = LBound(arrItems) to UBound(arrItems)
         strCur = arrItems(i)
         if fnItemMatcher(strCur, strItem) or (not blnKeepEmpty and strCur = "") then
            arrIdxToRemove(cntToRemove) = i
            cntToRemove = cntToRemove + 1
         end if
      next

      ' Did we find anthing to remove?
      if cntToRemove > 0 then
         ' Update the array and join it up again.
         for i = cntToRemove - 1 to 0 step -1
            arrItems = ArrayRemove(arrItems, arrIdxToRemove(i))
         next
         dim strNewValue : strNewValue = ArrayJoinString(arrItems, strSep)
         EnvRemoveItemEx = strNewValue

         ' Update the environment variable.
         LogPrint strCaller &": " & strName & ": '" & strValue & "' --> '" & strNewValue & "'"
         g_objShell.Environment("PROCESS")(strName) = strNewValue
      end if
   end if
end function


''
' Generic case-insensitive item matcher.
' See also PathMatch().
function EnvItemMatch(strItem1, strItem2)
   EnvItemMatch = (StrComp(strItem1, strItem2) = 0)
end function


''
' Prepends an item to an environment variable, after first removing any
' existing ones (case-insensitive, preserves empty elements).
function EnvPrependItem(strName, strItem, strSep)
   EnvPrependItem = EnvPrependItemEx(strName, strItem, strSep, true, GetRef("EnvItemMatch"))
   LogPrint "EnvPrependItem: " & strName & "=" & EnvPrependPathItem
end function


''
' Appends an item to an environment variable, after first removing any
' existing ones (case-insensitive, preserves empty elements).
function EnvAppendItem(strName, strItem, strSep)
   EnvAppendItem = EnvAppendItemEx(strName, strItem, strSep, true, GetRef("EnvItemMatch"))
   LogPrint "EnvAppendItem: " & strName & "=" & EnvPrependPathItem
end function


''
' Removes a string element from an environment variable, case
' insensitive but preserving empty elements.
function EnvRemoveItem(strName, strItem, strSep)
   EnvRemoveItem = EnvRemoveItemEx(strName, strIten, strSep, true, GetRef("EnvItemMatch"), "EnvRemoveItem")
end function


''
' Appends a string to an Path-like environment variable,
function EnvPrependPathItem(strName, strItem, strSep)
   EnvPrependPathItem = EnvPrependItemEx(strName, strItem, strSep, false, GetRef("PathMatch"))
   LogPrint "EnvPrependPathItem: " & strName & "=" & EnvPrependPathItem
end function


''
' Appends a string to an Path-like environment variable,
function EnvAppendPathItem(strName, strItem, strSep)
   EnvAppendPathItem = EnvAppendItemEx(strName, strItem, strSep, false, GetRef("PathMatch"))
   LogPrint "EnvAppendPathItem: " & strName & "=" & EnvAppendPathItem
end function


''
' Removes a string element from an Path-like environment variable, case
' insensitive and treating forward and backward slashes the same way.
function EnvRemovePathItem(strName, strItem, strSep)
   EnvRemovePathItem = EnvRemoveItemEx(strName, strIten, strSep, false, GetRef("PathMatch"), "EnvRemovePathItem")
end function


''
' Prepends a string to an environment variable
sub EnvUnset(strName)
   g_objShell.Environment("PROCESS").Remove(strName)
   LogPrint "EnvUnset: " & strName
end sub


''
' Gets the first non-empty environment variable of the given two.
function EnvGetFirst(strName1, strName2)
   EnvGetFirst = g_objShell.Environment("PROCESS")(strName1)
   if EnvGetFirst = "" then
      EnvGetFirst = g_objShell.Environment("PROCESS")(strName2)
   end if
end function

''
' Checks if the given enviornment variable exists.
function EnvExists(strName)
   EnvExists = g_objShell.Environment("PROCESS")(strName) <> ""
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Strings                                                                                                              '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Right pads a string with spaces to the given length
function RightPad(str, cch)
   if Len(str) < cch then
      RightPad = str & String(cch - Len(str), " ")
   else
      RightPad = str
   end if
end function


''
' Checks if the given character is a decimal digit
function CharIsDigit(ch)
   CharIsDigit = (InStr(1, "0123456789", ch) > 0)
end function

''
' Worker for StrVersionCompare
' The offset is updated to point to the first non-digit character.
function CountDigitsIgnoreLeadingZeros(ByRef str, ByRef off)
   dim cntDigits, blnLeadingZeros, ch, offInt
   cntDigits = 0
   if CharIsDigit(Mid(str, off, 1)) then
      ' Rewind to start of digest sequence.
      do while off > 1
         if not CharIsDigit(Mid(str, off - 1, 1)) then exit do
         off = off - 1
      loop
      ' Count digits, ignoring leading zeros.
      blnLeadingZeros = True
      for off = off to Len(str)
         ch = Mid(str, off, 1)
         if CharIsDigit(ch) then
            if ch <> "0" or blnLeadingZeros = False then
               cntDigits = cntDigits + 1
               blnLeadingZeros = False
            end if
         else
            exit for
         end if
      next
      ' If all zeros, count one of them.
      if cntDigits = 0 then cntDigits = 1
   end if
   CountDigitsIgnoreLeadingZeros = cntDigits
end function

''
' Very simple version string compare function.
' @returns < 0 if str1 is smaller than str2
' @returns 0   if str1 and str2 are equal
' @returns > 1 if str2 is larger than str1
function StrVersionCompare(str1, str2)
   ' Compare the strings.  We can rely on StrComp if equal or one is empty.
   'LogPrint "StrVersionCompare("&str1&","&str2&"):"
   StrVersionCompare = StrComp(str2, str1)
   if StrVersionCompare <> 0 then
      dim cch1, cch2, off1, off2, ch1, ch2, chPrev1, chPrev2, intDiff, cchDigits
      cch1 = Len(str1)
      cch2 = Len(str2)
      if cch1 > 0 and cch2 > 0 then
         ' Compare the common portion
         off1 = 1
         off2 = 1
         chPrev1 = "x"
         chPrev2 = "x"
         do while off1 <= cch1 and off2 <= cch2
            ch1 = Mid(str1, off1, 1)
            ch2 = Mid(str2, off2, 1)
            if ch1 = ch2 then
               off1 = off1 + 1
               off2 = off2 + 1
               chPrev1 = ch1
               chPrev2 = ch2
            else
               ' Is there a digest sequence in play.  This includes the scenario where one of the
               ' string ran out of digests.
               dim blnDigest1 : blnDigest1 = CharIsDigit(ch1)
               dim blnDigest2 : blnDigest2 = CharIsDigit(ch2)
               if    (blnDigest1 = True or blnDigest2 = True) _
                 and (blnDigest1 = True or CharIsDigit(chPrev1) = True) _
                 and (blnDigest2 = True or CharIsDigit(chPrev2) = True) _
               then
                  'LogPrint "StrVersionCompare: off1="&off1&" off2="&off2&" ch1="&ch1&" chPrev1="&chPrev1&" ch2="&ch2&" chPrev2="&chPrev2
                  if blnDigest1 = False then off1 = off1 - 1
                  if blnDigest2 = False then off2 = off2 - 1
                  ' The one with the fewer digits comes first.
                  ' Note! off1 and off2 are adjusted to next non-digit character in the strings.
                  cchDigits = CountDigitsIgnoreLeadingZeros(str1, off1)
                  intDiff = cchDigits - CountDigitsIgnoreLeadingZeros(str2, off2)
                  'LogPrint "StrVersionCompare: off1="&off1&" off2="&off2&" cchDigits="&cchDigits
                  if intDiff <> 0 then
                     StrVersionCompare = intDiff
                     'LogPrint "StrVersionCompare: --> "&intDiff&" #1"
                     exit function
                  end if

                  ' If the same number of digits, the smaller digit wins. However, because of
                  ' potential leading zeros, we must redo the compare. Assume ASCII-like stuff
                  ' and we can use StrComp for this.
                  intDiff = StrComp(Mid(str1, off1 - cchDigits, cchDigits), Mid(str2, off2 - cchDigits, cchDigits))
                  if intDiff <> 0 then
                     StrVersionCompare = intDiff
                     'LogPrint "StrVersionCompare: --> "&intDiff&" #2"
                     exit function
                  end if
                  chPrev1 = "x"
                  chPrev2 = "x"
               else
                  if blnDigest1 then
                     StrVersionCompare = -1   ' Digits before characters
                     'LogPrint "StrVersionCompare: --> -1 (#3)"
                  elseif blnDigest2 then
                     StrVersionCompare = 1       ' Digits before characters
                     'LogPrint "StrVersionCompare: --> 1 (#4)"
                  else
                     StrVersionCompare = StrComp(ch1, ch2)
                     'LogPrint "StrVersionCompare: --> "&StrVersionCompare&" (#5)"
                  end if
                  exit function
               end if
            end if
         loop

         ' The common part matches up, so the shorter string 'wins'.
         StrVersionCompare = (cch1 - off1) - (cch2 - off2)
      end if
   end if
   'LogPrint "StrVersionCompare: --> "&StrVersionCompare&" (#6)"
end function


''
' Returns the first list of the given string.
function StrGetFirstLine(str)
   dim off
   off = InStr(1, str, Chr(10))
   if off <= 0 then off = InStr(1, str, Chr(13))
   if off > 0 then
      StrGetFirstLine = Mid(str, 1, off)
   else
      StrGetFirstLine = str
   end if
end function


''
' Returns the first word in the given string.
'
' Only recognizes space, tab, newline and carriage return as word separators.
'
function StrGetFirstWord(str)
   dim strSep, offWord, offEnd, offEnd2, strSeparators
   strSeparators = " " & Chr(9) & Chr(10) & Chr(13)

   ' Skip leading separators.
   for offWord = 1 to Len(str)
      if InStr(1, strSeparators, Mid(str, offWord, 1)) < 1 then exit for
   next

   ' Find the end.
   offEnd = Len(str) + 1
   for offSep = 1 to Len(strSeparators)
      offEnd2 = InStr(offWord, str, Mid(strSeparators, offSep, 1))
      if offEnd2 > 0 and offEnd2 < offEnd then offEnd = offEnd2
   next

   StrGetFirstWord = Mid(str, offWord, offEnd - offWord)
end function


''
' Checks if the string starts with the given prefix (case sensitive).
function StrStartsWith(str, strPrefix)
   if len(str) >= Len(strPrefix) then
      StrStartsWith = (StrComp(Left(str, Len(strPrefix)), strPrefix, vbBinaryCompare) = 0)
   else
      StrStartsWith = false
   end if
end function


''
' Checks if the string starts with the given prefix, case insenstive edition.
function StrStartsWithI(str, strPrefix)
   if len(str) >= Len(strPrefix) then
      StrStartsWithI = (StrComp(Left(str, Len(strPrefix)), strPrefix, vbTextCompare) = 0)
   else
      StrStartsWithI = false
   end if
end function


''
' Checks if the string ends with the given suffix (case sensitive).
function StrEndsWith(str, strSuffix)
   if len(str) >= Len(strSuffix) then
      StrEndsWith = (StrComp(Right(str, Len(strSuffix)), strSuffix, vbBinaryCompare) = 0)
   else
      StrEndsWith = false
   end if
end function


''
' Checks if the string ends with the given suffix, case insenstive edition.
function StrEndsWithI(str, strSuffix)
   if len(str) >= Len(strSuffix) then
      StrEndsWithI = (StrComp(Right(str, Len(strSuffix)), strSuffix, vbTextCompare) = 0)
   else
      StrEndsWithI = false
   end if
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Arrays                                                                                                               '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Returns a reverse array (copy).
function ArrayReverse(arr)
   dim cnt, i, j, iHalf, objTmp
   cnt = UBound(arr) - LBound(arr) + 1
   if cnt > 0 then
      j     = UBound(arr)
      iHalf = Fix(LBound(arr) + cnt / 2)
      for i = LBound(arr) to iHalf - 1
         objTmp = arr(i)
         arr(i) = arr(j)
         arr(j) = objTmp
         j = j - 1
      next
   end if
   ArrayReverse = arr
end function


''
' Returns a reverse sorted array (strings).
function ArraySortStringsEx(arrStrings, ByRef fnCompare)
   dim str1, str2, i, j
   for i = LBound(arrStrings) to UBound(arrStrings)
      str1 = arrStrings(i)
      for j = i + 1 to UBound(arrStrings)
         str2 = arrStrings(j)
         if fnCompare(str2, str1) < 0 then
            arrStrings(j) = str1
            str1 = str2
         end if
      next
      arrStrings(i) = str1
   next
   ArraySortStringsEx = arrStrings
end function

'' Wrapper for StrComp as GetRef("StrComp") fails.
function WrapStrComp(str1, str2)
   WrapStrComp = StrComp(str1, str2)
end function

''
' Returns a reverse sorted array (strings).
function ArraySortStrings(arrStrings)
   ArraySortStrings = ArraySortStringsEx(arrStrings, GetRef("WrapStrComp"))
end function


''
' Returns a reverse sorted array (strings).
function ArrayVerSortStrings(arrStrings)
   ArrayVerSortStrings = ArraySortStringsEx(arrStrings, GetRef("StrVersionCompare"))
end function


'' Wrapper for StrComp as GetRef("StrComp") fails.
function WrapStrCompNeg(str1, str2)
   WrapStrCompNeg = -StrComp(str1, str2)
end function

''
' Returns a reverse sorted array (strings).
function ArrayRSortStrings(arrStrings)
   ArrayRSortStrings = ArraySortStringsEx(arrStrings, GetRef("WrapStrCompNeg"))
end function


''
' Returns a reverse version sorted array (strings).
function ArrayRVerSortStrings(arrStrings)
   ArrayRVerSortStrings = ArrayReverse(ArraySortStringsEx(arrStrings, GetRef("StrVersionCompare")))
end function


''
' Prints a string array.
sub ArrayPrintStrings(arrStrings, strPrefix)
   for i = LBound(arrStrings) to UBound(arrStrings)
      Print strPrefix & "arrStrings(" & i & ") = '" & arrStrings(i) & "'"
   next
end sub


''
' Returns an Array() statement string
function ArrayToString(arrStrings)
   dim strRet, i
   strRet = "Array("
   for i = LBound(arrStrings) to UBound(arrStrings)
      if i <> LBound(arrStrings) then strRet = strRet & ", "
      strRet = strRet & """" & arrStrings(i) & """"
   next
   ArrayToString = strRet & ")"
end function


''
' Joins the elements of an array into a string using the given item separator.
' @remark this is the same as Join() really.
function ArrayJoinString(arrStrings, strSep)
   if ArraySize(arrStrings) = 0 then
      ArrayJoinString = ""
   else
      dim i
      ArrayJoinString = "" & arrStrings(LBound(arrStrings))
      for i = LBound(arrStrings) + 1 to UBound(arrStrings)
         ArrayJoinString = ArrayJoinString & strSep & arrStrings(i)
      next
   end if
end function


''
' Returns the input array with the string appended.
' @note This works by reference
function ArrayAppend(ByRef arr, str)
   dim i
   redim preserve arr(UBound(arr) + 1)
   arr(UBound(arr)) = str
   ArrayAppend = arr
end function


''
' Returns the input array with the string prepended.
' @note This works by reference
function ArrayPrepend(ByRef arr, str)
   dim i
   redim preserve arr(UBound(arr) + 1)
   for i = UBound(arr) to (LBound(arr) + 1) step -1
      arr(i) = arr(i - 1)
   next
   arr(LBound(arr)) = str
   ArrayPrepend = arr
end function


''
' Returns the input array with the string prepended.
' @note This works by reference
function ArrayRemove(ByRef arr, idx)
   dim i
   for i = idx to (UBound(arr) - 1)
      arr(i) = arr(i + 1)
   next
   redim preserve arr(UBound(arr) - 1)
   ArrayRemove = arr
end function


''
' Checks if the array contains the given string (case sensitive).
function ArrayContainsString(ByRef arr, str)
   dim strCur
   ArrayContainsString = False
   for each strCur in arr
      if StrComp(strCur, str) = 0 then
         ArrayContainsString = True
         exit function
      end if
   next
end function


''
' Checks if the array contains the given string, using case insensitive compare.
function ArrayContainsStringI(ByRef arr, str)
   dim strCur
   ArrayContainsStringI = False
   for each strCur in arr
      if StrComp(strCur, str, vbTextCompare) = 0 then
         ArrayContainsStringI = True
         exit function
      end if
   next
end function


''
' Returns the index of the first occurance of the given string; -1 if not found.
function ArrayFindString(ByRef arr, str)
   dim i
   for i = LBound(arr) to UBound(arr)
      if StrComp(arr(i), str, vbBinaryCompare) = 0 then
         ArrayFindString = i
         exit function
      end if
   next
   ArrayFindString = LBound(arr) - 1
end function


''
' Returns the index of the first occurance of the given string, -1 if not found,
' case insensitive edition.
function ArrayFindStringI(ByRef arr, str)
   dim i
   for i = LBound(arr) to UBound(arr)
      if StrComp(arr(i), str, vbTextCompare) = 0 then
         ArrayFindStringI = i
         exit function
      end if
   next
   ArrayFindStringI = LBound(arr) - 1
end function


''
' Returns the number of entries in an array.
function ArraySize(ByRef arr)
   if (UBound(arr) >= 0) then
      ArraySize = UBound(arr) - LBound(arr) + 1
   else
      ArraySize = 0
   end if
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Registry                                                                                                             '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'' The registry globals
dim g_objReg, g_objRegCtx
dim g_blnRegistry
g_blnRegistry = false


''
' Init the register provider globals.
function RegInit()
   RegInit = false
   On Error Resume Next
   if g_blnRegistry = false then
      set g_objRegCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
      ' Comment out the following for lines if the cause trouble on your windows version.
      if IsWow64() then
         g_objRegCtx.Add "__ProviderArchitecture", 64
         g_objRegCtx.Add "__RequiredArchitecture", true
         LogPrint "RegInit: WoW64"
      end if
      set objLocator = CreateObject("Wbemscripting.SWbemLocator")
      set objServices = objLocator.ConnectServer("", "root\default", "", "", , , , g_objRegCtx)
      set g_objReg = objServices.Get("StdRegProv")
      g_blnRegistry = true
   end if
   RegInit = true
end function


''
' Translates a register root name to a value
' This will translate HKCU path to HKEY_USERS and fixing
function RegTransRoot(strRoot, ByRef sSubKeyName)
   const HKEY_LOCAL_MACHINE = &H80000002
   const HKEY_CURRENT_USER  = &H80000001
   const HKEY_USERS         = &H80000003

   select case strRoot
      case "HKLM"
         RegTransRoot = HKEY_LOCAL_MACHINE
      case "HKUS"
         RegTransRoot = HKEY_USERS
      case "HKCU"
         dim strCurrentSid
         strCurrentSid = GetSid()
         if strCurrentSid <> "" then
            sSubKeyName  = strCurrentSid & "\" & sSubKeyName
            RegTransRoot = HKEY_USERS
            'LogPrint "RegTransRoot: HKCU -> HKEY_USERS + " & sSubKeyName
         else
            RegTransRoot = HKEY_CURRENT_USER
            LogPrint "RegTransRoot: Warning! HKCU -> HKEY_USERS failed!"
         end if
      case else
         MsgFatal "RegTransRoot: Unknown root: '" & strRoot & "'"
         RegTransRoot = 0
   end select
end function


''
' Gets a value from the registry. Returns "" if string wasn't found / valid.
function RegGetString(strName)
   RegGetString = ""
   if RegInit() then
      dim strRoot, strKey, strValue

      ' split up into root, key and value parts.
      strRoot = left(strName, instr(strName, "\") - 1)
      strKey = mid(strName, instr(strName, "\") + 1, instrrev(strName, "\") - instr(strName, "\"))
      strValue = mid(strName, instrrev(strName, "\") + 1)

      ' Must use ExecMethod to call the GetStringValue method because of the context.
      Set InParms = g_objReg.Methods_("GetStringValue").Inparameters
      InParms.hDefKey     = RegTransRoot(strRoot, strKey)
      InParms.sSubKeyName = strKey
      InParms.sValueName  = strValue
      On Error Resume Next
      set OutParms = g_objReg.ExecMethod_("GetStringValue", InParms, , g_objRegCtx)
      if OutParms.ReturnValue = 0 then
         if not IsNull(OutParms.sValue) then
            RegGetString = OutParms.sValue
         end if
      end if
   else
      ' fallback mode
      On Error Resume Next
      RegGetString = g_objShell.RegRead(strName)
   end if
end function


''
' Gets a multi string value from the registry. Returns array of strings if found, otherwise empty array().
function RegGetMultiString(strName)
   RegGetMultiString = Array()
   if RegInit() then
      dim strRoot, strKey, strValue

      ' split up into root, key and value parts.
      strRoot = left(strName, instr(strName, "\") - 1)
      strKey = mid(strName, instr(strName, "\") + 1, instrrev(strName, "\") - instr(strName, "\"))
      strValue = mid(strName, instrrev(strName, "\") + 1)

      ' Must use ExecMethod to call the GetStringValue method because of the context.
      Set InParms = g_objReg.Methods_("GetMultiStringValue").Inparameters
      InParms.hDefKey     = RegTransRoot(strRoot, strKey)
      InParms.sSubKeyName = strKey
      InParms.sValueName  = strValue
      On Error Resume Next
      set OutParms = g_objReg.ExecMethod_("GetMultiStringValue", InParms, , g_objRegCtx)
      if OutParms.ReturnValue = 0 then
         if OutParms.sValue <> Null then
            RegGetMultiString = OutParms.sValue
         end if
      end if
   else
      ' fallback mode
      On Error Resume Next
      RegGetMultiString = g_objShell.RegRead(strName)
   end if
end function


''
' Returns an array of subkey strings.
function RegEnumSubKeys(strRoot, ByVal strKeyPath)
   RegEnumSubKeys = Array()
   if RegInit() then
      ' Must use ExecMethod to call the EnumKey method because of the context.
      Set InParms = g_objReg.Methods_("EnumKey").Inparameters
      InParms.hDefKey     = RegTransRoot(strRoot, strKeyPath)
      InParms.sSubKeyName = strKeyPath
      On Error Resume Next
      set OutParms = g_objReg.ExecMethod_("EnumKey", InParms, , g_objRegCtx)
      'LogPrint "RegEnumSubKeys(" & Hex(InParms.hDefKey) & "," & InParms.sSubKeyName &") -> " & OutParms.GetText_(1)
      if OutParms.ReturnValue = 0 then
         if OutParms.sNames <> Null then
            RegEnumSubKeys = OutParms.sNames
         end if
      end if
   else
      ' fallback mode
      dim objReg, rc, arrSubKeys
      set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
      On Error Resume Next
      rc = objReg.EnumKey(RegTransRoot(strRoot, strKeyPath), strKeyPath, arrSubKeys)
      if rc = 0 then
         RegEnumSubKeys = arrSubKeys
      end if
   end if
end function


''
' Returns an array of full path subkey strings.
function RegEnumSubKeysFull(strRoot, strKeyPath)
   dim arrTmp
   arrTmp = RegEnumSubKeys(strRoot, strKeyPath)
   for i = LBound(arrTmp) to UBound(arrTmp)
      arrTmp(i) = strKeyPath & "\" & arrTmp(i)
   next
   RegEnumSubKeysFull = arrTmp
end function


''
' Returns an rsorted array of subkey strings.
function RegEnumSubKeysRVerSorted(strRoot, strKeyPath)
   RegEnumSubKeysRVerSorted = ArrayRVerSortStrings(RegEnumSubKeys(strRoot, strKeyPath))
end function


''
' Returns an rsorted array of subkey strings.
function RegEnumSubKeysFullRVerSorted(strRoot, strKeyPath)
   RegEnumSubKeysFullRVerSorted = ArrayRVerSortStrings(RegEnumSubKeysFull(strRoot, strKeyPath))
end function


''
' Returns an array of value name strings.
function RegEnumValueNames(strRoot, ByVal strKeyPath)
   RegEnumValueNames = Array()
   if RegInit() then
      ' Must use ExecMethod to call the EnumKey method because of the context.
      Set InParms = g_objReg.Methods_("EnumValues").Inparameters
      InParms.hDefKey     = RegTransRoot(strRoot, strKeyPath)
      InParms.sSubKeyName = strKeyPath
      On Error Resume Next
      set OutParms = g_objReg.ExecMethod_("EnumValues", InParms, , g_objRegCtx)
      'LogPrint "RegEnumValueNames(" & Hex(InParms.hDefKey) & "," & InParms.sSubKeyName &") -> " & OutParms.GetText_(1)
      if OutParms.ReturnValue = 0 then
         if OutParms.sNames <> Null then
            RegEnumValueNames = OutParms.sNames
         end if
      end if
   else
      ' fallback mode
      dim objReg, rc, arrSubKeys
      set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
      On Error Resume Next
      rc = objReg.EnumValues(RegTransRoot(strRoot, strKeyPath), strKeyPath, arrSubKeys)
      if rc = 0 then
         RegEnumValueNames = arrSubKeys
      end if
   end if
end function


''
' Returns an array of full path value name strings.
function RegEnumValueNamesFull(strRoot, strKeyPath)
   dim arrTmp
   arrTmp = RegEnumValueNames(strRoot, strKeyPath)
   for i = LBound(arrTmp) to UBound(arrTmp)
      arrTmp(i) = strKeyPath & "\" & arrTmp(i)
   next
   RegEnumValueNamesFull = arrTmp
end function


''
' Extract relevant paths from program links using a callback function.
'
' Enumerates start menu program links from "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\UFH\SHC"
' and similar, using the given callback to examine each and return a path if relevant.  The relevant
' paths are returned in reverse sorted order.
'
' The callback prototype is as follows fnCallback(ByRef arrStrings, cStrings, ByRef objUser).
' Any non-empty return strings are collected, reverse sorted uniquely and returned.
'
function CollectFromProgramItemLinks(ByRef fnCallback, ByRef objUser)
   dim arrValues, strValue, arrStrings, str, arrCandidates, iCandidates, cStrings
   CollectFromProgramItemLinks = Array()

   arrValues = RegEnumValueNamesFull("HKCU", "SOFTWARE\Microsoft\Windows\CurrentVersion\UFH\SHC")
   redim arrCandidates(UBound(arrValues) - LBound(arrValues) + 1)
   iCandidates = 0
   for each strValue in arrValues
      arrStrings = RegGetMultiString("HKCU\" & strValue)
      if UBound(arrStrings) >= 0 then
         cStrings = UBound(arrStrings) + 1 - LBound(arrStrings)
         str = fnCallback(arrStrings, cStrings, objUser)
         if str <> "" then
            if not ArrayContainsStringI(arrCandidates, str) then
               arrCandidates(iCandidates) = str
               iCandidates = iCandidates + 1
            end if
         end if
      end if
   next
   if iCandidates > 0 then
      redim preserve arrCandidates(iCandidates - 1)
      arrCandidates = ArrayRVerSortStrings(arrCandidates)
      for iCandidates = LBound(arrCandidates) to UBound(arrCandidates)
         LogPrint "CollectFromProgramItemLinks: #" & iCandidates & ": " & arrCandidates(iCandidates)
      next
      CollectFromProgramItemLinks = arrCandidates
   end if
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Messaging and Output                                                                                                 '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Append text to the log file and echo it to stdout
sub Print(str)
   LogPrint str
   Wscript.Echo str
end sub


''
' Prints a test header
sub PrintHdr(strTest)
   LogPrint "***** Checking for " & strTest & " *****"
   Wscript.Echo "Checking for " & StrTest & "..."
end sub


''
' Prints a success message
sub PrintResultMsg(strTest, strResult)
   dim cchPad
   LogPrint "** " & strTest & ": " & strResult
   Wscript.Echo " Found " & RightPad(strTest & ": ", 22) & strPad & strResult
end sub


''
' Prints a successfully detected path
sub PrintResult(strTest, strPath)
   strLongPath = PathAbsLong(strPath)
   if PathAbs(strPath) <> strLongPath then
      LogPrint         "** " & strTest & ": " & strPath & " (" & UnixSlashes(strLongPath) & ")"
      Wscript.Echo " Found " & RightPad(strTest & ": ", 22) & strPath & " (" & UnixSlashes(strLongPath) & ")"
   else
      LogPrint         "** " & strTest & ": " & strPath
      Wscript.Echo " Found " & RightPad(strTest & ": ", 22) & strPath
   end if
end sub


''
' Info message.
sub MsgInfo(strMsg)
   Print "info: " & strMsg
end sub


''
' Warning message.
sub MsgWarning(strMsg)
   Print "warning: " & strMsg
end sub


''
' Fatal error.
sub MsgFatal(strMsg)
   Print "fatal error: " & strMsg
   Wscript.Quit(1)
end sub


''
' Error message, fatal unless flag to ignore errors is given.
sub MsgError(strMsg)
   Print "error: " & strMsg
   if g_blnContinueOnError = False then
      Wscript.Quit(1)
   end if
   g_rcScript = 1
end sub

''
' Error message, fatal unless flag to ignore errors is given.
' @note does not return
sub MsgSyntaxError(strMsg)
   Print "syntax error: " & strMsg
   Wscript.Quit(2)
end sub


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Helpers: Misc                                                                                                                 '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Translate a kBuild / VBox architecture name to a windows one.
function XlateArchitectureToWin(strArch)
   strArch = LCase(strArch)
   XlateArchitectureToWin = strArch
   if strArch = "amd64" then XlateArchitectureToWin = "x64"
end function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'  Testcases                                                                                                                     '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''
' Self test for some of the above routines.
'
sub SelfTest
   dim i, str
   str = "0123456789"
   for i = 1 to Len(str)
      if CharIsDigit(Mid(str, i, 1)) <> True then MsgFatal "SelfTest failed: CharIsDigit("&Mid(str, i, 1)&")"
   next
   str = "abcdefghijklmnopqrstuvwxyz~`!@#$%^&*()_+-=ABCDEFGHIJKLMNOPQRSTUVWXYZ/\[]{}"
   for i = 1 to Len(str)
      if CharIsDigit(Mid(str, i, 1)) <> False then MsgFatal "SelfTest failed: CharIsDigit("&Mid(str, i, 1)&")"
   next

   if StrVersionCompare("1234", "1234") <> 0 then MsgFatal "SelfTest failed: StrVersionCompare #1"
   if StrVersionCompare("1", "1") <> 0 then MsgFatal "SelfTest failed: StrVersionCompare #2"
   if StrVersionCompare("2", "1") <= 0 then MsgFatal "SelfTest failed: StrVersionCompare #3"
   if StrVersionCompare("1", "2") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #4"
   if StrVersionCompare("01", "1") <> 0 then MsgFatal "SelfTest failed: StrVersionCompare #5"
   if StrVersionCompare("01", "001") <> 0 then MsgFatal "SelfTest failed: StrVersionCompare #6"
   if StrVersionCompare("12", "123") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #7"
   if StrVersionCompare("v123", "123") <= 0 then MsgFatal "SelfTest failed: StrVersionCompare #8"
   if StrVersionCompare("v1.2.3", "v1.3.4") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #9"
   if StrVersionCompare("v1.02.3", "v1.3.4") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #10"
   if StrVersionCompare("v1.2.3", "v1.03.4") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #11"
   if StrVersionCompare("v1.2.4", "v1.23.4") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #12"
   if StrVersionCompare("v10.0.17163", "v10.00.18363") >= 0 then MsgFatal "SelfTest failed: StrVersionCompare #13"
   if StrVersionCompare("n 2.15.0", "2.12.0") <= 0 then MsgFatal "SelfTest failed: StrVersionCompare #14"

   if StrGetFirstWord("1") <> "1" then MsgFatal "SelfTest: StrGetFirstWord #1"
   if StrGetFirstWord(" 1 ") <> "1" then MsgFatal "SelfTest: StrGetFirstWord #2"
   if StrGetFirstWord(" 1  2 ") <> "1" then MsgFatal "SelfTest: StrGetFirstWord #3"
   if StrGetFirstWord("1 2") <> "1" then MsgFatal "SelfTest: StrGetFirstWord #4"
   if StrGetFirstWord("1234 5") <> "1234" then MsgFatal "SelfTest: StrGetFirstWord #5"
   if StrGetFirstWord("  ") <> "" then MsgFatal "SelfTest: StrGetFirstWord #6"

   dim arr
   arr = ArrayAppend(Array("0", "1"), "2")
   if ArraySize(arr) <> 3 then MsgFatal "SelfTest: Array #1: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""0"", ""1"", ""2"")" then MsgFatal "SelfTest: Array #1: " & ArrayToString(arr)

   arr = ArrayPrepend(arr, "-1")
   if ArraySize(arr) <> 4 then MsgFatal "SelfTest: Array #2: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""-1"", ""0"", ""1"", ""2"")" then MsgFatal "SelfTest: Array #2: " & ArrayToString(arr)

   ArrayPrepend arr, "-2"
   if ArraySize(arr) <> 5 then MsgFatal "SelfTest: Array #3: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""-2"", ""-1"", ""0"", ""1"", ""2"")" then MsgFatal "SelfTest: Array #3: " & ArrayToString(arr)

   ArrayRemove arr, 1
   if ArraySize(arr) <> 4 then MsgFatal "SelfTest: Array #4: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""-2"", ""0"", ""1"", ""2"")" then MsgFatal "SelfTest: Array #4: " & ArrayToString(arr)

   arr = ArrayRemove(arr, 2)
   if ArraySize(arr) <> 3 then MsgFatal "SelfTest: Array #5: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""-2"", ""0"", ""2"")" then MsgFatal "SelfTest: Array #5: " & ArrayToString(arr)

   arr = ArrayPrepend(arr, "42")
   arr = ArrayAppend(arr, "-42")
   if ArraySize(arr) <> 5 then MsgFatal "SelfTest: Array #6: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""42"", ""-2"", ""0"", ""2"", ""-42"")" then MsgFatal "SelfTest: Array #6: " & ArrayToString(arr)

   arr = ArraySortStrings(arr)
   if ArraySize(arr) <> 5 then MsgFatal "SelfTest: Array #7: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""-2"", ""-42"", ""0"", ""2"", ""42"")" then MsgFatal "SelfTest: Array #7: " & ArrayToString(arr)

   arr = ArrayRSortStrings(arr)
   if ArraySize(arr) <> 5 then MsgFatal "SelfTest: Array #7: size:" & ArraySize(arr)
   if ArrayToString(arr) <> "Array(""42"", ""2"", ""0"", ""-42"", ""-2"")" then MsgFatal "SelfTest: Array #8: " & ArrayToString(arr)

   arr = ArrayVerSortStrings(Array("v10", "v1", "v0"))
   if ArrayToString(arr) <> "Array(""v0"", ""v1"", ""v10"")" then MsgFatal "SelfTest: Array #9: " & ArrayToString(arr)

   arr = ArrayRVerSortStrings(arr)
   if ArrayToString(arr) <> "Array(""v10"", ""v1"", ""v0"")" then MsgFatal "SelfTest: Array #10: " & ArrayToString(arr)

   if ArrayJoinString(arr, ":") <> "v10:v1:v0" then MsgFatal "SelfTest: Array #11: " & ArrayJoinString(arr, ":")

   if PathMatch("c:\", "C:\") <> true then MsgFatal "SelfTest: PathMatch #1"
   if PathMatch("c:\\\winDows/sysTem32", "C:\WindowS\.\\.\System32\.") <> true then MsgFatal "SelfTest: PathMatch #2"
   if PathMatch("c:\\\winDows/sysTem32", "C:\WindowS\.\\..\System32\.") <> false then MsgFatal "SelfTest: PathMatch #3"
   if PathMatch("\\x\", "\\\x\") <> false then MsgFatal "SelfTest: PathMatch #4"
   if PathMatch("\\x\", "\\x\") <> true then MsgFatal "SelfTest: PathMatch #5"
   if PathMatch("\\", "\\") <> true then MsgFatal "SelfTest: PathMatch #6"
   if PathMatch("\\x", "\\x") <> true then MsgFatal "SelfTest: PathMatch #7"

end sub

'
' Run the self tests if we're executed directly.
'
if StrEndsWithI(Wscript.ScriptFullName, "\tools\win\vbscript\helpers.vbs") then
   Wscript.echo "helpers.vbs: Running self test..."
   SelfTest
   Wscript.echo "helpers.vbs: Self test complete."
end if