aboutsummaryrefslogtreecommitdiff
path: root/bbot/worker/worker.cxx
blob: 5a4d24068ec8b628edde83411e9d47a38baa5ebd (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
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
// file      : bbot/worker.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#ifndef _WIN32
#  include <signal.h> // signal()
#else
#  include <libbutl/win32-utility.hxx> // SetErrorMode(), Sleep()
#endif

#include <map>
#include <regex>
#include <cstring>   // strchr(), strncmp()
#include <sstream>
#include <iostream>
#include <system_error> // generic_category()

#include <libbutl/b.hxx>
#include <libbutl/pager.hxx>
#include <libbutl/prompt.hxx>
#include <libbutl/utility.hxx>              // to_utf8(), eof()
#include <libbutl/timestamp.hxx>
#include <libbutl/filesystem.hxx>
#include <libbutl/string-parser.hxx>
#include <libbutl/manifest-serializer.hxx>

#include <libbutl/json/parser.hxx>

#include <libbbot/manifest.hxx>

#include <bbot/types.hxx>
#include <bbot/utility.hxx>

#include <bbot/diagnostics.hxx>
#include <bbot/bootstrap-manifest.hxx>

#include <bbot/worker/worker-options.hxx>

using namespace butl;
using namespace bbot;

using std::cout;
using std::endl;

namespace bbot
{
  int
  main (int argc, char* argv[]);

  static int
  build (size_t argc, const char* argv[]);

  process_path argv0;
  worker_options ops;

  dir_path env_dir;

  // Note that upload can be quite large and take a while to upload under high
  // load.
  //
  const size_t tftp_blksize     (1468); // Between 512 (default) and 65464.
  const size_t tftp_put_timeout (3600); // 1 hour (also the default).
  const size_t tftp_get_timeout (10);   // 10 seconds.
  const size_t tftp_get_retries (3);    // Task request retries (see startup()).

  const dir_path bpkg_dir   (".bpkg");
  const dir_path repos_dir  (dir_path (bpkg_dir) /= "repos");
  const dir_path host_dir   (dir_path (bpkg_dir) /= "host");
  const dir_path build2_dir (dir_path (bpkg_dir) /= "build2");
}

static bool
exists (const dir_path& d)
try
{
  return dir_exists (d);
}
catch (const system_error& e)
{
  fail << "unable to stat path " << d << ": " << e << endf;
}

static bool
exists (const path& f)
try
{
  return file_exists (f, true /* follow_symlinks */);
}
catch (const system_error& e)
{
  fail << "unable to stat path " << f << ": " << e << endf;
}

static dir_path
current_directory ()
try
{
  return dir_path::current_directory ();
}
catch (const system_error& e)
{
  fail << "unable to obtain current directory: " << e << endf;
}

static void
#ifndef _WIN32
mk_p (tracer& t, string* log, const dir_path& d, bool sudo = false)
{
  if (sudo)
  {
    if (log != nullptr)
      *log += "sudo mkdir -p " + d.representation () + '\n';

    run_io (t, 0, 1, 2, "sudo", "mkdir", "-p", d);
  }
  else
#else
mk_p (tracer& t, string* log, const dir_path& d, bool = false)
{
#endif
  try
  {
    if (verb >= 3)
      t << "mkdir -p " << d;

    if (log != nullptr)
      *log += "mkdir -p " + d.representation () + '\n';

    try_mkdir_p (d);
  }
  catch (const system_error& e)
  {
    fail << "unable to create directory " << d << ": " << e << endf;
  }
}

static void
mk (tracer& t, string* log, const dir_path& d)
try
{
  if (verb >= 3)
    t << "mkdir " << d;

  if (log != nullptr)
    *log += "mkdir " + d.representation () + '\n';

  try_mkdir (d);
}
catch (const system_error& e)
{
  fail << "unable to create directory " << d << ": " << e << endf;
}

static bool
empty (const dir_path& d)
try
{
  return dir_empty (d);
}
catch (const system_error& e)
{
  fail << "unable to scan directory " << d << ": " << e << endf;
}

static void
cp_into (tracer& t, string* log, const path& p, const dir_path& d)
try
{
  if (verb >= 3)
    t << "cp " << p << ' ' << d;

  if (log != nullptr)
    *log += "cp " + p.string () + ' ' + d.representation () + '\n';

  cpfile_into (p, d);
}
catch (const system_error& e)
{
  fail << "unable to copy file " << p << " into " << d <<  ": " << e << endf;
}

static void
mv (tracer& t, string* log, const dir_path& from, const dir_path& to)
try
{
  if (verb >= 3)
    t << "mv " << from << ' ' << to;

  if (log != nullptr)
    *log += "mv " + from.representation () + ' ' + to.representation () +
            "\n";

  mvdir (from, to);
}
catch (const system_error& e)
{
  fail << "unable to move directory '" << from << "' to '" << to << "': " << e
       << endf;
}

static void
mv_into (tracer& t, string* log, const path& from, const dir_path& into)
try
{
  if (verb >= 3)
    t << "mv " << from << ' ' << into;

  if (log != nullptr)
    *log += "mv " + from.representation () + ' ' + into.representation () +
            "\n";

  mventry_into (from, into);
}
catch (const system_error& e)
{
  fail << "unable to move entry '" << from << "' into '" << into << "': " << e
       << endf;
}

static void
rm_r (tracer& t, string* log, const dir_path& d)
try
{
  if (verb >= 3)
    t << "rm -r " << d;

  if (log != nullptr)
    *log += "rm -r " + d.representation () + '\n';

  rmdir_r (d);
}
catch (const system_error& e)
{
  fail << "unable to remove directory " << d << ": " << e << endf;
}

static dir_path
change_wd (tracer& t, string* log, const dir_path& d, bool create = false)
try
{
  if (create)
    mk_p (t, log, d);

  dir_path r (current_directory ());

  if (verb >= 3)
    t << "cd " << d;

  if (log != nullptr)
    *log += "cd " + d.representation () + '\n';

  dir_path::current_directory (d);
  return r;
}
catch (const system_error& e)
{
  fail << "unable to change current directory to " << d << ": " << e << endf;
}

// Step IDs.
//
// NOTE: keep ids ordered according to the sequence of steps and remember to
//       update unreachable breakpoint checks if changing anything here.
//
enum class step_id
{
  // Common fallbacks for bpkg_*_create/b_test_installed_create and
  // bpkg_*_configure_build/b_test_installed_configure, respectively. Note:
  // not breakpoints.
  //
  b_create,
  b_configure,

  // Note that bpkg_module_* options are only used if the main package is a
  // build system module (using just ~build2 otherwise). They also have no
  // fallback (build system modules are just too different to try to handle
  // them together with target and host; e.g., install root). However,
  // bpkg_module_create is complemented with arguments from un-prefixed step
  // ids, the same way as other *.create[_for_*] steps (note that un-prefixed
  // steps are not fallbacks, they are always added first).
  //
  bpkg_create,         // Breakpoint and base.
  bpkg_target_create,  //: b_create, bpkg_create
  bpkg_host_create,    //: b_create, bpkg_create
  bpkg_module_create,  //: no fallback

  bpkg_link,

  bpkg_configure_add,
  bpkg_configure_fetch,

  // Global (as opposed to package-specific) bpkg-pkg-build options (applies
  // to all *_configure_build* steps). Note: not a breakpoint.
  //
  bpkg_global_configure_build,

  // Note that bpkg_configure_build serves as a breakpoint for the
  // bpkg-pkg-build call that configures (at once) the main package and all
  // its external tests.
  //
  bpkg_configure_build,         // Breakpoint and base.
  bpkg_target_configure_build,  //: b_configure, bpkg_configure_build
  bpkg_host_configure_build,    //: b_configure, bpkg_configure_build
  bpkg_module_configure_build,  //: b_configure, bpkg_configure_build

  bpkg_update,
  bpkg_test,

  // Note that separate test packages are configured as part of the
  // bpkg_configure_build step above with options taken from
  // bpkg_{target,host}_configure_build, depending on tests package type.
  //
  bpkg_test_separate_update, //: bpkg_update
  bpkg_test_separate_test,   //: bpkg_test

  // Note that we only perform the installation tests if this is a target
  // package or a self-hosted configuration. Also note that this step is
  // considered disabled if any of the bpkg_bindist_* steps is explicitly
  // enabled.
  //
  bpkg_install,

  bbot_install_ldconfig, // Note: disabled by default.

  // Note that the bpkg_bindist_* steps are mutually exclusive and the latest
  // status change for them (via the leading +/- characters in the prefix)
  // overrides all the previous ones. Disabled by default.
  //
  bpkg_bindist_debian,
  bpkg_bindist_fedora,
  bpkg_bindist_archive,

  // Note that this step is considered disabled unless one of the
  // bpkg_bindist_* steps is explicitly enabled. Note: not a breakpoint.
  //
  bbot_sys_install,

  bbot_sys_install_apt_get_update,
  bbot_sys_install_apt_get_install,
  bbot_sys_install_dnf_install,
  bbot_sys_install_tar_extract,

  bbot_sys_install_ldconfig, // Note: disabled by default.

  // Note: skipped for modules.
  //
  b_test_installed_create,    //: b_create
  b_test_installed_configure, //: b_configure
  b_test_installed_test,

  // Note that for a host package this can involve both run-time and build-
  // time tests (which means we may also need a shared configuration for
  // modules).
  //
  // The *_for_{target,host,module} denote main package type, not
  // configuration being created, which will always be target (more precisely,
  // target or host, but host only in a self-hosted case, which means it's
  // the same as target).
  //
  // Note that if this is a non-self-hosted configuration, we can only end up
  // here if building target package and so can just use *_create and *_build
  // values in buildtabs.
  //
  bpkg_test_separate_installed_create,            // Breakpoint and base.
  bpkg_test_separate_installed_create_for_target, //: bpkg_test_separate_installed_create
  bpkg_test_separate_installed_create_for_host,   //: bpkg_test_separate_installed_create
  bpkg_test_separate_installed_create_for_module, //: no fallback

  bpkg_test_separate_installed_link,            //  breakpoint only
  bpkg_test_separate_installed_configure_add,   //: bpkg_configure_add
  bpkg_test_separate_installed_configure_fetch, //: bpkg_configure_fetch

  bpkg_test_separate_installed_configure_build,            // Breakpoint and base.
  bpkg_test_separate_installed_configure_build_for_target, //: bpkg_test_separate_installed_configure_build
  bpkg_test_separate_installed_configure_build_for_host,   //: bpkg_test_separate_installed_configure_build
  bpkg_test_separate_installed_configure_build_for_module, //: bpkg_test_separate_installed_configure_build

  bpkg_test_separate_installed_update,          //: bpkg_update
  bpkg_test_separate_installed_test,            //: bpkg_test

  bbot_sys_uninstall_apt_get_remove,
  bbot_sys_uninstall_dnf_remove,

  bpkg_uninstall,

  bbot_bindist_upload, // Note: disabled by default, not a breakpoint.

  // Note that this step is considered disabled unless the upload/ directory
  // is not empty. Note: not a breakpoint.
  //
  bbot_upload,

  bbot_upload_tar_create,
  bbot_upload_tar_list,

  end
};

static const strings step_id_str {
  "b.create",
  "b.configure",

  "bpkg.create",
  "bpkg.target.create",
  "bpkg.host.create",
  "bpkg.module.create",

  "bpkg.link",

  "bpkg.configure.add",
  "bpkg.configure.fetch",

  "bpkg.global.configure.build",

  "bpkg.configure.build",
  "bpkg.target.configure.build",
  "bpkg.host.configure.build",
  "bpkg.module.configure.build",

  "bpkg.update",
  "bpkg.test",

  "bpkg.test-separate.update",
  "bpkg.test-separate.test",

  "bpkg.install",
  "bbot.install.ldconfig",

  "bpkg.bindist.debian",
  "bpkg.bindist.fedora",
  "bpkg.bindist.archive",

  "bbot.sys-install",
  "bbot.sys-install.apt-get.update",
  "bbot.sys-install.apt-get.install",
  "bbot.sys-install.dnf.install",
  "bbot.sys-install.tar.extract",
  "bbot.sys-install.ldconfig",

  "b.test-installed.create",
  "b.test-installed.configure",
  "b.test-installed.test",

  "bpkg.test-separate-installed.create",
  "bpkg.test-separate-installed.create_for_target",
  "bpkg.test-separate-installed.create_for_host",
  "bpkg.test-separate-installed.create_for_module",

  "bpkg.test-separate-installed.link",
  "bpkg.test-separate-installed.configure.add",
  "bpkg.test-separate-installed.configure.fetch",

  "bpkg.test-separate-installed.configure.build",
  "bpkg.test-separate-installed.configure.build_for_target",
  "bpkg.test-separate-installed.configure.build_for_host",
  "bpkg.test-separate-installed.configure.build_for_module",

  "bpkg.test-separate-installed.update",
  "bpkg.test-separate-installed.test",

  "bbot.sys-uninstall.apt-get.remove",
  "bbot.sys-uninstall.dnf.remove",

  "bpkg.uninstall",

  "bbot.bindist.upload",

  "bbot.upload",
  "bbot.upload.tar.create",
  "bbot.upload.tar.list",

  "end"};

static inline const string&
to_string (step_id s)
{
  return step_id_str[static_cast<size_t> (s)];
}

using std::regex;
namespace regex_constants = std::regex_constants;
using regexes = vector<regex>;

// UTF-8-sanitize and log the line. Also print it to a tracer, if specified,
// or to stderr otherwise at verbosity level 3 or higher.
//
static void
log_line (string&& l, string& log, tracer* trace = nullptr)
{
  if (verb >= 3)
  {
    if (trace != nullptr)
      *trace << l;
    else
      text << l;
  }

  to_utf8 (l, '?', codepoint_types::graphic, U"\n\r\t");

  log += l;
  log += '\n';
}

#ifndef _WIN32
const char* comment_begin ("#");
#else
const char* comment_begin ("rem");
#endif

static void
log_step_id (tracer& t, string& log, step_id id)
{
  string ts (to_string (system_clock::now (),
                        "%Y-%m-%d %H:%M:%S %Z",
                        true /* special */,
                        true /* local */));

  const string& sid (to_string (id));

  l3 ([&]{t << "step id: " << sid << ' ' << ts;});

  log += comment_begin;
  log += " step id: ";
  log += sid;
  log += ' ';
  log += ts;
  log += '\n';
}

// Add the specified string to the log as a comment. Unless the string is
// empty (e.g., a blank line to separate comments), also trace it.
//
static void
log_comment (tracer& t, string& log, const string& s)
{
  if (!s.empty ())
    l3 ([&]{t << s;});

  log += comment_begin;

  if (!s.empty ())
  {
    log += ' ';
    log += s;
  }

  log += '\n';
}

// Run the worker script command. Name is used for logging and diagnostics
// only. Match lines read from the command's stderr against the regular
// expressions and return the warning result status (instead of success) in
// case of a match. Save the executed command into last_cmd.
//
// Redirect stdout to stderr if the out_* arguments are not specified (out_str
// is NULL and out_file is empty; must never be specified both). Otherwise,
// save the process output into the variable referenced by out_str, if
// specified, and to the file referenced by out_file otherwise. Note: in the
// former case assumes that the output will always fit into the pipe buffer.
//
// If bkp_step is present and is equal to the command step, then prior to
// running this command ask the user if to continue or abort the task
// execution. If bkp_status is present, then ask for that if the command
// execution results with the specified or more critical status.
//
// For the special end step no command is executed. In this case only the user
// is potentially prompted and the step is traced/logged.
//
// If specified, the pre-run callback is called after the step id is logged
// but before the command is logged/executed.
//
using pre_run_function = void ();

template <typename... A>
static result_status
run_cmd (step_id step,
         tracer& t,
         string& log,
         const function<pre_run_function>& pre_run,
         optional<string>* out_str, const path& out_file,
         const regexes& warn_detect,
         const string& name,
         const optional<step_id>& bkp_step,
         const optional<result_status>& bkp_status,
         const strings& aux_env,
         string& last_cmd,
         const process_env& pe,
         A&&... a)
{
  assert (out_str == nullptr || out_file.empty ());

  string next_cmd;

  // Prompt the user if to continue the task execution and, if they refuse,
  // log this and throw abort.
  //
  struct abort {};

  auto prompt = [&aux_env, &last_cmd, &next_cmd, &t, &log] (const string& what)
  {
    diag_record dr (text);

    dr << '\n'
       << what << '\n'
       << "  current dir:           " << current_directory () << '\n'
       << "  environment:           " << ops.env_script () << ' ' << ops.env_target ();

    if (!aux_env.empty ())
    {
      dr << '\n'
         << "  auxiliary environment:";

      for (const string& e: aux_env)
        dr << '\n'
           << "    " << e;
    }

    if (!last_cmd.empty ())
      dr << '\n'
         << "  last command:          " << last_cmd;

    if (!next_cmd.empty ())
      dr << '\n'
         << "  next command:          " << next_cmd;

    dr.flush ();

    if (!yn_prompt (
          "continue execution (or you may shutdown the machine)? [y/n]"))
    {
      log_line ("execution aborted by interactive user", log, &t);
      throw abort ();
    }
  };

  auto prompt_step = [step, &t, &log, &bkp_step, &prompt, &pre_run] ()
  {
    // Prompt the user if the breakpoint is reached.
    //
    if (bkp_step && *bkp_step == step)
      prompt (to_string (step) + " step reached");

    log_step_id (t, log, step);

    if (pre_run)
      pre_run ();
  };

  try
  {
    // Trace, log, and save the command line.
    //
    auto cmdc = [&t, &log, &next_cmd, &prompt_step]
                (const char* c[], size_t n)
    {
      std::ostringstream os;
      process::print (os, c, n);
      next_cmd = os.str ();

      prompt_step ();

      // Log the command to be executed.
      //
      t (c, n);

      log += next_cmd;
      log += '\n';
    };

    result_status r (result_status::success);

    if (step != step_id::end)
    {
      try
      {
        // Redirect stdout to stderr, if the caller is not interested in it.
        //
        // Text mode seems appropriate.
        //
        fdpipe out_pipe (out_str != nullptr ? fdopen_pipe () : fdpipe ());
        fdpipe err_pipe (fdopen_pipe ());

        // If the output file is specified, then open "half-pipe".
        //
        if (!out_file.empty ())
        try
        {
          out_pipe.out = fdopen (out_file,
                                 fdopen_mode::out | fdopen_mode::create);
        }
        catch (const io_error& e)
        {
          fail << "unable to open " << out_file << ": " << e;
        }

        process pr (
          process_start_callback (
            cmdc,
            fdopen_null (), // Never reads from stdin.
            out_pipe.out != nullfd ? out_pipe.out.get () : 2,
            err_pipe,
            pe,
            forward<A> (a)...));

        out_pipe.out.close ();
        err_pipe.out.close ();

        {
          // Skip on exception.
          //
          ifdstream is (move (err_pipe.in),
                        fdstream_mode::skip,
                        ifdstream::badbit);

          for (string l; !eof (getline (is, l)); )
          {
            // Match the log line with the warning-detecting regular
            // expressions until the first match.
            //
            if (r != result_status::warning)
            {
              // Match flags.
              //
              // Note that by default std::regex_search() matches the empty
              // substrings in non-empty strings for all the major
              // implementations (see the butl::regex_replace_search()
              // function implementation for details). While it's unlikely
              // that the warning regex will match the empty substrings, let's
              // keep it consistent with the other regex_search() call sites.
              //
              regex_constants::match_flag_type mf (
                regex_constants::match_default);

              if (!l.empty ())
                mf |= regex_constants::match_not_null;

              for (const regex& re: warn_detect)
              {
                // Only examine the first 512 bytes. Long lines (e.g., linker
                // command lines) could trigger implementation-specific
                // limitations (like stack overflow). Plus, it is a
                // performance concern.
                //
                if (regex_search (l.begin (),
                                  (l.size () < 512
                                   ? l.end ()
                                   : l.begin () + 512),
                                  re,
                                  mf))
                {
                  r = result_status::warning;
                  break;
                }
              }
            }

            log_line (move (l), log);
          }
        }

        if (!pr.wait ())
        {
          const process_exit& e (*pr.exit);
          log_line (name + ' ' + to_string (e), log, &t);
          r = e.normal () ? result_status::error : result_status::abnormal;
        }

        // Only read the buffered output if the process terminated normally.
        //
        if (out_str != nullptr && pr.exit->normal ())
        {
          // Note: shouldn't throw since the output is buffered.
          //
          ifdstream is (move (out_pipe.in));
          *out_str = is.read_text ();
        }

        last_cmd = move (next_cmd);

        if (bkp_status && r >= *bkp_status)
        {
          next_cmd.clear (); // Note: used by prompt().
          prompt (!r ? "error occured" : "warning is issued");
        }
      }
      catch (const process_error& e)
      {
        fail << "unable to execute " << name << ": " << e;
      }
      catch (const io_error& e)
      {
        fail << "unable to read " << name << " diagnostics: " << e;
      }
    }
    else
    {
      next_cmd.clear (); // Note: used by prompt_step().
      prompt_step ();
    }

    return r;
  }
  catch (const abort&)
  {
    return result_status::abort;
  }
}

template <typename... A>
static result_status
run_cmd (step_id step,
         tracer& t,
         string& log,
         optional<string>* out_str, const path& out_file,
         const regexes& warn_detect,
         const string& name,
         const optional<step_id>& bkp_step,
         const optional<result_status>& bkp_status,
         const strings& aux_env,
         string& last_cmd,
         const process_env& pe,
         A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* pre_run */,
                  out_str, out_file,
                  warn_detect,
                  name,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  pe,
                  forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_bpkg (step_id step,
          const V& envvars,
          tracer& t,
          string& log,
          const function<pre_run_function>& pre_run,
          optional<string>& out,
          const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  pre_run,
                  &out, path () /* out_file */,
                  warn_detect,
                  "bpkg " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("bpkg", envvars),
                  verbosity, cmd, forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_bpkg (step_id step,
          const V& envvars,
          tracer& t,
          string& log, const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file */,
                  warn_detect,
                  "bpkg " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("bpkg", envvars),
                  verbosity, cmd, forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_bpkg (step_id step,
          const V& envvars,
          tracer& t,
          string& log,
          const function<pre_run_function>& pre_run,
          const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  pre_run,
                  nullptr /* out_str */, path () /* out_file */,
                  warn_detect,
                  "bpkg " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("bpkg", envvars),
                  verbosity, cmd, forward<A> (a)...);
}

template <typename... A>
static result_status
run_bpkg (step_id step,
          tracer& t,
          string& log,
          const function<pre_run_function>& pre_run,
          optional<string>& out,
          const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  const char* const* envvars (nullptr);

  return run_bpkg (step,
                   envvars,
                   t,
                   log,
                   pre_run,
                   out,
                   warn_detect,
                   bkp_step, bkp_status, aux_env, last_cmd,
                   verbosity, cmd, forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_bpkg (step_id step,
          const V& envvars,
          tracer& t,
          string& log, const path& out, const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  return run_cmd (step,
                  t,
                  log, nullptr /* out_str */, out, warn_detect,
                  "bpkg " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("bpkg", envvars),
                  verbosity, cmd, forward<A> (a)...);
}

template <typename... A>
static result_status
run_bpkg (step_id step,
          tracer& t,
          string& log, const path& out, const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  const char* const* envvars (nullptr);

  return run_bpkg (step,
                   envvars,
                   t,
                   log, out, warn_detect,
                   bkp_step, bkp_status, aux_env, last_cmd,
                   verbosity, cmd, forward<A> (a)...);
}

template <typename... A>
static result_status
run_bpkg (step_id step,
          tracer& t,
          string& log, const regexes& warn_detect,
          const optional<step_id>& bkp_step,
          const optional<result_status>& bkp_status,
          const strings& aux_env,
          string& last_cmd,
          const char* verbosity,
          const string& cmd, A&&... a)
{
  const char* const* envvars (nullptr);

  return run_bpkg (step,
                   envvars,
                   t,
                   log, warn_detect,
                   bkp_step, bkp_status, aux_env, last_cmd,
                   verbosity, cmd, forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_b (step_id step,
       const V& envvars,
       tracer& t,
       string& log, const regexes& warn_detect,
       const optional<step_id>& bkp_step,
       const optional<result_status>& bkp_status,
       const strings& aux_env,
       string& last_cmd,
       const char* verbosity,
       const strings& buildspecs, A&&... a)
{
  string name ("b");
  for (const string& s: buildspecs)
  {
    if (!name.empty ())
      name += ' ';

    name += s;
  }

  return run_cmd (step,
                  t, log,
                  nullptr /* out_str */, path () /* out_file */,
                  warn_detect,
                  name,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("b", envvars),
                  verbosity, buildspecs, forward<A> (a)...);
}

template <typename V, typename... A>
static result_status
run_b (step_id step,
       const V& envvars,
       tracer& t,
       string& log, const regexes& warn_detect,
       const optional<step_id>& bkp_step,
       const optional<result_status>& bkp_status,
       const strings& aux_env,
       string& last_cmd,
       const char* verbosity,
       const string& buildspec, A&&... a)
{
  return run_cmd (step,
                  t, log,
                  nullptr /* out_str */, path () /* out_file */,
                  warn_detect,
                  "b " + buildspec,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("b", envvars),
                  verbosity, buildspec, forward<A> (a)...);
}

template <typename... A>
static result_status
run_b (step_id step,
       tracer& t,
       string& log, const regexes& warn_detect,
       const optional<step_id>& bkp_step,
       const optional<result_status>& bkp_status,
       const strings& aux_env,
       string& last_cmd,
       const char* verbosity,
       const string& buildspec, A&&... a)
{
  const char* const* envvars (nullptr);
  return run_b (step,
                envvars,
                t,
                log, warn_detect,
                bkp_step, bkp_status, aux_env, last_cmd,
                verbosity, buildspec, forward<A> (a)...);
}

template <typename... A>
static result_status
run_b (step_id step,
       tracer& t,
       string& log, const regexes& warn_detect,
       const optional<step_id>& bkp_step,
       const optional<result_status>& bkp_status,
       const strings& aux_env,
       string& last_cmd,
       const char* verbosity,
       const strings& buildspecs, A&&... a)
{
  const char* const* envvars (nullptr);
  return run_b (step,
                envvars,
                t,
                log, warn_detect,
                bkp_step, bkp_status, aux_env, last_cmd,
                verbosity, buildspecs, forward<A> (a)...);
}

template <typename... A>
static result_status
run_ldconfig (step_id step,
              tracer& t,
              string& log, const regexes& warn_detect,
              const optional<step_id>& bkp_step,
              const optional<result_status>& bkp_status,
              const strings& aux_env,
              string& last_cmd,
              A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file*/,
                  warn_detect,
                  "sudo ldconfig",
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("sudo"),
                  "ldconfig", forward<A> (a)...);
}

template <typename... A>
static result_status
run_apt_get (step_id step,
             tracer& t,
             string& log, const regexes& warn_detect,
             const optional<step_id>& bkp_step,
             const optional<result_status>& bkp_status,
             const strings& aux_env,
             string& last_cmd,
             const string& cmd, A&&... a)
{
  // Note: dumps some of its diagnostics to stdout.
  //
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file*/,
                  warn_detect,
                  "sudo apt-get " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("sudo"),
                  "apt-get", cmd, forward<A> (a)...);
}

template <typename... A>
static result_status
run_dnf (step_id step,
         tracer& t,
         string& log, const regexes& warn_detect,
         const optional<step_id>& bkp_step,
         const optional<result_status>& bkp_status,
         const strings& aux_env,
         string& last_cmd,
         const string& cmd, A&&... a)
{
  // Note: dumps some of its diagnostics to stdout.
  //
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file*/,
                  warn_detect,
                  "sudo dnf " + cmd,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("sudo"),
                  "dnf", cmd, forward<A> (a)...);
}

#ifndef _WIN32
template <typename... A>
static result_status
run_tar (step_id step,
         tracer& t,
         string& log, const regexes& warn_detect,
         const optional<step_id>& bkp_step,
         const optional<result_status>& bkp_status,
         const strings& aux_env,
         string& last_cmd,
         bool sudo,
         A&&... a)
{
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file*/,
                  warn_detect,
                  sudo ? "sudo tar" : "tar",
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env (sudo ? "sudo" : "tar"),
                  sudo ? "tar" : nullptr, forward<A> (a)...);
}
#else
template <typename... A>
static result_status
run_tar (step_id step,
         tracer& t,
         string& log, const regexes& warn_detect,
         const optional<step_id>& bkp_step,
         const optional<result_status>& bkp_status,
         const strings& aux_env,
         string& last_cmd,
         bool /* sudo */,
         A&&... a)
{
  // Note: using bsdtar which can unpack .zip archives (and also not an MSYS
  //       executable).
  //
  return run_cmd (step,
                  t,
                  log,
                  nullptr /* out_str */, path () /* out_file*/,
                  warn_detect,
                  "bsdtar",
                  bkp_step, bkp_status, aux_env, last_cmd,
                  process_env ("bsdtar"),
                  forward<A> (a)...);
}
#endif

// Upload compressed manifest to the specified TFTP URL with curl. If disk
// is false, then upload without creating a temporary file.
//
// Issue diagnostics and throw failed on invalid manifest or process
// management errors and throw io_error for curl input/output errors or
// non-zero curl exit. Also throw system_error with ENOSPC if unable to create
// a temporary file due to insufficient disk space.
//
template <typename T>
static void
upload_manifest (tracer& trace,
                 const string& url,
                 const T& m,
                 const string& what,
                 bool disk = true)
{
  try
  {
    // Piping the data directly into curl's stdin sometimes results in the
    // broken pipe error on the client and partial/truncated upload on the
    // server. This happens quite regularly on older Linux distributions
    // (e.g., Debian 8, Ubuntu 16.04) but also sometimes on Windows. On the
    // other hand, uploading from a file appears to work reliably (we still
    // get an odd error on Windows from time to time with larger uploads).
    //
    auto_rmfile tmp;
    if (disk)
    {
      try
      {
        try
        {
          tmp = auto_rmfile (path::temp_path (what + "-manifest.lz4"));
          ofdstream ofs (tmp.path, fdopen_mode::binary);
          olz4stream ozs (ofs, 9, 5 /* 256KB */, nullopt /* content_size */);

          // Let's not break lines in the manifest values not to further
          // increase the size of the manifest encoded representation. Also
          // here we don't care much about readability of the manifest since
          // it will only be read by the bbot agent anyway.
          //
          manifest_serializer s (ozs, tmp.path.string (), true /*long_lines*/);
          m.serialize (s);

          ozs.close ();
          ofs.close ();
        }
        catch (const system_error& e)
        {
          if (e.code ().category () == std::generic_category () &&
              e.code ().value () == ENOSPC)
            throw_generic_error (ENOSPC);

          fail << "unable to save " << what << " manifest: " << e;
        }
      }
      catch (const io_error& e) // In case not derived from system_error.
      {
        fail << "unable to save " << what << " manifest: " << e;
      }
    }

    try
    {
      tftp_curl c (trace,
                   disk ? tmp.path : path ("-"),
                   nullfd,
                   curl::put,
                   url,
                   "--tftp-blksize", tftp_blksize,
                   "--max-time", tftp_put_timeout);

      if (!disk)
      {
        // Note: it's simpler to compress than do deal with the variability
        // everywhere else.
        //
        olz4stream ozs (c.out, 9, 5 /* 256KB */, nullopt /* content_size */);

        manifest_serializer s (ozs, url, true /* long_lines */);
        m.serialize (s);

        ozs.close ();
        c.out.close ();
      }

      if (!c.wait ())
        throw_generic_ios_failure (EIO, "non-zero curl exit code");
    }
    catch (const process_error& e)
    {
      fail << "unable to execute curl: " << e;
    }
    catch (const system_error& e)
    {
      const auto& c (e.code ());

      if (c.category () == generic_category ())
        throw_generic_ios_failure (c.value (), e.what ());
      else
        throw_system_ios_failure (c.value (), e.what ());
    }
  }
  catch (const manifest_serialization& e)
  {
    fail << "invalid " << what << " manifest: " << e.description;
  }
}

static strings
parse_auxiliary_environment (const string&, const char*); // See below.

static const string worker_checksum ("5"); // Logic version.

static int bbot::
build (size_t argc, const char* argv[])
{
  using std::map;
  using std::multimap;

  using string_parser::unquote;

  using serializer    = manifest_serializer;
  using serialization = manifest_serialization;

  using namespace bpkg;

  tracer trace ("build");

  // Our overall plan is as follows:
  //
  // 1. Parse the task manifest (it should be in CWD).
  //
  // 2. Run bpkg to create the package/tests configurations, add the
  //    repository to them, and configure, build, test, optionally install or
  //    alternatively bindist and sys-install, test installed, and
  //    (sys-)uninstall the package all while saving the logs in the result
  //    manifest.
  //
  // 3. Upload the result manifest and, optionally, the build artifacts.
  //
  // NOTE: consider updating worker_checksum if making any logic changes.
  //
  // Note also that we are being "watched" by the startup version of us which
  // will upload an appropriate result in case we exit with an error. So here
  // for abnormal situations (like a failure to parse the manifest), we just
  // fail.
  //
  task_manifest tm (
    parse_manifest<task_manifest> (path ("task.manifest"), "task"));

  // Reset the dependency checksum if the task's worker checksum doesn't match
  // the current one.
  //
  if (!tm.worker_checksum || *tm.worker_checksum != worker_checksum)
    tm.dependency_checksum = nullopt;

  result_manifest rm {
    tm.name,
    tm.version,
    result_status::success,
    operation_results {},
    worker_checksum,
    nullopt /* dependency_checksum */
  };

  auto add_result = [&rm] (string o) -> operation_result&
  {
    rm.results.push_back (
      operation_result {move (o), result_status::success, ""});

    return rm.results.back ();
  };

  dir_path rwd; // Root working directory.

  // Archive of the build artifacts for upload.
  //
  path upload_archive ("upload.tar");

  // Resolve the breakpoint specified by the interactive manifest value into
  // the step id or the result status breakpoint. If the breakpoint is
  // invalid, then log the error and abort the build. Note that we reuse the
  // configure operation log here not to complicate things.
  //
  optional<step_id> bkp_step;
  optional<result_status> bkp_status;
  string last_cmd; // Used in the user prompt.

  // Parse the auxiliary environment, if present, to dump it into the
  // configure operation log and to use it in the interactive build user
  // prompt. Note that this environment is already set by the parent process.
  //
  strings aux_env;

  for (;;) // The "breakout" loop.
  {
    auto fail_operation = [&trace] (operation_result& r,
                                    const string& e,
                                    result_status s,
                                    const string& name = "",
                                    uint64_t line = 0,
                                    uint64_t column = 0)
    {
      string prefix;

      if (!name.empty ())
      {
        prefix += name;
        prefix += ':';

        if (line != 0)
        {
          prefix += to_string (line);
          prefix += ':';

          if (column != 0)
          {
            prefix += to_string (column);
            prefix += ':';
          }
        }

        prefix += ' ';
      }

      l3 ([&]{trace << prefix << e;});

      r.log    += prefix + "error: " + e + '\n';
      r.status  = s;
    };

    // Regular expressions that detect different forms of build2 toolchain
    // warnings. Accidently (or not), they also cover GCC and Clang warnings
    // (for the English locale).
    //
    // The expressions will be matched multiple times, so let's make the
    // matching faster, with the potential cost of making regular expressions
    // creation slower.
    //
    regex::flag_type f (regex_constants::optimize); // ECMAScript is implied.

    regexes wre {
      regex ("^warning: ", f),
      regex ("^.+: warning: ", f)};

    for (const string& re: tm.unquoted_warning_regex ())
      wre.emplace_back (re, f);

    if (tm.interactive && *tm.interactive != "none")
    {
      const string& b (*tm.interactive);

      if (b == "error")
        bkp_status = result_status::error;
      else if (b == "warning")
        bkp_status = result_status::warning;
      else
      {
        for (size_t i (0); i < step_id_str.size (); ++i)
        {
          if (b == step_id_str[i])
          {
            bkp_step = static_cast<step_id> (i);
            break;
          }
        }
      }

      if (!bkp_step && !bkp_status)
      {
        fail_operation (add_result ("configure"),
                        "invalid interactive build breakpoint '" + b + '\'',
                        result_status::abort);

        break;
      }
    }

    // Parse the auxiliary environment, if present.
    //
    if (tm.auxiliary_environment)
    {
      // Note: cannot throw since has already been called successfully by the
      // parent process.
      //
      aux_env = parse_auxiliary_environment (*tm.auxiliary_environment,
                                             comment_begin);
    }

    // Split the argument into prefix (empty if not present) and unquoted
    // value (absent if not present) and determine the step status. If the
    // prefix is present and is prepended with the '+'/'-' character, then the
    // respective step needs to be enabled/disabled. Return nullopt if the
    // prefix is invalid.
    //
    // Note that arguments with absent values are normally used to
    // enable/disable steps and are omitted from the command lines.
    //
    struct argument
    {
      string prefix;

      // Absent if the argument value is an empty unquoted string.
      //
      optional<string> value;

      // True - enable, false - disable, nullopt - neutral.
      //
      optional<bool> step_status;
    };

    auto parse_arg = [] (const string& a) -> optional<argument>
    {
      size_t p (a.find_first_of (":=\"'"));

      auto value = [] (const string& v)
      {
        return !v.empty () ? unquote (v) : optional<string> ();
      };

      if (p == string::npos || a[p] != ':') // No prefix.
        return argument {string (), value (a), nullopt};

      string prefix (a, 0, p);

      optional<bool> enable;
      if (prefix[0] == '+' || prefix[0] == '-')
      {
        enable = (prefix[0] == '+');

        prefix.erase (0, 1);

        if (prefix != "bpkg.update"                         &&
            prefix != "bpkg.test"                           &&
            prefix != "bpkg.test-separate.update"           &&
            prefix != "bpkg.test-separate.test"             &&
            prefix != "bpkg.install"                        &&
            prefix != "bbot.install.ldconfig"               &&
            prefix != "bpkg.bindist.debian"                 &&
            prefix != "bpkg.bindist.fedora"                 &&
            prefix != "bpkg.bindist.archive"                &&
            prefix != "bbot.sys-install"                    &&
            prefix != "bbot.sys-install.ldconfig"           &&
            prefix != "b.test-installed.create"             &&
            prefix != "b.test-installed.test"               &&
            prefix != "bpkg.test-separate-installed.create" &&
            prefix != "bpkg.test-separate-installed.update" &&
            prefix != "bpkg.test-separate-installed.test"   &&
            prefix != "bbot.bindist.upload"                 &&
            prefix != "bbot.upload")
        {
          return nullopt; // Prefix is invalid.
        }
      }

      for (const string& id: step_id_str)
      {
        size_t n (prefix.size ());
        if (id.compare (0, n, prefix) == 0 &&
            (id.size () == n || (id.size () > n && id[n] == '.')))
          return argument {move (prefix), value (a.substr (p + 1)), enable};
      }

      return nullopt; // Prefix is invalid.
    };

    // Keep track of explicitly enabled/disabled steps.
    //
    map<string, bool> step_statuses;

    // Return true if the step is explicitly enabled via a +<prefix>:[<value>]
    // environment/configuration argument.
    //
    auto step_enabled = [&step_statuses] (step_id step) -> bool
    {
      auto i (step_statuses.find (to_string (step)));
      return i != step_statuses.end () && i->second;
    };

    // Return true if the step is explicitly disabled via a -<prefix>:[<value>]
    // environment/configuration argument.
    //
    auto step_disabled = [&step_statuses] (step_id step) -> bool
    {
      auto i (step_statuses.find (to_string (step)));
      return i != step_statuses.end () && !i->second;
    };

    // Save a step status.
    //
    // Note that since the bpkg.bindist.* steps are mutually exclusive we only
    // keep the latest status change (see above for details).
    //
    auto step_status = [&step_statuses] (const string& step, bool status)
    {
      if (step.compare (0, 13, "bpkg.bindist.") == 0)
      {
        step_statuses.erase ("bpkg.bindist.debian");
        step_statuses.erase ("bpkg.bindist.fedora");
        step_statuses.erase ("bpkg.bindist.archive");
      }

      step_statuses[step] = status;
    };

    // Parse the environment, target configuration, and build package
    // configuration arguments.
    //
    // NOTE: keep this parsing order intact so that, for example, a build
    //       package configuration argument can override step status specified
    //       by a target configuration argument.
    //

    // Parse environment arguments.
    //
    multimap<string, string> modules;
    multimap<string, string> env_args;

    for (size_t i (1); i != argc; ++i)
    {
      const char* a (argv[i]);
      optional<argument> v (parse_arg (a));

      if (!v)
        fail << "invalid environment argument prefix in '" << a << "'";

      bool mod (v->value              &&
                (*v->value)[0] != '-' &&
                v->value->find ('=') == string::npos);

      if (mod                                                           &&
          !v->prefix.empty ()                                           &&
          v->prefix != "b.create"                                       &&
          v->prefix != "bpkg.create"                                    &&
          v->prefix != "bpkg.target.create"                             &&
          v->prefix != "bpkg.host.create"                               &&
          v->prefix != "bpkg.module.create"                             &&
          v->prefix != "b.test-installed.create"                        &&
          v->prefix != "bpkg.test-separate-installed.create"            &&
          v->prefix != "bpkg.test-separate-installed.create_for_target" &&
          v->prefix != "bpkg.test-separate-installed.create_for_host"   &&
          v->prefix != "bpkg.test-separate-installed.create_for_module")
        fail << "invalid module prefix in '" << a << "'";

      if (v->step_status)
        step_status (v->prefix, *v->step_status);

      if (v->value)
        (mod ? modules : env_args).emplace (make_pair (move (v->prefix),
                                                       move (*v->value)));
    }

    // Parse target configuration arguments. Report failures to the bbot
    // controller.
    //
    multimap<string, string> tgt_args;

    for (const string& c: tm.target_config)
    {
      optional<argument> v (parse_arg (c));

      if (!v)
      {
        rm.status |= result_status::abort;
        l3 ([&]{trace << "invalid target configuration argument prefix in "
                      << "'" << c << "'";});
        break;
      }

      if (v->value               &&
          (*v->value)[0] != '-'  &&
          v->value->find ('=') == string::npos)
      {
        rm.status |= result_status::abort;
        l3 ([&]{trace << "invalid target configuration argument '" << c
                      << "'";});
        break;
      }

      if (v->step_status)
        step_status (v->prefix, *v->step_status);

      if (v->value)
        tgt_args.emplace (make_pair (move (v->prefix), move (*v->value)));
    }

    if (!rm.status)
      break;

    // If we end up with multiple current configurations (root and install;
    // see below), then when running the bpkg-pkg-build command we need to
    // specify the configuration for each package explicitly via
    // --config-uuid.
    //
    // While it's tempting to use the --config-name option instead of
    // --config-uuid, that wouldn't work well for multiple current
    // configurations. For --config-name the configuration search is carried
    // out among configurations explicitly linked to the main configuration
    // only. That's in contrast to --config-uuid, when the whole configuration
    // cluster is searched (see bpkg-pkg-build implementation for details).
    //
    // Also, the build package configuration may contain the
    // configuration-specific dependencies specified using the
    // package-specific --config-uuid option. Thus, we do not generate random
    // UUIDs but use some predefined values, which the user can refer to in
    // the *-build-config package manifest values.
    //
    // Note, though, that currently there is no way to customarily configure a
    // dependency in the private host and build2 configurations specifically.
    // In the future we may support that by, for example, creating such a
    // host/build2 configuration explicitly (making it not private) if any
    // dependency needs to be configured in it.
    //
    const char* target_uuid           ("00000000-0000-0000-0000-000000000001");
    const char* host_uuid             ("00000000-0000-0000-0000-000000000002");
    const char* module_uuid           ("00000000-0000-0000-0000-000000000003");
    const char* install_uuid          ("00000000-0000-0000-0000-000000000004");
    const char* target_installed_uuid ("00000000-0000-0000-0000-000000000005");
    const char* host_installed_uuid   ("00000000-0000-0000-0000-000000000006");
    const char* module_installed_uuid ("00000000-0000-0000-0000-000000000007");

    // Parse the build package configuration represented as a whitespace
    // separated list of the following potentially quoted bpkg-pkg-build
    // command arguments:
    //
    // <option>...
    // <config-var>...
    // ([{ <config-var>... }+] (?[sys:]|sys:)<pkg-name>[<version-spec>])...
    // ( { <config-var>... }+  <pkg-name>)...
    //
    // If the package configuration is specified, then parse it into the
    // following lists/maps:
    //
    // - The prefixed global options and configuration variables map
    //   (pkg_args). Added to the command lines at the corresponding steps
    //   after potential environment and target configuration arguments.
    //
    // - The unprefixed global options list (pkg_config_opts). Specified after
    //   all the prefixed global options on the bpkg-pkg-build command line at
    //   the bpkg.configure.build step.
    //
    // - The main package-specific configuration variables list
    //   (pkg_config_vars). Specified for the main package only on the
    //   bpkg-pkg-build command line at the bpkg.configure.build step,
    //   wherever it is configured. Also specified on the b-configure command
    //   line at the b.test-installed.configure step.
    //
    // - The main package-specific dependency packages list
    //   (pkg_config_main_deps), potentially with their own configuration
    //   variables (but not options). Only configured where the main package
    //   is configured with the bpkg-pkg-build command line at the
    //   bpkg.configure.build step.
    //
    // - The global system dependency packages list (pkg_config_glob_deps).
    //   Configured in all configurations with the bpkg-pkg-build command line
    //   at the bpkg.configure.build step.
    //
    // - The main and external test package-specific configuration variables
    //   map (pkg_config_pkgs). Specified on the bpkg-pkg-build command lines
    //   at the bpkg.configure.build and
    //   bpkg.test-separate-installed.configure.build steps. Package names
    //   other than the main and external test package names are silently
    //   ignored.
    //
    // - The configuration-specific dependencies, potentially with the
    //   dependency-specific configuration variables (pkg_config_deps).
    //   Configured in configurations specified by their package-specific
    //   --config-uuid=<uuid> options (see the above *_uuid variables for the
    //   recognized configuration UUIDs).
    //
    multimap<string, string>      pkg_args;
    strings                       pkg_config_opts;
    strings                       pkg_config_vars;
    vector<pair<string, strings>> pkg_config_main_deps; // ?<pkg>, sys:<pkg>
    vector<pair<string, strings>> pkg_config_glob_deps; // ?sys:<pkg>
    map<string, strings>          pkg_config_pkgs;      // <pkg>

    // { --config-uuid=<uuid>... }+ (?[sys:]<pkg> | sys:<pkg>)
    //
    // Maps configuration UUIDs to dependencies, potentially, with the
    // package-specific configuration variables.
    //
    map<string, vector<pair<string, strings>>> pkg_config_deps;

    // Return true if any configuration-specific dependencies need to be
    // configured in the specified configuration.
    //
    auto config_deps = [&pkg_config_deps] (const char* conf_uuid)
    {
      return pkg_config_deps.find (conf_uuid) != pkg_config_deps.end ();
    };

    // Add configuration-specific dependencies with the dependency-specific
    // configuration variables, if present, to the arguments list. Return true
    // if any dependency has been added to the list.
    //
    auto add_config_deps = [&pkg_config_deps] (const char* conf_uuid,
                                               strings& args)
    {
      bool r (false);
      auto i (pkg_config_deps.find (conf_uuid));

      if (i != pkg_config_deps.end ())
      {
        const vector<pair<string, strings>>& deps (i->second);

        // Add dependencies which have some configuration variables specified
        // and count the number of others.
        //
        // ({ --config-uuid <uuid> <var>... }+ <pkg>)...
        //
        size_t no_vars (0);
        for (const pair<string, strings>& d: deps)
        {
          if (!d.second.empty ())
          {
            args.push_back ("{");
            args.push_back ("--config-uuid");
            args.push_back (conf_uuid);
            args.insert (args.end (), d.second.begin (), d.second.end ());
            args.push_back ("}+");

            args.push_back (d.first);
          }
          else
            ++no_vars;
        }

        // Add dependencies which have no configuration variables specified.
        //
        // { --config-uuid <uuid> }+ { <pkg>... }
        //
        if (no_vars != 0)
        {
          args.push_back ("{");
          args.push_back ("--config-uuid");
          args.push_back (conf_uuid);
          args.push_back ("}+");

          if (no_vars != 1)
            args.push_back ("{");

          for (const pair<string, strings>& d: deps)
          {
            if (d.second.empty ())
              args.push_back (d.first);
          }

          if (no_vars != 1)
            args.push_back ("}");
        }

        r = true;
      }

      return r;
    };

    if (!tm.package_config.empty ())
    {
      struct abort {};

      auto fail = [&tm, &add_result, &fail_operation] (const string& d,
                                                       bool throw_abort = true)
      {
        fail_operation (add_result ("configure"),
                        "invalid package configuration: " + d +
                        "\n  info: package configuration: '"  +
                        tm.package_config + '\'',
                        result_status::abort);

        if (throw_abort)
          throw abort ();
      };

      try
      {
        strings argsv (string_parser::parse_quoted (tm.package_config,
                                                    false /* unquote */,
                                                    true /* comments */));

        cli::vector_scanner scanv (argsv);
        cli::group_scanner args (scanv);

        while (args.more ())
        {
          string a (args.next ());

          // Unless the argument is an unquoted dependency (starts with `?` or
          // `sys:`), first try to interpret it as a prefixed option/variable
          // and/or step id status (enabled/disabled).
          //
          if (!(a[0] == '?' || a.compare (0, 4, "sys:") == 0))
          {
            optional<argument> v (parse_arg (a));

            // Note that we only assume an argument as prefixed if the prefix
            // is a known step id. Otherwise, we interpret the argument as
            // unprefixed global option, variable, or a package spec.
            //
            if (v && !v->prefix.empty ())
            {
              if (v->value              &&
                  (*v->value)[0] != '-' &&
                  v->value->find ('=') == string::npos)
                fail ("invalid prefixed argument '" + a + '\'');

              if (args.group ().more ())
                fail ("unexpected options group for prefixed argument '" + a +
                      '\'');

              if (v->step_status)
                step_status (v->prefix, *v->step_status);

              if (v->value)
                pkg_args.emplace (make_pair (move (v->prefix),
                                             move (*v->value)));

              continue;
            }
          }

          a = unquote (a);

          // Return true if the argument is an option.
          //
          // Note that options with values can only be specified using
          // the single argument notation.
          //
          auto opt = [] (const string& a)
          {
            // Make sure that -- or - is always followed by some characters.
            //
            return a.compare (0, 2, "--") == 0 ? a.size () > 2 :
                   a[0] == '-'                 ? a.size () > 1 :
                                                 false         ;
          };

          // Return true if the argument is a configuration variable.
          //
          auto var = [] (const string& a)
          {
            // Note: we need to be careful not to misinterpret
            // '?libfoo == 1.0.0' as a variable.
            //
            return a.compare (0, 7, "config.") == 0 &&
                   a.find ('=') != string::npos;
          };

          bool o (opt (a));
          bool v (var (a));

          cli::scanner& ag (args.group ());

          if (o)      // Option.
          {
            if (ag.more ())
              fail ("unexpected options group for option '" + a + '\'');

            pkg_config_opts.push_back (move (a));
          }
          else if (v) // Configuration variable.
          {
            if (ag.more ())
              fail ("unexpected options group for configuration variable '" +
                    a + '\'');

            pkg_config_vars.push_back (move (a));
          }
          else        // Dependency or build-to-hold package.
          {
            // Note that we consider a system package as a dependency
            // regardless whether it is prefixed with '?' or not.
            //
            strings vars;
            strings uuids;
            while (ag.more ())
            {
              string da (unquote (ag.next ()));

              if (da.compare (0, 14, "--config-uuid=") == 0)
              {
                string uuid (da, 14);

                if (uuid != target_uuid           &&
                    uuid != host_uuid             &&
                    uuid != module_uuid           &&
                    uuid != install_uuid          &&
                    uuid != target_installed_uuid &&
                    uuid != host_installed_uuid   &&
                    uuid != module_installed_uuid)
                  fail ("unrecognized configuration UUID '" + uuid + '\'');

                uuids.push_back (move (uuid));
              }
              else if (var (da))
              {
                vars.push_back (move (da));
              }
              else
              {
                fail ("argument is not a configuration variable nor "
                      "configuration UUID for dependency " + a + ": '" + da +
                      '\'');
              }
            }

            // Add the system dependency packages (prefixed with `?sys:`) with
            // no configuration specified to a separate list, to be specified
            // globally on the bpkg-pkg-build command line for configuring
            // them in all the (being) created configurations. Add the
            // configuration-specific dependency packages to the
            // per-configuration lists, to be specified on the bpkg-pkg-build
            // command line for configuring them in the specific
            // configurations.
            //
            // Note, though, that we will handle the build-to-hold system
            // packages (prefixed with `sys:`) in the same way as non system
            // dependencies, since such an auto-configuration is only
            // supported by bpkg-pkg-build for system dependencies. In the
            // future, we may support that on the bbot worker level by, for
            // example, specifying all the configurations manually for the
            // build-to-hold system packages and also specifying them as a
            // system dependencies globally. We need to be careful to make
            // sure that these dependencies are also auto-configured for the
            // private configurations potentially created by bpkg-pkg-build.
            //

            // If the specified dependency is configuration-specific, then add
            // it to the configuration-specific lists and to the specified list
            // otherwise.
            //
            // Note: moves out entries from uuids list.
            //
            auto add_dep = [&a, &vars, &uuids, &pkg_config_deps]
                           (vector<pair<string, strings>>& non_cfg_spec_deps)
            {
              if (!uuids.empty ())
              {
                for (string& uuid: uuids)
                  pkg_config_deps[move (uuid)].emplace_back (a, vars);
              }
              else
                non_cfg_spec_deps.emplace_back (move (a), move (vars));
            };

            // Configuration-specific or global package dependency.
            //
            if (a.compare (0, 5, "?sys:") == 0)
            {
              add_dep (pkg_config_glob_deps);
            }
            //
            // Configuration-specific or main package dependency.
            //
            else if (a[0] == '?' || a.compare (0, 4, "sys:") == 0)
            {
              add_dep (pkg_config_main_deps);
            }
            //
            // Build-to-hold package.
            //
            else
            {
              if (vars.empty ())
                fail ("no configuration variables specified for package '" +
                      a + '\'');

              if (!uuids.empty ())
                fail ("configuration UUID cannot be specified for "
                      "build-to-hold package '" + a + '\'');

              auto i (pkg_config_pkgs.find (a));

              if (i == pkg_config_pkgs.end ())
              {
                pkg_config_pkgs.emplace (move (a), move (vars));
              }
              else
              {
                strings& vs (i->second);
                vs.insert (vs.end (),
                           make_move_iterator (vars.begin ()),
                           make_move_iterator (vars.end ()));
              }
            }
          }
        }
      }
      catch (const cli::exception& e)
      {
        fail (e.what (), false /* throw_abort */);
        break;
      }
      catch (const string_parser::invalid_string& e)
      {
        fail (e.what (), false /* throw_abort */);
        break;
      }
      catch (const abort&)
      {
        break;
      }
    }

    // Return command arguments for the specified step id, complementing
    // *.create[_for_*] steps with un-prefixed arguments. If no arguments are
    // specified for the step then use the specified fallbacks, potentially
    // both. Arguments with more specific prefixes come last. Optionally,
    // search for arguments starting from the specified step id rather than
    // from the least specific one (tool id).
    //
    auto step_args = [] (const multimap<string, string>& args,
                         step_id step,
                         optional<step_id> fallback1 = nullopt,
                         optional<step_id> fallback2 = nullopt,
                         optional<step_id> start_step = nullopt) -> cstrings
    {
      cstrings r;

      // Add arguments for a specified, potentially empty, prefix.
      //
      auto add_args = [&args, &r] (const string& prefix)
      {
        auto range (args.equal_range (prefix));

        for (auto i (range.first); i != range.second; ++i)
          r.emplace_back (i->second.c_str ());
      };

      // Add un-prefixed arguments if this is one of the *.create[_for_*]
      // steps.
      //
      switch (step)
      {
      case step_id::b_create:
      case step_id::bpkg_create:
      case step_id::bpkg_target_create:
      case step_id::bpkg_host_create:
      case step_id::bpkg_module_create:
      case step_id::b_test_installed_create:
      case step_id::bpkg_test_separate_installed_create:
      case step_id::bpkg_test_separate_installed_create_for_target:
      case step_id::bpkg_test_separate_installed_create_for_host:
      case step_id::bpkg_test_separate_installed_create_for_module:
        {
          add_args ("");
          break;
        }
      default: break;
      }

      auto add_step_args = [&add_args] (step_id step,
                                        optional<step_id> start_step = nullopt)
      {
        const string& s (to_string (step));

        size_t n;

        if (start_step)
        {
          const string& ss (to_string (*start_step));

          assert (s.size () >= ss.size ()            &&
                  s.compare (0, ss.size (), ss) == 0 &&
                  (s.size () == ss.size () || s[ss.size ()] == '.'));

          n = ss.size ();
        }
        else
          n = 0;

        for (;; ++n)
        {
          n = s.find ('.', n);

          add_args (n == string::npos ? s : string (s, 0, n));

          if (n == string::npos)
            break;
        }
      };

      // If no arguments found for the step id, then use the fallback step
      // ids, if specified.
      //
      if (args.find (to_string (step)) != args.end ())
      {
        add_step_args (step, start_step);
      }
      else
      {
        // Note that if we ever need to specify fallback pairs with common
        // ancestors, we may want to suppress duplicate ancestor step ids.
        //
        if (fallback1)
          add_step_args (*fallback1);

        if (fallback2)
          add_step_args (*fallback2);
      }

      return r;
    };

    // bpkg-rep-fetch trust options.
    //
    cstrings trust_ops;
    {
      const char* t ("--trust-no");

      for (const string& fp: tm.trust)
      {
        if (fp == "yes")
          t = "--trust-yes";
        else
        {
          trust_ops.push_back ("--trust");
          trust_ops.push_back (fp.c_str ());
        }
      }

      trust_ops.push_back (t);
    }

    const string&  pkg     (tm.name.string ());
    const version& ver     (tm.version);
    const string   repo    (tm.repository.string ());
    const dir_path pkg_dir (pkg + '-' + ver.string ());
    const string   pkg_var (tm.name.variable ());

    // Specify the revision explicitly for the bpkg-build command not to end
    // up with a race condition building the latest revision rather than the
    // zero revision.
    //
    const string pkg_rev (pkg +
                          '/' +
                          version (ver.epoch,
                                   ver.upstream,
                                   ver.release,
                                   ver.effective_revision (),
                                   ver.iteration).string ());

    // Query the project's build system information with `b info`.
    //
    auto prj_info = [&trace] (const dir_path& d,
                              b_info_flags fl,
                              const char* what)
    {
      // Note that the `b info` diagnostics won't be copied into any of the
      // build logs. This is fine as this is likely to be an infrastructure
      // problem, given that the project distribution has been successfully
      // created. It's actually not quite clear which log this diagnostics
      // could go into.
      //
      try
      {
        return b_info (d, fl, verb, trace);
      }
      catch (const b_error& e)
      {
        if (e.normal ())
          throw failed (); // Assume the build2 process issued diagnostics.

        fail << "unable to query " << what << ' ' << d << " info: " << e
             << endf;
      }
    };

    rwd = current_directory ();

    // Create directory for the build artifacts to archive and upload.
    //
    dir_path upload_dir ("upload");

    mk (trace, nullptr /* log */, upload_dir);

    // If the package comes from a version control-based repository, then we
    // will also test its dist meta-operation. Specifically, we will checkout
    // the package outside the configuration directory passing --checkout-root
    // to the configure-only pkg-build command, re-distribute the checked out
    // directory in the load distribution mode, and then use this distribution
    // as a source to build the package.
    //
    dir_path dist_root (rwd / dir_path ("dist"));
    dir_path dist_src  (dist_root / pkg_dir);

    dir_path dist_install_root (rwd / dir_path ("dist-install"));
    dir_path dist_install_src  (dist_install_root / pkg_dir);

    dir_path dist_installed_root (rwd / dir_path ("dist-installed"));

    // Redistribute the package source directory (pkg_dir) checked out into
    // the directory other than the configuration directory (dist_root) and
    // replace it with the newly created distribution. Assume that the current
    // directory is the package configuration directory. Optionally pass the
    // config.import.* variable override and/or set the environment variables
    // for the build2 process. Return true if the dist meta-operation
    // succeeds.
    //
    auto redist = [&trace, &wre, &bkp_step, &bkp_status, &aux_env, &last_cmd]
                  (step_id step,
                   operation_result& r,
                   const dir_path& dist_root,
                   const dir_path& pkg_dir, // <name>-<version>
                   const optional<string>& import = nullopt,
                   const small_vector<string, 1>& envvars = {})
    {
      // Temporarily change the current directory to the distribution root
      // parent directory from the configuration directory to shorten the
      // command line paths and try to avoid the '..' path prefix.
      //
      dir_path dp (dist_root.directory ());
      dir_path dn (dist_root.leaf ());

      // Redistribute the package using the configured output directory.
      //
      dir_path cnf_dir (change_wd (trace, &r.log, dp));
      dir_path out_dir (cnf_dir.relative (dp) / pkg_dir);
      dir_path src_dir (dn / pkg_dir);

      // Create the re-distribution root directory next to the distribution
      // root.
      //
      dir_path redist_root ("re" + dn.string ());

      r.status |= run_b (
        step,
        envvars,
        trace, r.log, wre,
        bkp_step, bkp_status, aux_env, last_cmd,
        "-v",
        "config.dist.root=" + redist_root.string (),
        import,
        ("dist('" + src_dir.representation () + "'@'" +
         out_dir.representation () + "')"));

      if (!r.status)
        return false;

      // Replace the package source directory with the re-distribution result.
      //
      rm_r (trace, &r.log, src_dir);
      mv   (trace, &r.log, redist_root / pkg_dir, src_dir);

      change_wd (trace, &r.log, cnf_dir); // Return back to the configuration.
      return true;
    };

    // Note that if this is not a self-hosted configuration, then we do not
    // build external runtime tests nor run internal for host or module
    // packages because the assumption is that they have been built/run (and
    // with buildtab settings such as warnings, etc) when testing the
    // self-hosted configuration this non-self-hosted one is based on. Also,
    // by the same reason, we don't install tools or modules nor generate the
    // binary distribution packages for them for non-self-hosted
    // configurations.
    //
    // Actually, it could make sense to build and install tools and module
    // from a target configuration in this case. But that means for a
    // non-self-hosted configuration a tool/module may want to test two
    // things: its output build and its own build, which means we would need a
    // way to control which of the two things (or both) are to be tested
    // (think of two cross-compiler configurations, Emscripten and MinGW: for
    // the former a source code generator would normally only want to test the
    // output while for the latter -- both; maybe we could have a `cross-host`
    // class, meaning that the configuration is not host itself but its target
    // is). In any case, seeing that there is no way to verify such own build
    // works, we ignore this for now.
    //
    // Also note that build system modules can only have external build-time
    // tests (which is verified by bpkg-rep-fetch) and target packages cannot
    // have external build-time tests (which we verify ourselves).
    //
    bool selfhost (tm.host && *tm.host);

    // Detect if the package is of the target, host, or module type.
    //
    auto requirement = [&tm] (const char* id)
    {
      return find_if (tm.requirements.begin (),
                      tm.requirements.end (),
                      [id] (const requirement_alternatives& r)
                      {
                        if (r.size () == 1)
                        {
                          const requirement_alternative& a (r[0]);
                          return find (a.begin (), a.end (), id) != a.end ();
                        }

                        return false;
                      }) != tm.requirements.end ();
    };

    bool module_pkg (pkg.compare (0, 10, "libbuild2-") == 0);
    bool bootstrap  (module_pkg && requirement ("bootstrap"));
    bool host_pkg   (!module_pkg && requirement ("host"));
    bool target_pkg (!module_pkg && !host_pkg);

    // Don't generate binary packages for tools or modules for non-self-hosted
    // configurations (see above for details).
    //
    optional<step_id> bindist;

    if (target_pkg || selfhost)
    {
      if (step_enabled (step_id::bpkg_bindist_debian))
        bindist = step_id::bpkg_bindist_debian;
      else if (step_enabled (step_id::bpkg_bindist_fedora))
        bindist = step_id::bpkg_bindist_fedora;
      else if (step_enabled (step_id::bpkg_bindist_archive))
        bindist = step_id::bpkg_bindist_archive;
    }

    bool sys_install (bindist && !step_disabled (step_id::bbot_sys_install));
    bool bindist_upload (bindist && step_enabled (step_id::bbot_bindist_upload));

    // Unless a bpkg.bindist.* step is enabled or bpkg.install step is
    // disabled, search for config.install.root variable. If it is present and
    // has a non-empty value, then test the package installation and
    // uninstall. Note that passing [null] value would be meaningless, so we
    // don't recognize it as a special one.
    //
    // Note that the host package can only be installed for a self-hosted
    // configuration, using bpkg configuration of the target type.
    //
    // Also note that the module package is always installed for a self-hosted
    // configuration (and never otherwise), using config.install.root
    // specified for ~build2 configuration.
    //
    // If present, indicates that the install, test installed, and uninstall
    // operations need to be tested.
    //
    // Note that the main package may not support the install operation. We,
    // however, can only detect that after the package is configured. If
    // that's the case, we will disable the steps which may not be performed
    // for such a package (bpkg.install, bpkg.bindist.*, etc) later, after the
    // package is configured.
    //
    optional<dir_path> install_root;

    // While building and running tests against the installation created
    // either from source or from the archive distribution package we will
    // make the bin/ subdirectory of config.install.root, if specified, the
    // first entry in the PATH environment variable, except for build system
    // modules which supposedly don't install any executables.
    //
    // Note that normally the config.install.root is expected to be prefixed
    // with the bpkg.target.create or, as a fallback, b.create or bpkg.create
    // step ids. However, for testing of the relocatable installations it can
    // be desirable to extract the archive distribution package content at the
    // bbot.sys-install.tar.extract step into a different installation
    // directory. If that's the case, then this directory needs to also be
    // specified as bbot.sys-install:config.install.root. If specified, this
    // directory will be preferred as a base for forming the bin/ directory
    // path.
    //
    optional<dir_path> install_bin;

    auto config_install_root = [&step_args, &tgt_args]
                               (step_id s,
                                optional<step_id> f1 = nullopt,
                                optional<step_id> f2 = nullopt)
      -> optional<dir_path>
    {
      size_t n (19);
      auto space = [] (char c) {return c == ' ' || c == '\t';};

      for (const char* a: reverse_iterate (step_args (tgt_args, s, f1, f2)))
      {
        if (strncmp (a, "config.install.root", n) == 0 &&
            (a[n] == '=' || space (a[n])))
        {
          while (space (a[n])) ++n; // Skip spaces.
          if (a[n] == '=')     ++n; // Skip the equal sign.
          while (space (a[n])) ++n; // Skip spaces.

          // Note that the config.install.root variable value may potentially
          // be quoted.
          //
          return dir_path (unquote (a + n));
        }
      }

      return nullopt;
    };

    if ((target_pkg || selfhost) &&
        !bindist                 &&
        !step_disabled (step_id::bpkg_install))
    {
      if (!module_pkg)
      {
        install_root = config_install_root (step_id::bpkg_target_create,
                                            step_id::b_create,
                                            step_id::bpkg_create);

        if (install_root)
          install_bin = *install_root / dir_path ("bin");
      }
      else
        install_root = dir_path ();
    }

    // Split external test packages into the runtime and build-time lists.
    //
    // Note that runtime and build-time test packages are always configured in
    // different bpkg configurations, since they can depend on different
    // versions of the same package.
    //
    small_vector<test_dependency, 1> runtime_tests;
    small_vector<test_dependency, 1> buildtime_tests;

    for (test_dependency& t: tm.tests)
    {
      if (t.buildtime)
        buildtime_tests.push_back (move (t));
      else if (target_pkg || selfhost)
        runtime_tests.push_back (move (t));
    }

    bool has_buildtime_tests (!buildtime_tests.empty ());
    bool has_runtime_tests   (!runtime_tests.empty ());

    // Abort if a target package has external build-time tests.
    //
    if (target_pkg && has_buildtime_tests)
    {
      fail_operation (
        add_result ("configure"),
        "build-time tests in package not marked with `requires: host`",
        result_status::abort);

      break;
    }

    // Create the required build configurations.
    //
    // Note that if this is a target package, then we intentionally do not
    // create host or module configuration letting the automatic private
    // configuration creation to take its course (since that would probably be
    // the most typical usage scenario).
    //
    // Also note that we may need a separate target configuration to build the
    // host package for installation. This is required to avoid a potential
    // conflict between the main package and a tool it may try to run during
    // the build. We also do the same for module packages which, while cannot
    // have build-time dependencies, could have private code generators. This
    // configuration needs to have the target type (so that it uses any
    // build-time dependencies from build-host/module configurations). Note
    // also that we currently only do this for self-hosted configuration
    // (since we don't install otherwise, see above).
    //
    dir_path target_conf  ("build");
    dir_path host_conf    ("build-host");
    dir_path module_conf  ("build-module");
    dir_path install_conf ("build-install");

    // Main package config.
    //
    const dir_path& main_pkg_conf (target_pkg ? target_conf :
                                   host_pkg   ? host_conf   :
                                                module_conf);

    // Create the target configuration if this is a target package or if the
    // host/module package has external build-time tests.
    //
    bool create_target (target_pkg || has_buildtime_tests);

    // Create the host configuration if this is a host package.
    //
    // Also create it for the module package with external build-time tests.
    // The idea is to be able to test a tool which might only be tested via
    // the module. To be precise, we need to check that the tests package has
    // a build-time dependency (on the tool) but that's not easy to do and so
    // we will create a host configuration if a module has any build-time
    // tests.
    //
    bool create_host (host_pkg || (module_pkg && has_buildtime_tests));

    // Create the module configuration if the package is a build system
    // module.
    //
    // Also create it for the host package with the external build-time tests,
    // so that a single build2 configuration is used for both target and host
    // packages (this is important in case they happen to use the same
    // module).
    //
    bool create_module (module_pkg || (host_pkg && has_buildtime_tests));

    // Create the configuration for installing the main package (potentially
    // as a part of generating binary distribution package) of the host or
    // module type, unless it's not supposed to be installed.
    //
    bool create_install (!target_pkg && (install_root || bindist));

    // Here is the table of the configurations created for the different types
    // of packages (see below for details on configurations created for the
    // test installed case). Columns are package types (target, host, or
    // module) and rows are configuration types created:
    //
    //                   target    host               module
    // ---------------------------------------------------------------
    // target            yes       build-time tests   build-time tests
    // host              private   yes                build-time tests
    // module            private   build-time tests   yes
    // install           no        install/bindist    install/bindist
    //
    // And only if has run-time tests (only target package or host package for
    // self-hosted configurations) or has build-time tests (only host or
    // module package):
    //
    //                   target    host               module
    // ---------------------------------------------------------------
    // target installed  yes       build-time tests   yes
    // host installed    private   configure sys:     yes
    // module installed  private   build-time tests   configure sys:

    // Configuration where the package will be installed from.
    //
    dir_path effective_install_conf (
      rwd / (create_install ? install_conf : main_pkg_conf));

    // Root configuration through which we will be configuring the cluster
    // (note: does not necessarily match the main package type).
    //
    // In other words, this is configuration that will be specified for
    // bpkg-pkg-build as the current configuration (via -d). It must be the
    // configuration that links to all the other configurations, except
    // install.
    //
    // Note that the install configuration, if present, is either the
    // cluster's "second root" (for a host package) or is an independent
    // cluster (for a module package). In either case it needs to additionally
    // be specified as a current configuration on the command line.
    //
    const dir_path& root_conf (create_target ? target_conf :
                               create_host   ? host_conf   :
                                               module_conf);

    // Note that bpkg doesn't support configuring bootstrap module dependents
    // well, not distinguishing such modules from regular ones (see
    // pkg_configure() for details). Thus, we need to pass the
    // !config.import.* global override wherever required ourselves.
    //
    // Also note that since this override is global, it may only be specified
    // globally on the bpkg command line (as opposed to package-specific
    // overrides).
    //
    optional<string> bootstrap_import;

    if (bootstrap)
      bootstrap_import = "!config.import." + pkg_var + '=' +
        (rwd / main_pkg_conf).string ();

    // Log the configuration UUID as a comment.
    //
    auto log_conf_uuid = [] (tracer& t, string& log,
                             const char* uuid,
                             const char* name)
    {
      string s (uuid);
      s += " - ";
      s += name;

      log_comment (t, log, s);
    };

    // Configure.
    //
    {
      operation_result& r (add_result ("configure"));

      // If we have auxiliary environment, show it in the logs.
      //
      if (!aux_env.empty ())
      {
        for (const string& e: aux_env)
        {
          r.log += e;
          r.log += '\n';
        }

        // Add a trailing blank line to separate this from the rest.
        //
        r.log += '\n';
      }

      // Noop, just for the log record.
      //
      change_wd (trace, &r.log, rwd);

      // Let's however distinguish the target package as a simple common case
      // and simplify the configuration creation and packages configuration
      // commands making them more readable in the build log. For this simple
      // case only one configuration needs to be created explicitly and so it
      // doesn't need the UUID. Also there is no need in any package-specific
      // options for the bpkg-pkg-build command in this case.
      //
      // Create the target configuration.
      //
      // bpkg create <env-modules> <env-config-args>
      //                           <tgt-config-args>
      //                           <pkg-config-args>
      //
      if (create_target)
      {
        step_id b  (step_id::bpkg_create);        // Breakpoint.
        step_id s  (step_id::bpkg_target_create); // Step.
        step_id f1 (step_id::b_create);           // First fallback.
        step_id f2 (step_id::bpkg_create);        // Second fallback.

        r.status |= run_bpkg (
          b,
          trace, r.log, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-V",
          "create",
          "-d", target_conf,
          (!target_pkg || config_deps (target_uuid)
           ? cstrings ({"--uuid", target_uuid})
           : cstrings ()),
          step_args (modules,  s, f1, f2),
          step_args (env_args, s, f1, f2),
          step_args (tgt_args, s, f1, f2),
          step_args (pkg_args, s, f1, f2));

        if (!r.status)
          break;
      }

      // Create the host configurations.
      //
      if (create_host)
      {
        step_id b (step_id::bpkg_create);

        if (host_pkg && selfhost)
        {
          // Create the host configuration.
          //
          {
            step_id s  (step_id::bpkg_host_create);
            step_id f1 (step_id::b_create);
            step_id f2 (step_id::bpkg_create);

            // bpkg create --type host <env-modules> <env-config-args>
            //                                       <tgt-config-args>
            //                                       <pkg-config-args>
            //
            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-V",
              "create",
              "-d", host_conf,
              "--type", "host",
              "--uuid", host_uuid,
              step_args (modules,  s, f1, f2),
              step_args (env_args, s, f1, f2),
              step_args (tgt_args, s, f1, f2),
              step_args (pkg_args, s, f1, f2));

            if (!r.status)
              break;
          }

          // Create the install configuration.
          //
          // bpkg create <env-modules> <env-config-args>
          //                           <tgt-config-args>
          //                           <pkg-config-args>
          //
          if (create_install)
          {
            step_id s  (step_id::bpkg_target_create);
            step_id f1 (step_id::b_create);
            step_id f2 (step_id::bpkg_create);

            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-V",
              "create",
              "-d", install_conf,
              "--uuid", install_uuid,
              step_args (modules,  s, f1, f2),
              step_args (env_args, s, f1, f2),
              step_args (tgt_args, s, f1, f2),
              step_args (pkg_args, s, f1, f2));

            if (!r.status)
              break;
          }
        }
        else
        {
          // b create(<dir>) config.config.load=~host-no-warnings
          //
          // Note also that we suppress warnings about unused config.* values.
          //
          r.status |= run_b (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-V",
            "create(" + host_conf.representation () + ",cc)",
            "config.config.load=~host-no-warnings",
            "config.config.persist+='config.*'@unused=drop");

          if (!r.status)
            break;

          // bpkg create --existing --type host
          //
          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "create",
            "--existing",
            "-d", host_conf,
            "--type", "host",
            "--uuid", host_uuid);

          if (!r.status)
            break;
        }
      }

      // Create the module configurations.
      //
      if (create_module)
      {
        step_id b (step_id::bpkg_create);

        // Create the module configuration.
        //
        {
          // b create(<dir>) config.config.load=~build2[-no-warnings]
          //                 [<env-config-args>
          //                  <tgt-config-args>
          //                  <pkg-config-args>]
          //
          // If the main package is not a build system module or the
          // configuration is not self-hosted, then we load the
          // ~build2-no-warnings configuration rather than ~build2.
          //
          // Note also that we suppress warnings about unused config.* values.
          //
          // What if a module wants to use CLI? The current thinking is that
          // we will be "whitelisting" base (i.e., those that can plausibly be
          // used by multiple modules) libraries and tools for use by build
          // system modules. So if and when we whitelist CLI, we will add it
          // here, next to cc.
          //
          string  mods;
          cstrings eas;
          cstrings cas;
          cstrings pas;

          if (module_pkg && selfhost)
          {
            step_id s (step_id::bpkg_module_create);

            for (const char* m: step_args (modules, s))
            {
              if (!mods.empty ())
                mods += ' ';

              mods += m;
            }

            eas = step_args (env_args, s);
            cas = step_args (tgt_args, s);
            pas = step_args (pkg_args, s);
          }
          else
            mods = "cc";

          r.status |= run_b (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-V",
            "create(" + module_conf.representation () + ',' + mods + ')',
            (module_pkg && selfhost
             ? "config.config.load=~build2"
             : "config.config.load=~build2-no-warnings"),
            "config.config.persist+='config.*'@unused=drop",
            eas,
            cas,
            pas);

          if (!r.status)
            break;

          // bpkg create --existing --type build2
          //
          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "create",
            "--existing",
            "-d", module_conf,
            "--type", "build2",
            "--uuid", module_uuid);

          if (!r.status)
            break;
        }

        // Create the install configuration.
        //
        if (create_install && module_pkg)
        {
          step_id s (step_id::bpkg_module_create);

          string mods;
          for (const char* m: step_args (modules, s))
          {
            if (!mods.empty ())
              mods += ' ';

            mods += m;
          }

          // b create(<dir>) config.config.load=~build2 <env-config-args>
          //                                            <tgt-config-args>
          //                                            <pkg-config-args>
          //
          r.status |= run_b (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-V",
            "create(" + install_conf.representation () + ',' + mods + ')',
            "config.config.load=~build2",
            "config.config.persist+='config.*'@unused=drop",
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s));

          if (!r.status)
            break;

          // bpkg create --existing
          //
          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "create",
            "--existing",
            "-d", install_conf,
            "--uuid", install_uuid);

          if (!r.status)
            break;
        }
      }

      // Link the configurations.
      //
      // bpkg link -d <dir> <dir>
      //
      {
        step_id b (step_id::bpkg_link);

        if (create_target)
        {
          if (create_host)
          {
            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-v",
              "link",
              "-d", target_conf,
              host_conf);

            if (!r.status)
              break;
          }

          if (create_module)
          {
            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-v",
              "link",
              "-d", target_conf,
              module_conf);

            if (!r.status)
              break;
          }
        }

        if (create_host)
        {
          if (create_module)
          {
            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-v",
              "link",
              "-d", host_conf,
              module_conf);

            if (!r.status)
              break;
          }
        }

        // Link the install configuration only for the host package. Note that
        // the module package may not have build-time dependencies and so
        // doesn't need configurations for them.
        //
        if (create_install && host_pkg)
        {
          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "link",
            "-d", install_conf,
            host_conf);

          if (!r.status)
            break;

          if (create_module)
          {
            r.status |= run_bpkg (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "-v",
              "link",
              "-d", install_conf,
              module_conf);

            if (!r.status)
              break;
          }
        }
      }

      // Fetch repositories into the main package configuration, the target
      // configuration for external build-time tests, if any, and the install
      // configuration, if present.
      //
      // While at it, stash the configurations where the repositories have
      // been fetched to, in order to remove the repository caches when they
      // become no longer needed to free up a bit of space.
      //
      dir_paths fetched_repo_confs;

      // bpkg add <env-config-args> <tgt-config-args> <pkg-config-args>
      //          <repository-url>
      //
      {
        step_id b (step_id::bpkg_configure_add);
        step_id s (step_id::bpkg_configure_add);

        r.status |= run_bpkg (
          b,
          trace, r.log, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "add",
          "-d", main_pkg_conf,
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          repo);

        if (!r.status)
          break;
      }

      // bpkg fetch <env-config-args> <tgt-config-args> <pkg-config-args>
      //            <trust-options>
      //
      {
        step_id b (step_id::bpkg_configure_fetch);
        step_id s (step_id::bpkg_configure_fetch);

        r.status |= run_bpkg (
          b,
          trace, r.log, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "fetch",
          "-d", main_pkg_conf,
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          trust_ops);

        if (!r.status)
          break;

        fetched_repo_confs.push_back (main_pkg_conf);
      }

      if (create_install)
      {
        // bpkg add <env-config-args> <tgt-config-args> <pkg-config-args>
        //          <repository-url>
        //
        {
          step_id b (step_id::bpkg_configure_add);
          step_id s (step_id::bpkg_configure_add);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "add",
            "-d", install_conf,
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            repo);

          if (!r.status)
            break;
        }

        // bpkg fetch <env-config-args> <tgt-config-args> <pkg-config-args>
        //            <trust-options>
        //
        {
          step_id b (step_id::bpkg_configure_fetch);
          step_id s (step_id::bpkg_configure_fetch);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "fetch",
            "-d", install_conf,
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            trust_ops);

          if (!r.status)
            break;

          fetched_repo_confs.push_back (install_conf);
        }
      }

      if (has_buildtime_tests)
      {
        // bpkg add <env-config-args> <tgt-config-args> <pkg-config-args>
        //          <repository-url>
        //
        {
          step_id b (step_id::bpkg_configure_add);
          step_id s (step_id::bpkg_configure_add);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "add",
            "-d", target_conf,
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            repo);

          if (!r.status)
            break;
        }

        // bpkg fetch <env-config-args> <tgt-config-args> <pkg-config-args>
        //            <trust-options>
        //
        {
          step_id b (step_id::bpkg_configure_fetch);
          step_id s (step_id::bpkg_configure_fetch);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "fetch",
            "-d", target_conf,
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            trust_ops);

          if (!r.status)
            break;

          fetched_repo_confs.push_back (target_conf);
        }
      }

      // Configure all the packages using a single bpkg-pkg-build command.
      //
      // First, prepare the common and package arguments.
      //
      // If no variables are specified in the package configuration, then add
      // the config.<pkg>.develop=false variable for the main package instead
      // to trigger its package skeleton creation and loading. Also add this
      // variable for the external test packages for the same purpose. This
      // way we make sure that these packages can be used as dependencies of
      // dependents with configuration clauses.
      //
      // Also add the dependency packages specified in the package
      // configuration, if any, to configurations where the main package is
      // being configured.
      //
      // Should we also add the dependency packages to configurations where
      // the test packages are being configured? It feels like we shouldn't.
      // Moreover, in the future we may decide to support specifying tests
      // package configuration in the tests manifest value or some such. In
      // this case a test package may have its own dependencies to be
      // configured. What we could probably do now, is to never share a bpkg
      // configuration between the main package and the tests packages if we
      // configure any dependencies in it. Note that such dependencies may
      // potentially be unsatisfactory for the test packages (unsatisfactory
      // version, etc). This, however, seems rather far fetched so let's keep
      // it simple for now.
      //
      strings common_args;
      strings pkgs;

      if (target_pkg) // The simple common case (see above)?
      {
        // The overall command looks like this (but some parts may be omitted):
        //
        // bpkg build --configure-only <env-config-args>
        //                             <tgt-config-args>
        //                             <pkg-config-args>
        //                             <pkg-config-opts>
        //      --
        //      { <pkg-config-vars>|config.<pkg-name>.develop=false          }+   <pkg>
        //      { <rtt-config-vars>|config.<runtime-test-name>.develop=false }+   <runtime-test>...
        //      { <dep-config-vars>                                          }+   <main-dep>...
        //                                                                        <main-dep>...
        //                                                                        <glob-dep>...
        //      { <target-config> <dep-config-vars>                          }+   <dep>...
        //      { <target-config>                                            }+ { <dep>... }
        //
        step_id s  (step_id::bpkg_target_configure_build);
        step_id f1 (step_id::b_configure);
        step_id f2 (step_id::bpkg_configure_build);

        cstrings eas (step_args (env_args, s, f1, f2));
        cstrings cas (step_args (tgt_args, s, f1, f2));
        cstrings pas (step_args (pkg_args, s, f1, f2));

        common_args.push_back ("--checkout-root");
        common_args.push_back (dist_root.string ());

        common_args.insert (common_args.end (), eas.begin (), eas.end ());
        common_args.insert (common_args.end (), cas.begin (), cas.end ());
        common_args.insert (common_args.end (), pas.begin (), pas.end ());

        // Add the main package.
        //
        pkgs.push_back ("{");

        // @@ config.<pkg>.develop=false
        //
        // Only add the config.<pkg>.develop variable if there are no package
        // configuration variables specified.
        //
        auto i (pkg_config_pkgs.find (tm.name.string ()));

        if (!pkg_config_vars.empty () || i != pkg_config_pkgs.end ())
        {
          if (!pkg_config_vars.empty ())
            pkgs.insert (pkgs.end (),
                         pkg_config_vars.begin (), pkg_config_vars.end ());

          if (i != pkg_config_pkgs.end ())
            pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());
        }
#if 1
        else
          pkgs.push_back ("config." + pkg_var + ".develop=false");
#endif

        pkgs.push_back ("}+");

        pkgs.push_back (pkg_rev);

        // Add the runtime test packages.
        //
        for (const auto& t: runtime_tests)
        {
          pkgs.push_back ("{");

          // @@ config.<pkg>.develop=false
          //
          // Only add the config.<pkg>.develop variable if there are no
          // package configuration variables specified.
          //
          auto i (pkg_config_pkgs.find (t.name.string ()));

          if (i != pkg_config_pkgs.end ())
            pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());
#if 1
          else
            pkgs.push_back ("config." + t.name.variable () + ".develop=false");
#endif

          pkgs.push_back ("}+");

          // Add test dependency package constraints (strip the potential
          // reflection variable assignment; for example 'bar > 1.0.0').
          //
          pkgs.push_back (t.dependency::string ());
        }

        // Add the main package dependencies.
        //
        for (const pair<string, strings>& d: pkg_config_main_deps)
        {
          if (!d.second.empty ())
          {
            pkgs.push_back ("{");
            pkgs.insert (pkgs.end (), d.second.begin (), d.second.end ());
            pkgs.push_back ("}+");
          }

          pkgs.push_back (d.first);
        }
      }
      else
      {
        // The overall command looks like this (but some parts may be omitted):
        //
        // bpkg build --configure-only            <env-config-args>
        //                                        <tgt-config-args>
        //                                        <pkg-config-args>
        //                                        <pkg-config-opts>
        //      --
        //      { <build-config>                  <env-config-args>
        //                                        <tgt-config-args>
        //                                        <pkg-config-args>
        //                                        <pkg-config-vars>|config.<pkg-name>.develop=false            }+   <pkg>
        //
        //      { <build-config>                  <env-config-args>
        //                                        <tgt-config-args>
        //                                        <pkg-config-args>
        //                                        <rtt-config-vars>|config.<runtime-test-name>.develop=false   }+   <runtime-test>...
        //
        //      { <install-config>                <env-config-args>
        //                                        <tgt-config-args>
        //                                        <pkg-config-args>
        //                                        <pkg-config-vars>                                            }+   <pkg>
        //
        //      { <target-config>                 <env-config-args>
        //                                        <tgt-config-args>
        //                                        <pkg-config-args>
        //                                        <btt-config-vars>|config.<buildtime-test-name>.develop=false }+   <buildtime-test>...
        //
        //      { <build-config> <install-config> <dep-config-vars>                                            }+   <main-dep>...
        //      { <build-config> <install-config>                                                              }+ { <main-dep>... }
        //                                                                                                          <glob-dep>...
        //      { <(target|host|module|install)-config> <dep-config-vars>                                      }+   <dep>...
        //      { <(target|host|module|install)-config>                                                        }+ { <dep>... }...
        //

        // Main package configuration name.
        //
        const char* conf_uuid (host_pkg ? host_uuid : module_uuid);

        // Add the main package args.
        //
        // Also add the external runtime test packages here since they share
        // the configuration directory with the main package.
        //
        {
          step_id s (target_pkg ? step_id::bpkg_target_configure_build :
                     host_pkg   ? step_id::bpkg_host_configure_build   :
                                  step_id::bpkg_module_configure_build);

          step_id f1 (step_id::b_configure);
          step_id f2 (step_id::bpkg_configure_build);

          cstrings eas (step_args (env_args, s, f1, f2));
          cstrings cas (step_args (tgt_args, s, f1, f2));
          cstrings pas (step_args (pkg_args, s, f1, f2));

          // Add the main package.
          //
          {
            pkgs.push_back ("{");

            pkgs.push_back ("--config-uuid");
            pkgs.push_back (conf_uuid);

            pkgs.push_back ("--checkout-root");
            pkgs.push_back (dist_root.string ());

            pkgs.insert (pkgs.end (), eas.begin (), eas.end ());
            pkgs.insert (pkgs.end (), cas.begin (), cas.end ());
            pkgs.insert (pkgs.end (), pas.begin (), pas.end ());

            // @@ config.<pkg>.develop=false
            //
            // Only add the config.<pkg>.develop variable if there are no
            // package configuration variables specified.
            //
            auto i (pkg_config_pkgs.find (tm.name.string ()));

            if (!pkg_config_vars.empty () || i != pkg_config_pkgs.end ())
            {
              if (!pkg_config_vars.empty ())
                pkgs.insert (pkgs.end (),
                             pkg_config_vars.begin (), pkg_config_vars.end ());

              if (i != pkg_config_pkgs.end ())
                pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());
            }
#if 1
            else
              pkgs.push_back ("config." + pkg_var + ".develop=false");
#endif

            pkgs.push_back ("}+");

            pkgs.push_back (pkg_rev);
          }

          // Add the runtime test packages.
          //
          for (const auto& t: runtime_tests)
          {
            pkgs.push_back ("{");

            pkgs.push_back ("--config-uuid");
            pkgs.push_back (conf_uuid);

            pkgs.push_back ("--checkout-root");
            pkgs.push_back (dist_root.string ());

            pkgs.insert (pkgs.end (), eas.begin (), eas.end ());
            pkgs.insert (pkgs.end (), cas.begin (), cas.end ());
            pkgs.insert (pkgs.end (), pas.begin (), pas.end ());

            // @@ config.<pkg>.develop=false
            //
            // Only add the config.<pkg>.develop variable if there are no
            // package configuration variables specified.
            //
            auto i (pkg_config_pkgs.find (t.name.string ()));

            if (i != pkg_config_pkgs.end ())
              pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());
#if 1
            else
              pkgs.push_back ("config." + t.name.variable () + ".develop=false");
#endif

            pkgs.push_back ("}+");

            // Strip the potential reflection variable assignment.
            //
            pkgs.push_back (t.dependency::string ());
          }
        }

        // Add the main package configured in the install configuration and
        // the external build-time test packages.
        //
        {
          step_id s  (step_id::bpkg_target_configure_build);
          step_id f1 (step_id::b_configure);
          step_id f2 (step_id::bpkg_configure_build);

          cstrings eas (step_args (env_args, s, f1, f2));
          cstrings cas (step_args (tgt_args, s, f1, f2));
          cstrings pas (step_args (pkg_args, s, f1, f2));

          // Add the main package.
          //
          if (create_install)
          {
            common_args.push_back ("-d");
            common_args.push_back (install_conf.string ());

            pkgs.push_back ("{");

            pkgs.push_back ("--config-uuid");
            pkgs.push_back (install_uuid);

            // Note that we do another re-distribution (with a separate
            // --checkout-root) in case the package is missing file that
            // are only used during installation.
            //
            pkgs.push_back ("--checkout-root");
            pkgs.push_back (dist_install_root.string ());

            pkgs.insert (pkgs.end (), eas.begin (), eas.end ());
            pkgs.insert (pkgs.end (), cas.begin (), cas.end ());
            pkgs.insert (pkgs.end (), pas.begin (), pas.end ());

            pkgs.insert (pkgs.end (),
                         pkg_config_vars.begin (), pkg_config_vars.end ());

            auto i (pkg_config_pkgs.find (tm.name.string ()));

            if (i != pkg_config_pkgs.end ())
              pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());

            pkgs.push_back ("}+");

            pkgs.push_back (pkg_rev);
          }

          // Add the build-time test packages.
          //
          // @@ config.<pkg>.develop=false
          //
          for (const auto& t: buildtime_tests)
          {
            pkgs.push_back ("{");

            pkgs.push_back ("--config-uuid");
            pkgs.push_back (target_uuid);

            pkgs.push_back ("--checkout-root");
            pkgs.push_back (dist_root.string ());

            pkgs.insert (pkgs.end (), eas.begin (), eas.end ());
            pkgs.insert (pkgs.end (), cas.begin (), cas.end ());
            pkgs.insert (pkgs.end (), pas.begin (), pas.end ());

            // @@ config.<pkg>.develop=false
            //
            // Only add the config.<pkg>.develop variable if there are no
            // package configuration variables specified.
            //
            auto i (pkg_config_pkgs.find (t.name.string ()));

            if (i != pkg_config_pkgs.end ())
              pkgs.insert (pkgs.end (), i->second.begin (), i->second.end ());
#if 1
            else
              pkgs.push_back ("config." + t.name.variable () + ".develop=false");
#endif

            pkgs.push_back ("}+");

            // Strip the build-time mark and potential reflection variable
            // assignment.
            //
            pkgs.push_back (t.dependency::string ());
          }
        }

        // Add the main package dependencies to those configurations where
        // the main package is configured.
        //
        {
          // Add dependencies which have some configuration variables
          // specified and count the number of others.
          //
          // ({ --config-uuid=<uuid>... <var>... }+ <pkg>)...
          //
          size_t no_vars (0);
          for (const pair<string, strings>& d: pkg_config_main_deps)
          {
            if (!d.second.empty ())
            {
              pkgs.push_back ("{");

              pkgs.push_back ("--config-uuid");
              pkgs.push_back (conf_uuid);

              if (create_install)
              {
                pkgs.push_back ("--config-uuid");
                pkgs.push_back (install_uuid);
              }

              pkgs.insert (pkgs.end (), d.second.begin (), d.second.end ());

              pkgs.push_back ("}+");

              pkgs.push_back (d.first);
            }
            else
              ++no_vars;
          }

          // Add dependencies which have no configuration variables specified.
          //
          // { --config-uuid=<uuid>... }+ { <pkg>... }
          //
          if (no_vars != 0)
          {
            pkgs.push_back ("{");

            pkgs.push_back ("--config-uuid");
            pkgs.push_back (conf_uuid);

            if (create_install)
            {
              pkgs.push_back ("--config-uuid");
              pkgs.push_back (install_uuid);
            }

            pkgs.push_back ("}+");

            if (no_vars != 1)
              pkgs.push_back ("{");

            for (const pair<string, strings>& d: pkg_config_main_deps)
            {
              if (d.second.empty ())
                pkgs.push_back (d.first);
            }

            if (no_vars != 1)
              pkgs.push_back ("}");
          }
        }
      }

      // Add the global system dependencies.
      //
      for (const pair<string, strings>& d: pkg_config_glob_deps)
        pkgs.push_back (d.first);

      // Only log configuration UUIDs if they are specified on the command
      // line.
      //
      bool log_uuids (!target_pkg);

      // Add the configuration-specific dependencies.
      //
      // Note that while it's tempting to optimize by omitting the
      // --config-uuid option for a simple target configuration only case,
      // that would change the semantics since ?sys:<dependency> would
      // potentially be configured in the private host and module
      // configurations in this case.
      //
      log_uuids = add_config_deps (target_uuid,  pkgs) || log_uuids;
      log_uuids = add_config_deps (host_uuid,    pkgs) || log_uuids;
      log_uuids = add_config_deps (module_uuid,  pkgs) || log_uuids;
      log_uuids = add_config_deps (install_uuid, pkgs) || log_uuids;

      // Finally, configure all the packages.
      //
      {
        step_id b (step_id::bpkg_configure_build);
        step_id s (step_id::bpkg_global_configure_build);

        optional<string> dependency_checksum;

        function<pre_run_function> log_uuids_func;

        if (log_uuids)
        {
          log_uuids_func = [&r, &trace,
                            target_uuid, host_uuid, module_uuid, install_uuid,
                            &log_conf_uuid] ()
          {
            log_comment   (trace, r.log, "");
            log_conf_uuid (trace, r.log, target_uuid,  "target");
            log_conf_uuid (trace, r.log, host_uuid,    "host");
            log_conf_uuid (trace, r.log, module_uuid,  "module");
            log_conf_uuid (trace, r.log, install_uuid, "install");
            log_comment   (trace, r.log, "");
          };
        }

        r.status |= run_bpkg (
          b,
          trace, r.log,
          log_uuids_func,
          dependency_checksum,
          wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "build",
          "--configure-only",
          "--rebuild-checksum",
          tm.dependency_checksum ? *tm.dependency_checksum : "",
          "--yes",
          "-d", root_conf,
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          common_args,
          pkg_config_opts,
          (has_runtime_tests || has_buildtime_tests
           ? bootstrap_import
           : nullopt),
          "--",
          pkgs);

        // The dependency checksum is tricky, here are the possibilities:
        //
        // - absent: bpkg terminated abnormally (or was not executed due to
        //           a breakpoint) -- nothing to do here.
        //
        // - empty: bpkg terminated normally with error before calculating the
        //          checksum -- nothing to do here either.
        //
        // - one line: bpkg checksum that we want.
        //
        // - many lines: someone else (e.g., buildfile) printed to stdout,
        //               which we consider an error.
        //
        if (dependency_checksum && !dependency_checksum->empty ())
        {
          string& s (*dependency_checksum);

          // Make sure that the output contains a single line, and bail out
          // with the error status if that's not the case.
          //
          if (s.find ('\n') == s.size () - 1)
          {
            s.pop_back ();

            // If the dependency checksum didn't change, then save it to the
            // result manifest, clean the logs and bail out with the skip
            // result status.
            //
            if (tm.dependency_checksum && *tm.dependency_checksum == s)
            {
              l3 ([&]{trace << "skip";});

              rm.status = result_status::skip;
              rm.dependency_checksum = move (s);
              rm.results.clear ();
              break;
            }

            // Save the (new) dependency checksum to the result manifest.
            //
            // Also note that we save the checksum if bpkg failed after the
            // checksum was printed. As a result, we won't be rebuilding the
            // package until the error is fixed (in a package or worker) and
            // the checksum changes, which feels like a proper behavior.
            //
            rm.dependency_checksum = move (s);
          }
          else
            fail_operation (r,
                            "unexpected bpkg output:\n'" + s + '\'',
                            result_status::error);
        }

        if (!r.status)
          break;

        // Now, as all the packages are configured, remove the repository
        // caches to free up the space.
        //
        for (const dir_path& d: fetched_repo_confs)
        {
          dir_path rd (d / repos_dir);
          if (exists (rd))
            rm_r (trace, &r.log, rd);
        }
      }

      // Redistribute the main package in both build and install
      // configurations, if required (test packages will be handled later).
      //
      if (exists (dist_src))
      {
        change_wd (trace, &r.log, main_pkg_conf);

        step_id b (step_id::bpkg_configure_build);

        if (!redist (b, r, dist_root, pkg_dir))
          break;
      }

      if (exists (dist_install_src))
      {
        change_wd (trace, &r.log, rwd / install_conf);

        step_id b (step_id::bpkg_configure_build);

        if (!redist (b, r, dist_install_root, pkg_dir))
          break;
      }

      rm.status |= r.status;
    }

#ifdef _WIN32
    // Give Windows a chance to (presumably) scan any files we may have just
    // unpacked. Failed that, if we try to overwrite any such file (e.g., a
    // generated header) we may end up with a permission denied error. Note
    // also that this is in addition to the 2 seconds retry we have in our
    // fdopen() implementation, which is not always enough.
    //
    Sleep (5000);
#endif

    auto fail_unreached_breakpoint = [&bkp_step, &fail_operation]
                                     (operation_result& r)
    {
      assert (bkp_step);

      fail_operation (r,
                      "interactive build breakpoint " +
                      to_string (*bkp_step) + " cannot be reached",
                      result_status::abort);
    };

    // Note that if the bpkg.update step is disabled, we also skip all the
    // test and install related steps.
    //
    if (!step_disabled (step_id::bpkg_update))
    {
      // Update the main package.
      //
      {
        operation_result& r (add_result ("update"));

        change_wd (trace, &r.log, rwd / main_pkg_conf);

        // bpkg update <env-config-args> <tgt-config-args> <pkg-config-args>
        //             <package-name>
        //
        step_id b (step_id::bpkg_update);
        step_id s (step_id::bpkg_update);

        r.status |= run_bpkg (
          b,
          trace, r.log, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "update",
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          pkg);

        if (!r.status)
          break;

        rm.status |= r.status;
      }

      b_project_info prj (
        prj_info (pkg_dir,
                  b_info_flags::ext_mods | b_info_flags::subprojects,
                  "project"));

      // If the package turned out to be non-installable, then disable all the
      // steps which may not be performed for such a package.
      //
      if (find (prj.operations.begin (),
                prj.operations.end (),
                "install") == prj.operations.end ())
      {
        install_root   = nullopt;
        bindist        = nullopt;
        sys_install    = false;
        bindist_upload = false;
      }

      // Re-distribute if comes from a version control-based repository,
      // update, and test external test packages in the bpkg configuration in
      // the current working directory. Optionally pass the config.import.*
      // variable override and/or set the environment variables for the bpkg
      // processes. Return true if all operations for all packages succeeded.
      //
      // Pass true as the installed argument to use the test separate installed
      // phase step ids (bpkg.test-separate-installed.*) and the test separate
      // phase step ids (bpkg.test-separate.*) otherwise. In both cases fall
      // back to the main phase step ids (bpkg.*) when no environment/
      // configuration arguments are specified for them.
      //
      auto test = [&trace, &wre,
                   &bkp_step, &bkp_status, &aux_env, &last_cmd,
                   &step_args, &env_args, &tgt_args, &pkg_args,
                   &bootstrap_import,
                   &redist]
        (operation_result& r,
         const small_vector<test_dependency, 1>& tests,
         const dir_path& dist_root,
         bool installed,
         bool update_only,
         const small_vector<string, 1>& envvars = {})
        {
          const optional<string>& import (!installed
                                          ? bootstrap_import
                                          : nullopt);

          for (const test_dependency& td: tests)
          {
            const string& pkg (td.name.string ());

            // Re-distribute.
            //
            if (exists (dist_root))
            {
              // Note that re-distributing the test package is a bit tricky
              // since we don't know its version and so cannot deduce its
              // source directory name easily. We could potentially run the
              // bpkg-status command after the package is configured and parse
              // the output to obtain the version. Let's, however, keep it
              // simple and find the source directory using the package
              // directory name pattern.
              //
              try
              {
                dir_path pkg_dir;

                // Note: doesn't follow symlinks.
                //
                path_search (dir_path (pkg + "-*/"),
                             [&pkg_dir] (path&& pe, const string&, bool interm)
                             {
                               if (!interm)
                                 pkg_dir = path_cast<dir_path> (move (pe));

                               return interm;
                             },
                             dist_root,
                             path_match_flags::none);

                if (!pkg_dir.empty ())
                {
                  step_id b (
                    installed
                    ? step_id::bpkg_test_separate_installed_configure_build
                    : step_id::bpkg_configure_build);

                  if (!redist (b, r, dist_root, pkg_dir, import, envvars))
                    return false;
                }
              }
              catch (const system_error& e)
              {
                fail << "unable to scan directory " << dist_root << ": " << e;
              }
            }

            // Update.
            //
            // bpkg update <env-config-args> <tgt-config-args> <pkg-config-args>
            //             <package-name>
            //
            {
              step_id b (installed
                         ? step_id::bpkg_test_separate_installed_update
                         : step_id::bpkg_test_separate_update);

              step_id s (b);

              step_id f (step_id::bpkg_update);

              r.status |= run_bpkg (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                "update",
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f),
                import,
                pkg);

              if (!r.status)
                return false;
            }

            // Test.
            //
            // Note that we assume that the package supports the test operation
            // since this is its main purpose.
            //
            // bpkg test <env-config-args> <tgt-config-args> <pkg-config-args>
            //           <package-name>
            //
            if (!update_only)
            {
              step_id b (installed
                         ? step_id::bpkg_test_separate_installed_test
                         : step_id::bpkg_test_separate_test);

              step_id s (b);

              step_id f (step_id::bpkg_test);

              r.status |= run_bpkg (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                "test",
                "--package-cwd", // See above for details.
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f),
                import,
                pkg);

              if (!r.status)
                return false;
            }

            // Now, as the external tests package is tested, clean it to free
            // up a bit of space.
            //
            {
              step_id b (installed
                         ? step_id::bpkg_test_separate_installed_test
                         : step_id::bpkg_test_separate_test);

              r.status |= run_bpkg (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-q",
                "clean",
                pkg);

              if (!r.status)
                return false;
            }
          }

          return true;
        };

      // Test the main package.
      //
      // Run the internal tests if the test operation is supported by the
      // project but only for the target package or if the configuration is
      // self-hosted.
      //
      bool has_internal_tests ((target_pkg || selfhost) &&
                               find (prj.operations.begin (),
                                     prj.operations.end (),
                                     "test") != prj.operations.end ());

      // Collect the "testable" subprojects.
      //
      // Note that while we run the package tests using the bpkg-test command,
      // we still collect the "testable" subprojects to clean them at the end
      // to free up a bit of space. We will also reuse this list for testing
      // against the installed package.
      //
      dir_paths subprj_dirs; // "Testable" package subprojects.
      strings clean_specs;   // While at it, collect the clean specs.

      for (const b_project_info::subproject& sp: prj.subprojects)
      {
        dir_path d (pkg_dir / sp.path);

        // Retrieve the subproject information similar to how we've done it
        // for the package.
        //
        b_project_info si (prj_info (d,
                                     b_info_flags::ext_mods,
                                     "subproject"));

        const strings& ops (si.operations);
        if (find (ops.begin (), ops.end (), "test") != ops.end ())
        {
          subprj_dirs.push_back (sp.path);
          clean_specs.push_back ("clean('" + d.representation () + "')");
        }
      }

      if (has_internal_tests || has_runtime_tests || has_buildtime_tests)
      {
        operation_result& r (add_result ("test"));

        // Run internal tests.
        //
        if (has_internal_tests && !step_disabled (step_id::bpkg_test))
        {
          // Use --package-cwd to help ported to build2 third-party packages a
          // bit (see bpkg-pkg-test(1) for details).
          //
          // Note that internal tests that load the module itself don't make
          // much sense, thus we don't pass the config.import.*  variable on
          // the command line for modules that require bootstrap.
          //
          // bpkg test <env-config-args> <tgt-config-args> <pkg-config-args>
          //           <package-name>
          //
          step_id b (step_id::bpkg_test);
          step_id s (step_id::bpkg_test);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "test",
            "--package-cwd",
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            pkg);

          if (!r.status)
            break;
        }
        //
        // Fail if the breakpoint refers to the bpkg.test step but the package
        // has no internal tests or this step is disabled.
        //
        else if (bkp_step && *bkp_step == step_id::bpkg_test)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        // Now, as the subprojects are tested, clean them to free up a bit of
        // space.
        //
        if (!clean_specs.empty ())
        {
          step_id b (step_id::bpkg_test);

          r.status |= run_b (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-q",
            clean_specs);

          if (!r.status)
            break;
        }

        // External tests.
        //
        // Note that if the bpkg.test-separate.update step is disabled, we
        // also skip bpkg.test-separate.test.
        //
        if ((has_runtime_tests || has_buildtime_tests) &&
            !step_disabled (step_id::bpkg_test_separate_update))
        {
          bool update_only (step_disabled (step_id::bpkg_test_separate_test));

          // Fail if the breakpoint refers to the bpkg.test-separate.test step
          // but this step is disabled.
          //
          if (update_only &&
              bkp_step    &&
              *bkp_step == step_id::bpkg_test_separate_test)
          {
            fail_unreached_breakpoint (r);
            break;
          }

          // External runtime tests.
          //
          // Note that we assume that these packages belong to the dependent
          // package's repository or its complement repositories, recursively.
          // Thus, we test them in the configuration used to build the
          // dependent package.
          //
          if (has_runtime_tests)
          {
            if (!test (r,
                       runtime_tests,
                       dist_root,
                       false /* installed */,
                       update_only))
              break;
          }

          // External build-time tests.
          //
          if (has_buildtime_tests)
          {
            change_wd (trace, &r.log, rwd / target_conf);

            if (!test (r,
                       buildtime_tests,
                       dist_root,
                       false /* installed */,
                       update_only))
              break;
          }
        }
        //
        // Fail if the breakpoint refers to some of the bpkg.test-separate.*
        // steps but the package either has no external tests or the
        // bpkg.test-separate.update step is disabled.
        //
        else if (bkp_step                                        &&
                 *bkp_step >= step_id::bpkg_test_separate_update &&
                 *bkp_step <= step_id::bpkg_test_separate_test)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to some of the test steps but the
      // package has no tests.
      //
      else if (bkp_step                        &&
               *bkp_step >= step_id::bpkg_test &&
               *bkp_step <= step_id::bpkg_test_separate_test)
      {
        fail_unreached_breakpoint (add_result ("test"));
        break;
      }

      // Install from source.
      //
      if (install_root)
      {
        operation_result& r (add_result ("install"));

        change_wd (trace, &r.log, effective_install_conf);

        // Note that for a host or module package we don't need the target
        // configuration anymore, if present. So let's free up the space a
        // little bit.
        //
        if (!target_pkg && create_target)
          rm_r (trace, &r.log, rwd / target_conf);

        // Install.
        //
        {
          // bpkg install <env-config-args> <tgt-config-args> <pkg-config-args>
          //              <package-name>
          //
          step_id b (step_id::bpkg_install);
          step_id s (step_id::bpkg_install);

          r.status |= run_bpkg (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "-v",
            "install",
            step_args (env_args, s),
            step_args (tgt_args, s),
            step_args (pkg_args, s),
            pkg);

          if (!r.status)
            break;
        }

        // Run ldconfig.
        //
        if (step_enabled (step_id::bbot_install_ldconfig))
        {
          // sudo ldconfig <env-config-args> <tgt-config-args> <pkg-config-args>
          //
          step_id b  (step_id::bbot_install_ldconfig);
          step_id s  (step_id::bbot_install_ldconfig);
          step_id ss (step_id::bbot_install_ldconfig);

          r.status |= run_ldconfig (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss));

          if (!r.status)
            break;
        }
        //
        // Fail if the breakpoint refers to the bbot.install.ldconfig step but
        // this step is disabled.
        //
        else if (bkp_step && *bkp_step == step_id::bbot_install_ldconfig)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to the bpkg.install related steps but
      // the package is not supposed to be installed from source.
      //
      else if (bkp_step                           &&
               *bkp_step >= step_id::bpkg_install &&
               *bkp_step <= step_id::bbot_install_ldconfig)
      {
        fail_unreached_breakpoint (add_result ("install"));
        break;
      }

      // Generate the binary distribution package.
      //
      // Note that if bbot.bindist.upload step is enabled, it makes sense to
      // only copy the generated binary distribution files to the
      // upload/bindist/<distribution>/ directory after the binary
      // distribution packages are testes, i.e. after the potential
      // bbot.sys-uninstall.* steps.
      //
      // The following bindist_* structures contain a subset of members of the
      // corresponding structures described in the STRUCTURED RESULT section
      // of the bpkg-pkg-bindist(1) man page. Note: needed later for
      // uninstall, upload.
      //
      struct bindist_os_release
      {
        string name_id;
        optional<string> version_id;
      };

      struct bindist_file
      {
        string type;
        bbot::path path;              // Absolute and normalized.
        optional<string> system_name;
      };

      struct bindist_package
      {
        string name;
        string version;
        optional<string> system_version;
        vector<bindist_file> files;
      };

      struct bindist_result_type
      {
        string distribution;
        string architecture;
        bindist_os_release os_release;
        bindist_package package;
        vector<bindist_package> dependencies;
      };

      bindist_result_type bindist_result;

      const dir_path& bindist_conf (
        create_install ? install_conf : main_pkg_conf);

      // Make it absolute for the sake of diagnostics.
      //
      path bindist_result_file (rwd / bindist_conf / "bindist-result.json");

      if (bindist)
      {
        operation_result& r (add_result ("bindist"));

        // Fail if the breakpoint refers to a bpkg.bindist.* step but this
        // step differs from the enabled one.
        //
        if (bkp_step                                     &&
            (*bkp_step == step_id::bpkg_bindist_debian ||
             *bkp_step == step_id::bpkg_bindist_fedora ||
             *bkp_step == step_id::bpkg_bindist_archive) &&
            *bkp_step != *bindist)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        change_wd (trace, &r.log, rwd);

        // Note that for a host or module package we don't need the target
        // configuration anymore, if present. So let's free up the space a
        // little bit.
        //
        if (!target_pkg && create_target)
          rm_r (trace, &r.log, rwd / target_conf);

        string distribution;
        dir_path output_root;

        switch (*bindist)
        {
        case step_id::bpkg_bindist_debian:
          {
            distribution = "debian";
            output_root = dir_path ("bindist");
            break;
          }
        case step_id::bpkg_bindist_fedora:
          {
            distribution = "fedora";
            break;
          }
        case step_id::bpkg_bindist_archive:
          {
            distribution = "archive";
            output_root = dir_path ("bindist");
            break;
          }
        default: assert (false);
        }

        // bpkg bindist --distribution <distribution>
        //              <env-config-args> <tgt-config-args> <pkg-config-args>
        //              <package-name>
        //
        // Note that if we are installing the result, we need to generate
        // packages for all the dependencies unless they are included in the
        // package (with --recursive). The way we are going to arrange for
        // this is by specifying --recursive=separate first and letting any
        // user --recursive option override that.
        //
        step_id b (*bindist);
        step_id s (*bindist);

        r.status |= run_bpkg (
          b,
          trace, r.log, bindist_result_file, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "bindist",
          "--distribution", distribution,
          sys_install ? cstrings ({"--recursive", "separate"}) : cstrings (),
          "--structured-result", "json",
          (!output_root.empty ()
           ? cstrings ({"--output-root", output_root.string ().c_str ()})
           : cstrings ()),
          "-d", bindist_conf,
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          pkg);

        if (!r.status)
          break;

        // Parse the structured result JSON.
        //
        try
        {
          ifdstream is (bindist_result_file);
          json::parser p (is, bindist_result_file.string ());

          using event = json::event;

          auto bad_json = [&p] (string d)
          {
            throw json::invalid_json_input (p.input_name,
                                            p.line (),
                                            p.column (),
                                            p.position (),
                                            move (d));
          };

          // Parse bindist_os_release object.
          //
          auto parse_os_release = [&p] ()
          {
            // enter: after begin_object
            // leave: after end_object

            bindist_os_release r;

            // Skip unknown/uninteresting members.
            //
            while (p.next_expect (event::name, event::end_object))
            {
              const string& n (p.name ());

              if (n == "name_id")
              {
                r.name_id = p.next_expect_string ();
              }
              else if (n == "version_id")
              {
                r.version_id = p.next_expect_string ();
              }
              else
                p.next_expect_value_skip ();
            }

            return r;
          };

          // Parse a bindist_file object.
          //
          auto parse_file = [&p, &bad_json] ()
          {
            // enter: after begin_object
            // leave: after end_object

            bindist_file r;

            // Skip unknown/uninteresting members.
            //
            while (p.next_expect (event::name, event::end_object))
            {
              const string& n (p.name ());

              if (n == "type")
              {
                r.type = p.next_expect_string ();
              }
              else if (n == "path")
              {
                try
                {
                  r.path =
                    path (p.next_expect_string ()).complete ().normalize ();
                }
                catch (const invalid_path& e)
                {
                  bad_json ("invalid package file path '" + e.path + "'");
                }
              }
              else if (n == "system_name")
              {
                r.system_name = p.next_expect_string ();
              }
              else
                p.next_expect_value_skip ();
            }

            return r;
          };

          // Parse a bindist_package object.
          //
          auto parse_package = [&p, &parse_file] ()
          {
            // enter: after begin_object
            // leave: after end_object

            bindist_package r;

            // Skip unknown/uninteresting members.
            //
            while (p.next_expect (event::name, event::end_object))
            {
              const string& n (p.name ());

              if (n == "name")
              {
                r.name = p.next_expect_string ();
              }
              else if (n == "version")
              {
                r.version = p.next_expect_string ();
              }
              else if (n == "system_version")
              {
                r.system_version = p.next_expect_string ();
              }
              else if (n == "files")
              {
                p.next_expect (event::begin_array);

                while (p.next_expect (event::begin_object, event::end_array))
                  r.files.push_back (parse_file ());
              }
              else
                p.next_expect_value_skip ();
            }

            return r;
          };

          // Parse the bindist_result.
          //
          // Note that if the bbot.bindist.upload step is enabled, then we
          // require bindist_result.os_release.version_id to be present. This
          // way the uploaded binary package can be published for a specific
          // version of the distribution.
          //
          p.next_expect (event::begin_object);

          while (p.next_expect (event::name, event::end_object))
          {
            const string& n (p.name ());

            if (n == "distribution")
            {
              bindist_result.distribution = p.next_expect_string ();

              if (bindist_result.distribution != distribution)
                bad_json ("expected distribution '" + distribution +
                          "' instead of '" + bindist_result.distribution + "'");
            }
            else if (n == "architecture")
            {
              bindist_result.architecture = p.next_expect_string ();
            }
            else if (n == "os_release")
            {
              p.next_expect (event::begin_object);
              bindist_result.os_release = parse_os_release ();

              if (!bindist_result.os_release.version_id && bindist_upload)
                bad_json ("version_id must be present if bbot.bindist.upload "
                          "step is enabled");
            }
            else if (n == "package")
            {
              p.next_expect (event::begin_object);
              bindist_result.package = parse_package ();
            }
            else if (n == "dependencies")
            {
              p.next_expect (event::begin_array);

              while (p.next_expect (event::begin_object, event::end_array))
                bindist_result.dependencies.push_back (parse_package ());
            }
            else
              p.next_expect_value_skip ();
          }
        }
        catch (const json::invalid_json_input& e)
        {
          fail_operation (
            r,
            string ("invalid bpkg-pkg-bindist result json input: ") +
            e.what (),
            result_status::abort,
            e.name,
            e.line,
            e.column);

          // Fall through.
        }
        catch (const io_error& e)
        {
          fail << "unable to read " << bindist_result_file << ": " << e;
        }

        if (!r.status)
          break;

        log_line ("generated " + distribution + " package for " + pkg + '/' +
                  ver.string () + ':',
                  r.log);

        for (const bindist_file& f: bindist_result.package.files)
          log_line ("  " + f.path.string (), r.log);

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to a bpkg.bindist.* step but this step
      // is disabled.
      //
      else if (bkp_step &&
               (*bkp_step == step_id::bpkg_bindist_debian ||
                *bkp_step == step_id::bpkg_bindist_fedora ||
                *bkp_step == step_id::bpkg_bindist_archive))
      {
        fail_unreached_breakpoint (add_result ("bindist"));
        break;
      }

      // Install from the binary distribution package generated on a
      // bpkg.bindist.* step.
      //
      if (sys_install)
      {
        operation_result& r (add_result ("sys-install"));

        // Fail if the breakpoint refers to the bbot.sys-install step since
        // it has no specific command associated.
        //
        if (bkp_step && *bkp_step == step_id::bbot_sys_install)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        // Noop, just for the log record.
        //
        change_wd (trace, &r.log, rwd);

        // Collect the binary package files.
        //
        // Specifically, for now we consider files with the system name
        // specified as package files.
        //
        cstrings pfs;

        auto add_package_files = [&pfs] (const vector<bindist_file>& bfs)
        {
          for (const bindist_file& f: bfs)
          {
            if (f.system_name)
              pfs.push_back (f.path.string ().c_str ());
          }
        };

        add_package_files (bindist_result.package.files);

        for (const bindist_package& d: bindist_result.dependencies)
          add_package_files (d.files);

        // Install for the `debian` distribution.
        //
        if (*bindist == step_id::bpkg_bindist_debian)
        {
          // Update package index.
          //
          {
            // sudo apt-get update <env-config-args>
            //                     <tgt-config-args>
            //                     <pkg-config-args>
            //
            step_id b  (step_id::bbot_sys_install_apt_get_update);
            step_id s  (step_id::bbot_sys_install_apt_get_update);
            step_id ss (step_id::bbot_sys_install_apt_get_update);

            r.status |= run_apt_get (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "update",
              "--assume-yes",
              step_args (env_args, s, nullopt, nullopt, ss),
              step_args (tgt_args, s, nullopt, nullopt, ss),
              step_args (pkg_args, s, nullopt, nullopt, ss));

            if (!r.status)
              break;
          }

          // Install.
          //
          {
            // sudo apt-get install <env-config-args>
            //                      <tgt-config-args>
            //                      <pkg-config-args>
            //                      <distribution-package-file>...
            //
            // Note that apt-get install requires a directory separator for an
            // argument to be treated as a file rather than name. The paths we
            // pass are absolute.
            //
            step_id b  (step_id::bbot_sys_install_apt_get_install);
            step_id s  (step_id::bbot_sys_install_apt_get_install);
            step_id ss (step_id::bbot_sys_install_apt_get_install);

            r.status |= run_apt_get (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              "install",
              "--assume-yes",
              step_args (env_args, s, nullopt, nullopt, ss),
              step_args (tgt_args, s, nullopt, nullopt, ss),
              step_args (pkg_args, s, nullopt, nullopt, ss),
              pfs);

            if (!r.status)
              break;
          }
        }
        //
        // Fail if the breakpoint refers to a bbot.sys-install.apt_get.* step
        // but the distribution is other than `debian`.
        //
        else if (bkp_step                                              &&
                 *bkp_step >= step_id::bbot_sys_install_apt_get_update &&
                 *bkp_step <= step_id::bbot_sys_install_apt_get_install)
        {
          fail_unreached_breakpoint (r);
          break;
        }
        //
        // Install for the `fedora` distribution.
        //
        else if (*bindist == step_id::bpkg_bindist_fedora)
        {
          // sudo dnf install <env-config-args>
          //                  <tgt-config-args>
          //                  <pkg-config-args>
          //                  <distribution-package-file>...
          //
          step_id b  (step_id::bbot_sys_install_dnf_install);
          step_id s  (step_id::bbot_sys_install_dnf_install);
          step_id ss (step_id::bbot_sys_install_dnf_install);

          r.status |= run_dnf (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "install",
            "--refresh",
            "--assumeyes",
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss),
            pfs);

          if (!r.status)
            break;
        }
        //
        // Fail if the breakpoint refers to a bbot.sys-install.dnf.* step but
        // the distribution is other than `fedora`.
        //
        else if (bkp_step && *bkp_step == step_id::bbot_sys_install_dnf_install)
        {
          fail_unreached_breakpoint (r);
          break;
        }
        //
        // Install for the `archive` distribution.
        //
        // Since there is no easy way to extract from multiple archives with a
        // single command, we run tar in a loop.
        //
        // Note that it is assumed that the --directory and --strip-components
        // options are passed via <*-config-args>. The extracted executables
        // can be arranged to be found by setting config.install.root for
        // bpkg.target.create, etc (the same way as for installing from
        // source).
        //
        else if (*bindist == step_id::bpkg_bindist_archive)
        {
          // If the bbot.sys-install:config.install.root variable is
          // specified, then make sure the directory it refers to exists by
          // the time we run `tar -xf`, so that this command doesn't fail
          // trying to extract into a non-existent directory. Note that we do
          // that regardless whether the package is a build system module or
          // not.
          //
          optional<dir_path> ir (
            config_install_root (step_id::bbot_sys_install));

          if (ir)
            mk_p (trace, &r.log, *ir, true /* sudo */);

          if (!module_pkg)
          {
            if (!ir)
              ir = config_install_root (step_id::bpkg_target_create,
                                        step_id::b_create,
                                        step_id::bpkg_create);

            if (ir)
              install_bin = *ir / dir_path ("bin");
          }

          for (const char* f: pfs)
          {
            // [sudo] tar -xf <distribution-package-file> <env-config-args>
            //                                            <tgt-config-args>
            //                                            <pkg-config-args>
            //
            step_id b  (step_id::bbot_sys_install_tar_extract);
            step_id s  (step_id::bbot_sys_install_tar_extract);
            step_id ss (step_id::bbot_sys_install_tar_extract);

            r.status |= run_tar (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              true /* sudo */,
              "-xf",
              f,
              step_args (env_args, s, nullopt, nullopt, ss),
              step_args (tgt_args, s, nullopt, nullopt, ss),
              step_args (pkg_args, s, nullopt, nullopt, ss));

            if (!r.status)
              break;
          }

          if (!r.status)
            break;

          // Run ldconfig.
          //
          if (step_enabled (step_id::bbot_sys_install_ldconfig))
          {
            // sudo ldconfig <env-config-args>
            //               <tgt-config-args>
            //               <pkg-config-args>
            //
            step_id b  (step_id::bbot_sys_install_ldconfig);
            step_id s  (step_id::bbot_sys_install_ldconfig);
            step_id ss (step_id::bbot_sys_install_ldconfig);

            r.status |= run_ldconfig (
              b,
              trace, r.log, wre,
              bkp_step, bkp_status, aux_env, last_cmd,
              step_args (env_args, s, nullopt, nullopt, ss),
              step_args (tgt_args, s, nullopt, nullopt, ss),
              step_args (pkg_args, s, nullopt, nullopt, ss));

            if (!r.status)
              break;
          }
          //
          // Fail if the breakpoint refers to the bbot.sys-install.ldconfig
          // step but this step is disabled.
          //
          else if (bkp_step && *bkp_step == step_id::bbot_sys_install_ldconfig)
          {
            fail_unreached_breakpoint (r);
            break;
          }
        }
        //
        // Fail if the breakpoint refers to a
        // bbot.sys-install.{tar.extract,ldconfig} step but the distribution
        // is other than `archive`.
        //
        else if (bkp_step &&
                 *bkp_step >= step_id::bbot_sys_install_tar_extract &&
                 *bkp_step <= step_id::bbot_sys_install_ldconfig)
        {
          fail_unreached_breakpoint (r);
          break;
        }
        else
          assert (false);

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to a bbot.sys-install.* step but this
      // step is disabled.
      //
      else if (bkp_step                               &&
               *bkp_step >= step_id::bbot_sys_install &&
               *bkp_step <= step_id::bbot_sys_install_ldconfig)
      {
        fail_unreached_breakpoint (add_result ("sys-install"));
        break;
      }

      // Now, if the package is installed, either from source or from the
      // binary distribution package, the overall plan is as follows:
      //
      // 1. If the package has subprojects that support the test operation,
      //    then configure, build, and test them out of the source tree
      //    against the installed package using the build system directly.
      //
      // 2. If any of the test packages are specified, then configure, build,
      //    and test them in a separate bpkg configuration(s) against the
      //    installed package.
      //
      if (install_root || sys_install)
      {
        // Run the internal tests if the project contains "testable"
        // subprojects, but not for a module.
        //
        has_internal_tests = !module_pkg && !subprj_dirs.empty ();

        if (has_internal_tests || has_runtime_tests || has_buildtime_tests)
        {
          operation_result& r (add_result ("test-installed"));

          change_wd (trace, &r.log, rwd);

          // Make sure that the installed package executables are properly
          // imported when configuring and running tests, unless we are testing
          // the build system module (that supposedly doesn't install any
          // executables).
          //
          small_vector<string, 1> envvars;

          if (install_bin)
          {
            // Note that we add the $config.install.root/bin directory at the
            // beginning of the PATH environment variable value, so the
            // installed executables are found first.
            //
            const string& ib (install_bin->string ());

            log_comment (trace, r.log,
                         "add " + ib + " to PATH environment variable");

            string paths ("PATH=" + ib);

            if (optional<string> s = getenv ("PATH"))
            {
              paths += path::traits_type::path_separator;
              paths += *s;
            }

            envvars.push_back (move (paths));
          }

          // Run internal tests.
          //
          if (has_internal_tests &&
              !step_disabled (step_id::b_test_installed_create))
          {
            // Create the configuration.
            //
            // b create(<dir>, <env-modules>) <env-config-args>
            //                                <tgt-config-args>
            //                                <pkg-config-args>
            //
            // Amalgamation directory that will contain configuration
            // subdirectory for package tests out of source tree build.
            //
            dir_path out_dir ("build-installed");

            {
              step_id b (step_id::b_test_installed_create);
              step_id s (step_id::b_test_installed_create);
              step_id f (step_id::b_create);

              string mods; // build2 create meta-operation parameters.

              for (const char* m: step_args (modules, s, f))
              {
                mods += mods.empty () ? ", " : " ";
                mods += m;
              }

              r.status |= run_b (
                b,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-V",
                "create('" + out_dir.representation () + '\'' + mods + ')',
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f));

              if (!r.status)
                break;
            }

            // Configure testable subprojects sequentially and test/build in
            // parallel afterwards.
            //
            // It feels right to configure internal tests also passing the
            // main package configuration variables, since they may need to
            // align with the main package setup (enable some testscripts,
            // etc).
            //
            strings test_specs;
            strings clean_specs;
            for (const dir_path& d: subprj_dirs)
            {
              // b configure(<subprj-src-dir>@<subprj-out-dir>) <env-config-args>
              //                                                <tgt-config-args>
              //                                                <pkg-config-args>
              //                                                <pkg-vars>
              //
              step_id b (step_id::b_test_installed_configure);
              step_id s (step_id::b_test_installed_configure);
              step_id f (step_id::b_configure);

              dir_path subprj_src_dir (exists (dist_src)
                                       ? dist_src / d
                                       : main_pkg_conf / pkg_dir / d);

              dir_path subprj_out_dir (out_dir / d);

              r.status |= run_b (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                "configure('" +
                subprj_src_dir.representation () + "'@'" +
                subprj_out_dir.representation () + "')",
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f),
                pkg_config_vars);

              if (!r.status)
                break;

              string rp (subprj_out_dir.representation ());

              test_specs.push_back ("test('" + rp + "')");
              clean_specs.push_back ("clean('" + rp + "')");
            }

            if (!r.status)
              break;

            // Build/test subprojects.
            //
            // b test(<subprj-out-dir>)... <env-config-args>
            //                             <tgt-config-args>
            //                             <pkg-config-args>
            //
            if (!step_disabled (step_id::b_test_installed_test))
            {
              step_id b (step_id::b_test_installed_test);
              step_id s (step_id::b_test_installed_test);

              r.status |= run_b (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                test_specs,
                step_args (env_args, s),
                step_args (tgt_args, s),
                step_args (pkg_args, s));

              if (!r.status)
                break;

              // Now, as the subprojects are tested, clean them to free up a
              // bit of space.
              //
              r.status |= run_b (
                b,
                envvars,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-q",
                clean_specs);

              if (!r.status)
                break;
            }
            //
            // Fail if the breakpoint refers to the b.test-installed.test step
            // but this step is disabled.
            //
            else if (bkp_step && *bkp_step == step_id::b_test_installed_test)
            {
              fail_unreached_breakpoint (r);
              break;
            }
          }
          //
          // Fail if the breakpoint refers to some of the b.test-installed.*
          // steps but the package doesn't have any internal tests or the
          // b.test-installed.create step is disabled.
          //
          else if (bkp_step                                      &&
                   *bkp_step >= step_id::b_test_installed_create &&
                   *bkp_step <= step_id::b_test_installed_test)
          {
            fail_unreached_breakpoint (r);
            break;
          }

          // Run runtime and build-time tests.
          //
          // Note that we only build runtime tests for target packages and for
          // host packages in self-hosted configurations.
          //
          if ((has_runtime_tests || has_buildtime_tests) &&
              !step_disabled (step_id::bpkg_test_separate_installed_create))
          {
            // Stash the absolute path of the initial build target
            // configuration.
            //
            const dir_path& init_target_conf (target_conf);

            // Create the required build configurations.
            //
            dir_path target_conf ("build-installed-bpkg");
            dir_path host_conf   ("build-installed-bpkg-host");
            dir_path module_conf ("build-installed-bpkg-module");

            // Create the target configuration if this is a target package
            // having external runtime tests or a host/module package having
            // external build-time tests.
            //
            bool create_target (target_pkg || has_buildtime_tests);

            // Note that even if there are no runtime tests for a host/module
            // package, we still need to create the host/build2 configuration
            // to configure the system package in.
            //
            bool create_host (host_pkg || module_pkg);

            bool create_module (module_pkg ||
                                (host_pkg && has_buildtime_tests));

            // Note: a module package cannot have runtime tests and so the
            // module configuration is only created to serve build-time tests.
            // Thus, the host or target configuration is always created as
            // well and the module configuration is never a root
            // configuration.
            //
            assert (create_target || create_host);

            // Root configuration through which we will be configuring the
            // cluster.
            //
            const dir_path& root_conf (create_target ? target_conf : host_conf);

            // Runtime tests configuration. Should only be used if there are
            // any.
            //
            const dir_path& runtime_tests_conf (target_pkg
                                                ? target_conf
                                                : host_conf);

            // Create the target configuration.
            //
            // bpkg create <env-modules> <env-config-args>
            //                           <tgt-config-args>
            //                           <pkg-config-args>
            //
            if (create_target)
            {
              step_id b (step_id::bpkg_test_separate_installed_create);

              // Note that here and below the _for_* step ids are determined
              // by the main package type (and, yes, that means we will use
              // the same step ids for target and host configuration -- that,
              // however, should be ok since host configuration will only be
              // created in the self-hosted case).
              //
              step_id s (
                target_pkg
                ? step_id::bpkg_test_separate_installed_create_for_target
                : host_pkg
                  ? step_id::bpkg_test_separate_installed_create_for_host
                  : step_id::bpkg_test_separate_installed_create_for_module);

              // Note: no fallback for modules.
              //
              optional<step_id> f (!module_pkg
                                   ? step_id::bpkg_test_separate_installed_create
                                   : optional<step_id> ());

              r.status |= run_bpkg (
                b,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-V",
                "create",
                "-d", target_conf,
                (config_deps (target_installed_uuid)
                 ? cstrings ({"--uuid", target_installed_uuid})
                 : cstrings ()),
                step_args (modules,  s, f),
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f));

              if (!r.status)
                break;
            }

            // Create the host configuration.
            //
            if (create_host)
            {
              // bpkg create --type host <env-modules> <env-config-args>
              //                                       <tgt-config-args>
              //                                       <pkg-config-args>
              //
              step_id b (step_id::bpkg_test_separate_installed_create);

              step_id s (host_pkg
                         ? step_id::bpkg_test_separate_installed_create_for_host
                         : step_id::bpkg_test_separate_installed_create_for_module);

              // Note: no fallback for modules.
              //
              optional<step_id> f (!module_pkg
                                   ? step_id::bpkg_test_separate_installed_create
                                   : optional<step_id> ());

              r.status |= run_bpkg (
                b,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-V",
                "create",
                "-d", host_conf,
                "--type", "host",
                "--name", "host",
                (config_deps (host_installed_uuid)
                 ? cstrings ({"--uuid", host_installed_uuid})
                 : cstrings ()),
                step_args (modules,  s, f),
                step_args (env_args, s, f),
                step_args (tgt_args, s, f),
                step_args (pkg_args, s, f));

              if (!r.status)
                break;
            }

            // Create the module configuration.
            //
            // Note that we never build any tests in it but only configure the
            // system package. Note, however, that the host/module package
            // build-time tests can potentially build some other modules here.
            //
            if (create_module)
            {
              // b create(<dir>) config.config.load=~build2-no-warnings
              //
              step_id b (step_id::bpkg_test_separate_installed_create);

              r.status |= run_b (
                b,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-V",
                "create(" + module_conf.representation () + ",cc)",
                "config.config.load=~build2-no-warnings",
                "config.config.persist+='config.*'@unused=drop");

              if (!r.status)
                break;

              // bpkg create --existing --type build2
              //
              r.status |= run_bpkg (
                b,
                trace, r.log, wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                "create",
                "--existing",
                "-d", module_conf,
                "--type", "build2",
                "--name", "module",
                (config_deps (module_installed_uuid)
                 ? cstrings ({"--uuid", module_installed_uuid})
                 : cstrings ()));

              if (!r.status)
                break;
            }

            // Link the configurations.
            //
            // bpkg link -d <dir> <dir>
            //
            {
              step_id b (step_id::bpkg_test_separate_installed_link);

              if (create_target)
              {
                if (create_host)
                {
                  r.status |= run_bpkg (
                    b,
                    trace, r.log, wre,
                    bkp_step, bkp_status, aux_env, last_cmd,
                    "-v",
                    "link",
                    "-d", target_conf,
                    host_conf);

                  if (!r.status)
                    break;
                }

                if (create_module)
                {
                  r.status |= run_bpkg (
                    b,
                    trace, r.log, wre,
                    bkp_step, bkp_status, aux_env, last_cmd,
                    "-v",
                    "link",
                    "-d", target_conf,
                    module_conf);

                  if (!r.status)
                    break;
                }

                // If for the target package the initial build target
                // configuration contains the private host and/or module
                // configurations, then it may mean that the external
                // (runtime) tests for this package use some tools and/or
                // modules. Not to rebuild them again for the test install
                // case, we will just link these private configurations to the
                // installed test target configuration. This way the external
                // tests, built and executed against the installed main
                // package, can reuse the already built tools and/or modules.
                //
                if (target_pkg)
                {
                  dir_path hc (init_target_conf / host_dir);

                  if (exists (hc))
                  {
                    r.status |= run_bpkg (
                      b,
                      trace, r.log, wre,
                      bkp_step, bkp_status, aux_env, last_cmd,
                      "-v",
                      "link",
                      "-d", target_conf,
                      hc);

                    if (!r.status)
                      break;
                  }

                  dir_path mc (init_target_conf / build2_dir);

                  if (exists (mc))
                  {
                    r.status |= run_bpkg (
                      b,
                      trace, r.log, wre,
                      bkp_step, bkp_status, aux_env, last_cmd,
                      "-v",
                      "link",
                      "-d", target_conf,
                      mc);

                    if (!r.status)
                      break;
                  }
                }
              }

              if (create_host)
              {
                if (create_module)
                {
                  r.status |= run_bpkg (
                    b,
                    trace, r.log, wre,
                    bkp_step, bkp_status, aux_env, last_cmd,
                    "-v",
                    "link",
                    "-d", host_conf,
                    module_conf);

                  if (!r.status)
                    break;
                }
              }
            }

            // Add and fetch the repositories.
            //
            // Stash fetched repositories as above.
            //
            dir_paths fetched_repo_confs;

            if (has_runtime_tests)
            {
              // bpkg add <env-config-args> <tgt-config-args> <pkg-config-args>
              //          <repository-url>
              //
              {
                step_id b (step_id::bpkg_test_separate_installed_configure_add);
                step_id s (step_id::bpkg_test_separate_installed_configure_add);
                step_id f (step_id::bpkg_configure_add);

                r.status |= run_bpkg (
                  b,
                  trace, r.log, wre,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  "-v",
                  "add",
                  "-d", runtime_tests_conf,
                  step_args (env_args, s, f),
                  step_args (tgt_args, s, f),
                  step_args (pkg_args, s, f),
                  repo);

                if (!r.status)
                  break;
              }

              // bpkg fetch <env-config-args> <tgt-config-args> <pkg-config-args>
              //            <trust-options>
              //
              {
                step_id b (step_id::bpkg_test_separate_installed_configure_fetch);
                step_id s (step_id::bpkg_test_separate_installed_configure_fetch);
                step_id f (step_id::bpkg_configure_fetch);

                r.status |= run_bpkg (
                  b,
                  trace, r.log, wre,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  "-v",
                  "fetch",
                  "-d", runtime_tests_conf,
                  step_args (env_args, s, f),
                  step_args (tgt_args, s, f),
                  step_args (pkg_args, s, f),
                  trust_ops);

                if (!r.status)
                  break;

                fetched_repo_confs.push_back (runtime_tests_conf);
              }
            }

            if (has_buildtime_tests)
            {
              // bpkg add <env-config-args> <tgt-config-args> <pkg-config-args>
              //          <repository-url>
              //
              {
                step_id b (step_id::bpkg_test_separate_installed_configure_add);
                step_id s (step_id::bpkg_test_separate_installed_configure_add);
                step_id f (step_id::bpkg_configure_add);

                r.status |= run_bpkg (
                  b,
                  trace, r.log, wre,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  "-v",
                  "add",
                  "-d", target_conf,
                  step_args (env_args, s, f),
                  step_args (tgt_args, s, f),
                  step_args (pkg_args, s, f),
                  repo);

                if (!r.status)
                  break;
              }

              // bpkg fetch <env-config-args> <tgt-config-args> <pkg-config-args>
              //            <trust-options>
              //
              {
                step_id b (step_id::bpkg_test_separate_installed_configure_fetch);
                step_id s (step_id::bpkg_test_separate_installed_configure_fetch);
                step_id f (step_id::bpkg_configure_fetch);

                r.status |= run_bpkg (
                  b,
                  trace, r.log, wre,
                  bkp_step, bkp_status, aux_env, last_cmd,
                  "-v",
                  "fetch",
                  "-d", target_conf,
                  step_args (env_args, s, f),
                  step_args (tgt_args, s, f),
                  step_args (pkg_args, s, f),
                  trust_ops);

                if (!r.status)
                  break;

                fetched_repo_confs.push_back (target_conf);
              }
            }

            // Configure all the packages using a single bpkg-pkg-build command.
            //
            // bpkg build --configure-only <env-config-args> <tgt-config-args> <pkg-config-args>
            //      { <build-installed-config>                <rtt-config-vars> }+   <runtime-test>...
            //      { <build-installed-config>                                  }+ { <runtime-test>... }
            //      {                                         <btt-config-vars> }+   <buildtime-test>...
            //                                                                       ?sys:<pkg>
            //                                                                       <glob-dep>...
            //      { <(target|host|module)-installed-config> <dep-config-vars> }+   <dep>...
            //      { <(target|host|module)-installed-config>                   }+ { <dep>... }...
            //
            strings pkgs;

            if (has_runtime_tests)
            {
              // Note that only host package runtime tests can (but not
              // necessarily) be configured in a linked configuration and
              // require --config-name to be specified for them.
              //
              assert (!module_pkg);

              string conf_name (runtime_tests_conf == root_conf
                                ? ""
                                : "host");

              // If there are any runtime tests with configuration variables,
              // then add them to the command line as following:
              //
              // { --config-name <name> <config-var>... }+ <runtime-test>...
              //
              // Also count the number of runtime tests without configuration
              // variables.
              //
              size_t no_vars (0);
              for (const auto& t: runtime_tests)
              {
                auto i (pkg_config_pkgs.find (t.name.string ()));

                if (i != pkg_config_pkgs.end ())
                {
                  pkgs.push_back ("{");

                  if (!conf_name.empty ())
                  {
                    pkgs.push_back ("--config-name");
                    pkgs.push_back (conf_name);
                  }

                  pkgs.insert (pkgs.end (),
                               i->second.begin (), i->second.end ());

                  pkgs.push_back ("}+");

                  // Strip the potential reflection variable assignment.
                  //
                  pkgs.push_back (t.dependency::string ());
                }
                else
                  ++no_vars;
              }

              // If there are any runtime tests without configuration
              // variables, then add them to the command line as following:
              //
              // { --config-name <name> }+ { <runtime-test>... }
              //
              if (no_vars != 0)
              {
                bool og (!conf_name.empty ());

                if (og)
                {
                  pkgs.push_back ("{");

                  pkgs.push_back ("--config-name");
                  pkgs.push_back (conf_name);

                  pkgs.push_back ("}+");
                }

                if (og && no_vars != 1)
                  pkgs.push_back ("{");

                for (const auto& t: runtime_tests)
                {
                  if (pkg_config_pkgs.find (t.name.string ()) ==
                      pkg_config_pkgs.end ())
                  {
                    // Strip the potential reflection variable assignment.
                    //
                    pkgs.push_back (t.dependency::string ());
                  }
                }

                if (og && no_vars != 1)
                  pkgs.push_back ("}");
              }
            }

            if (has_buildtime_tests)
            {
              for (const auto& t: buildtime_tests)
              {
                auto i (pkg_config_pkgs.find (t.name.string ()));

                if (i != pkg_config_pkgs.end ())
                {
                  pkgs.push_back ("{");

                  pkgs.insert (pkgs.end (),
                               i->second.begin (), i->second.end ());

                  pkgs.push_back ("}+");
                }

                // Strip the build-time mark and potential reflection variable
                // assignment.
                //
                pkgs.push_back (t.dependency::string ());
              }
            }

            pkgs.push_back ("?sys:" + pkg_rev);

            // Add the global system dependencies.
            //
            for (const pair<string, strings>& d: pkg_config_glob_deps)
              pkgs.push_back (d.first);

            // Only log configuration UUIDs if they are specified on the
            // command line.
            //
            bool log_uuids (false);

            // Add the configuration-specific dependencies.
            //
            log_uuids = add_config_deps (target_installed_uuid, pkgs) || log_uuids;
            log_uuids = add_config_deps (host_installed_uuid,   pkgs) || log_uuids;
            log_uuids = add_config_deps (module_installed_uuid, pkgs) || log_uuids;

            // Finally, configure all the test packages.
            //
            {
              step_id b (step_id::bpkg_test_separate_installed_configure_build);

              step_id g (step_id::bpkg_global_configure_build); // Global.

              step_id s (
                target_pkg
                ? step_id::bpkg_test_separate_installed_configure_build_for_target
                  : host_pkg
                  ? step_id::bpkg_test_separate_installed_configure_build_for_host
                  : step_id::bpkg_test_separate_installed_configure_build_for_module);

              step_id f (step_id::bpkg_test_separate_installed_configure_build);

              function<pre_run_function> log_uuids_func;

              if (log_uuids)
              {
                log_uuids_func = [&r, &trace,
                                  target_installed_uuid,
                                  host_installed_uuid,
                                  module_installed_uuid,
                                  &log_conf_uuid] ()
                  {
                    log_comment   (trace, r.log, "");
                    log_conf_uuid (trace, r.log, target_installed_uuid, "target installed");
                    log_conf_uuid (trace, r.log, host_installed_uuid,   "host installed");
                    log_conf_uuid (trace, r.log, module_installed_uuid, "module installed");
                    log_comment   (trace, r.log, "");
                  };
              }

              r.status |= run_bpkg (
                b,
                envvars,
                trace, r.log,
                log_uuids_func,
                wre,
                bkp_step, bkp_status, aux_env, last_cmd,
                "-v",
                "build",
                "--configure-only",
                "--checkout-root", dist_installed_root,
                "--yes",
                "-d", root_conf,
                step_args (env_args, g),
                step_args (env_args, s, f),
                step_args (tgt_args, g),
                step_args (tgt_args, s, f),
                step_args (pkg_args, g),
                step_args (pkg_args, s, f),
                "--",
                pkgs);

              if (!r.status)
                break;

              // Now, as all the packages are configured, remove the
              // repository caches to free up the space.
              //
              for (const dir_path& d: fetched_repo_confs)
              {
                dir_path rd (d / repos_dir);
                if (exists (rd))
                  rm_r (trace, &r.log, rd);
              }
            }

#ifdef _WIN32
            Sleep (5000); // See above.
#endif

            // Note that if bpkg.test-separate-installed.update step is
            // disabled, we also skip bpkg.test-separate-installed.test.
            //
            if (!step_disabled (step_id::bpkg_test_separate_installed_update))
            {
              bool update_only (
                step_disabled (step_id::bpkg_test_separate_installed_test));

              // Fail if the breakpoint refers to the
              // bpkg.test-separate-installed.test step but this step is
              // disabled.
              //
              if (update_only &&
                  bkp_step    &&
                  *bkp_step == step_id::bpkg_test_separate_installed_test)
              {
                fail_unreached_breakpoint (r);
                break;
              }

              // External runtime tests.
              //
              if (has_runtime_tests)
              {
                const dir_path& runtime_tests_conf (target_pkg
                                                    ? target_conf
                                                    : host_conf);

                change_wd (trace, &r.log, runtime_tests_conf);

                if (!test (r,
                           runtime_tests,
                           dist_installed_root,
                           true /* installed */,
                           update_only,
                           envvars))
                  break;
              }

              // External build-time tests.
              //
              if (has_buildtime_tests)
              {
                change_wd (trace, &r.log, rwd / target_conf);

                if (!test (r,
                           buildtime_tests,
                           dist_installed_root,
                           true /* installed */,
                           update_only,
                           envvars))
                  break;
              }
            }
            //
            // Fail if the breakpoint refers to some of the
            // bpkg.test-separate-installed.{update,test} steps but the
            // bpkg.test-separate-installed.update step is disabled.
            //
            else if (bkp_step                                                  &&
                     *bkp_step >= step_id::bpkg_test_separate_installed_update &&
                     *bkp_step <= step_id::bpkg_test_separate_installed_test)
            {
              fail_unreached_breakpoint (r);
              break;
            }
          }
          //
          // Fail if the breakpoint refers to some of the
          // bpkg.test-separate-installed.* steps but the package has no
          // external tests or the bpkg.test-separate-installed.create step is
          // disabled.
          //
          else if (bkp_step                                                  &&
                   *bkp_step >= step_id::bpkg_test_separate_installed_create &&
                   *bkp_step <= step_id::bpkg_test_separate_installed_test)
          {
            fail_unreached_breakpoint (r);
            break;
          }

          rm.status |= r.status;
        }
        //
        // Fail if the breakpoint refers to some of the test installed steps
        // but the package has no tests.
        //
        else if (bkp_step                                      &&
                 *bkp_step >= step_id::b_test_installed_create &&
                 *bkp_step <= step_id::bpkg_test_separate_installed_test)
        {
          fail_unreached_breakpoint (add_result ("test-installed"));
          break;
        }
      }
      //
      // Fail if the breakpoint refers to some of the test installed steps but
      // the package is not supposed to be installed neither from source nor
      // from the binary distribution package.
      //
      else if (bkp_step                                      &&
               *bkp_step >= step_id::b_test_installed_create &&
               *bkp_step <= step_id::bpkg_test_separate_installed_test)
      {
        fail_unreached_breakpoint (add_result ("test-installed"));
        break;
      }

      // Uninstall, if installed from the binary distribution package.
      //
      // Note: noop for the archive distribution.
      //
      if (sys_install &&
          (*bindist == step_id::bpkg_bindist_debian ||
           *bindist == step_id::bpkg_bindist_fedora))
      {
        operation_result& r (add_result ("sys-uninstall"));

        // Noop, just for the log record.
        //
        change_wd (trace, &r.log, rwd);

        // Collect the binary package system names.
        //
        cstrings pns;

        auto add_package_names = [&pns] (const vector<bindist_file>& bfs)
        {
          for (const bindist_file& f: bfs)
          {
            if (f.system_name)
              pns.push_back (f.system_name->c_str ());
          }
        };

        add_package_names (bindist_result.package.files);

        for (const bindist_package& d: bindist_result.dependencies)
          add_package_names (d.files);

        // Uninstall for the `debian` distribution.
        //
        if (*bindist == step_id::bpkg_bindist_debian)
        {
          // sudo apt-get remove <env-config-args>
          //                     <tgt-config-args>
          //                     <pkg-config-args>
          //                     <distribution-package-name>...
          //
          step_id b  (step_id::bbot_sys_uninstall_apt_get_remove);
          step_id s  (step_id::bbot_sys_uninstall_apt_get_remove);
          step_id ss (step_id::bbot_sys_uninstall_apt_get_remove);

          r.status |= run_apt_get (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "remove",
            "--assume-yes",
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss),
            pns);

          if (!r.status)
            break;
        }
        //
        // Fail if the breakpoint refers to the
        // bbot.sys-uninstall.apt-get.remove step but the distribution is
        // other than `debian`.
        //
        else if (bkp_step &&
                 *bkp_step == step_id::bbot_sys_uninstall_apt_get_remove)
        {
          fail_unreached_breakpoint (r);
          break;
        }
        //
        // Uninstall for the `fedora` distribution.
        //
        else if (*bindist == step_id::bpkg_bindist_fedora)
        {
          // sudo dnf remove <env-config-args>
          //                 <tgt-config-args>
          //                 <pkg-config-args>
          //                 <distribution-package-name>...
          //
          step_id b  (step_id::bbot_sys_uninstall_dnf_remove);
          step_id s  (step_id::bbot_sys_uninstall_dnf_remove);
          step_id ss (step_id::bbot_sys_uninstall_dnf_remove);

          r.status |= run_dnf (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            "remove",
            "--assumeyes",
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss),
            pns);

          if (!r.status)
            break;
        }
        //
        // Fail if the breakpoint refers to the bbot.sys-uninstall.dnf.remove
        // step but the distribution is other than `fedora`.
        //
        else if (bkp_step &&
                 *bkp_step == step_id::bbot_sys_uninstall_dnf_remove)
        {
          fail_unreached_breakpoint (r);
          break;
        }
        else
          assert (false);

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to a bbot.sys-uninstall.* step but
      // this step is disabled.
      //
      else if (bkp_step                                                &&
               *bkp_step >= step_id::bbot_sys_uninstall_apt_get_remove &&
               *bkp_step <= step_id::bbot_sys_uninstall_dnf_remove)
      {
        fail_unreached_breakpoint (add_result ("sys-uninstall"));
        break;
      }

      // Uninstall, if installed from source.
      //
      if (install_root)
      {
        operation_result& r (add_result ("uninstall"));

        change_wd (trace, &r.log, effective_install_conf);

        // bpkg uninstall <env-config-args> <tgt-config-args> <pkg-config-args>
        //                <package-name>
        //
        step_id b (step_id::bpkg_uninstall);
        step_id s (step_id::bpkg_uninstall);

        r.status |= run_bpkg (
          b,
          trace, r.log, wre,
          bkp_step, bkp_status, aux_env, last_cmd,
          "-v",
          "uninstall",
          step_args (env_args, s),
          step_args (tgt_args, s),
          step_args (pkg_args, s),
          pkg);

        if (!r.status)
          break;

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to the bpkg.uninstall step but the
      // package was not installed from source.
      //
      else if (bkp_step && *bkp_step == step_id::bpkg_uninstall)
      {
        fail_unreached_breakpoint (add_result ("uninstall"));
        break;
      }

      // Now, after the package is fully tested, let's prepare the build
      // artifacts for the upload, using the upload operation log.
      //

      // Prepare the bindist artifacts.
      //
      // Move the binary distribution files generated for the main package and
      // bindist-result.json to the upload/bindist/<distribution>/ directory.
      // Also serialize the subset of the bindist result as
      // bindist-result.manifest.
      //
      // Fail if the breakpoint refers to the bbot.bindist.upload step since
      // it has no specific command associated.
      //
      if (bkp_step && *bkp_step == step_id::bbot_bindist_upload)
      {
        fail_unreached_breakpoint (add_result ("upload"));
        break;
      }

      if (bindist_upload)
      {
        operation_result& r (add_result ("upload"));

        change_wd (trace, &r.log, rwd);

        dir_path d (upload_dir           /
                    dir_path ("bindist") /
                    dir_path (bindist_result.distribution));

        log_step_id (trace, r.log, step_id::bbot_bindist_upload);

        mk_p (trace, &r.log, d);

        // Move a file to the upload/bindist/<distribution>/ directory.
        //
        // On Windows copy the file instead of moving not to fail if it is
        // being scanned by the Windows Defender or some such.
        //
        auto mv = [&d, &r, &rwd, &trace] (const path& p)
        {
#ifndef _WIN32
          bool mv (true);
#else
          bool mv (false);
#endif
          // Use relative path, if possible, to keep the operation log tidy
          // (won't be the case on Fedora).
          //
          const path& rp (p.sub (rwd) ? p.leaf (rwd) : p);

          if (mv)
            mv_into (trace, &r.log, rp, d);
          else
            cp_into (trace, &r.log, rp, d);
        };

        // Main package files.
        //
        for (const bindist_file& f: bindist_result.package.files)
          mv (f.path);

        // Bindist result JSON.
        //
        mv (bindist_result_file);

        // Bindist result manifest.
        //
        path mf (d / "bindist-result.manifest");

        try
        {
          ofdstream os (mf);
          serializer s (os, mf.string ());

          // Serialize package manifest.
          //
          s.next ("", "1"); // Start of manifest.

          s.next ("distribution", bindist_result.distribution);
          s.next ("architecture", bindist_result.architecture);

          s.next ("os-release-name-id", bindist_result.os_release.name_id);

          // Should have failed earlier.
          //
          assert (bindist_result.os_release.version_id);

          s.next ("os-release-version-id",
                  *bindist_result.os_release.version_id);

          s.next ("package-name", bindist_result.package.name);
          s.next ("package-version", bindist_result.package.version);

          if (bindist_result.package.system_version)
            s.next ("package-system-version",
                    *bindist_result.package.system_version);

          s.next ("", "");  // End of manifest.

          // Serialize package file manifests.
          //
          for (const bindist_file& f: bindist_result.package.files)
          {
            s.next ("", "1"); // Start of manifest.

            s.next ("package-file-type", f.type);

            // Note: the simple path representation is POSIX.
            //
            s.next ("package-file-path", f.path.leaf ().string ());

            if (f.system_name)
              s.next ("package-file-system-name", *f.system_name);

            s.next ("", "");  // End of manifest.
          }

          s.next ("", ""); // End of stream.

          os.close ();
        }
        catch (const io_error& e)
        {
          fail << "unable to write to '" << mf << "': " << e;
        }
        catch (const serialization& e)
        {
          fail << "unable to serialize bindist result: " << e;
        }
      }

      // Create the archive of the build artifacts for subsequent upload, if
      // the upload/ directory is not empty.
      //
      // Note that the archive will be uploaded later, right before uploading
      // the result manifest, unless the task has been aborted by the user or
      // the result status is error or worse.
      //
      if (!empty (rwd / upload_dir) && !step_disabled (step_id::bbot_upload))
      {
        // The upload operation log must have been added as part of the
        // build artifacts preparation for upload.
        //
        operation_result& r (rm.results.back ());

        // Fail if the breakpoint refers to the bbot.upload step since it has
        // no specific command associated.
        //
        if (bkp_step && *bkp_step == step_id::bbot_upload)
        {
          fail_unreached_breakpoint (r);
          break;
        }

        change_wd (trace, &r.log, rwd);

        // Archive the build artifacts.
        //
        {
          // tar -cf upload.tar <env-config-args>
          //                    <tgt-config-args>
          //                    <pkg-config-args>
          //         upload/
          //
          step_id b  (step_id::bbot_upload_tar_create);
          step_id s  (step_id::bbot_upload_tar_create);
          step_id ss (step_id::bbot_upload_tar_create);

          // Make sure the archive is portable.
          //
          // Note that OpenBSD tar does not support --format but it appear
          // ustar is the default (see bpkg/system-package-manager-archive.cxx
          // for details).
          //
          r.status |= run_tar (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            false /* sudo */,
#ifndef __OpenBSD__
            "--format", "ustar",
#endif
            "-cf",
            upload_archive,
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss),
            upload_dir);

          if (!r.status)
            break;
        }

        // It feels useful to also print the archive content to the log.
        //
        {
          // tar -tf upload.tar <env-config-args>
          //                    <tgt-config-args>
          //                    <pkg-config-args>
          //
          step_id b  (step_id::bbot_upload_tar_list);
          step_id s  (step_id::bbot_upload_tar_list);
          step_id ss (step_id::bbot_upload_tar_list);

          r.status |= run_tar (
            b,
            trace, r.log, wre,
            bkp_step, bkp_status, aux_env, last_cmd,
            false /* sudo */,
            "-tf",
            upload_archive,
            step_args (env_args, s, nullopt, nullopt, ss),
            step_args (tgt_args, s, nullopt, nullopt, ss),
            step_args (pkg_args, s, nullopt, nullopt, ss));

          if (!r.status)
            break;
        }

        rm.status |= r.status;
      }
      //
      // Fail if the breakpoint refers to some of the bbot.upload.* steps but
      // there is either nothing to upload or the bbot.upload step is
      // disabled.
      //
      else if (bkp_step                          &&
               *bkp_step >= step_id::bbot_upload &&
               *bkp_step <= step_id::bbot_upload_tar_list)
      {
        // If the upload operation log have been added as part of the build
        // artifacts preparation for upload, then use this log to report the
        // error. Otherwise, add the new log for that.
        //
        operation_result* pr (&rm.results.back ());

        if (pr->operation != "upload")
          pr = &add_result ("upload");

        fail_unreached_breakpoint (*pr);
        break;
      }
    }
    //
    // Fail if the breakpoint refers to bpkg.update or any dependent step but
    // the bpkg.update step is disabled.
    //
    else if (bkp_step                          &&
             *bkp_step >= step_id::bpkg_update &&
             *bkp_step <= step_id::bbot_upload)
    {
      fail_unreached_breakpoint (add_result ("update"));
      break;
    }

    break;
  }

  if (!rm.results.empty ())
  {
    operation_result& r (rm.results.back ());

    rm.status |= r.status; // Merge last in case of a break.

    // Unless there is an error (or worse) encountered, log the special 'end'
    // step and, if this step is specified in the interactive manifest value,
    // ask the user if to continue the task execution.
    //
    bool error (!rm.status);

    if (!error)
    {
      r.status |= run_cmd (step_id::end,
                           trace, r.log,
                           nullptr /* out_str */, path () /* out_file */,
                           regexes (),
                           "" /* name */,
                           bkp_step, bkp_status, aux_env, last_cmd,
                           process_env ());

      rm.status |= r.status;
    }

    // Truncate logs if they would exceed the upload limit.
    //
    // @@ TMP: currently this limit is hard-coded. In the future it should be
    //    sent along with the task manifest.
    //
    const size_t upload_limit (15 * 1024 * 1024);
    {
      // Reserve 10K for other manifest values (alternatively, we could do it
      // exactly in upload_manifest()).
      //
      const size_t manifest_size (10 * 1024);

      size_t n (manifest_size);
      for (const operation_result& r: rm.results)
        n += r.log.size ();

      if (n > upload_limit)
      {
        // Divide the size equally among all the operations and truncate any
        // that exceed their allowance. This way we will get some information
        // for each operation.
        //
        n = (upload_limit - manifest_size) / rm.results.size ();

        for (operation_result& r: rm.results)
        {
          if (r.log.size () <= n)
            continue;

          // We need to be careful not to truncate it in the middle of UTF-8
          // sequence. So we look for the last newline that still fits.
          //
          size_t p (n - 80 /* for the "log truncated" note */);
          for (; p != 0 && r.log[p] != '\n'; --p) ;
          r.log.resize (p != 0 ? p + 1 : 0); // Keep the newline.
          r.log += "-------------------------------LOG TRUNCATED-------------------------------\n";
        }
      }
    }
  }
  else
    assert (rm.status == result_status::abort ||
            rm.status == result_status::skip);

  if (!rwd.empty ())
  {
    change_wd (trace, nullptr /* log */, rwd);

    // Upload the build artifacts archive, if exists.
    //
    bool error (!rm.status);
    if (exists (upload_archive) && !error)
    {
      const string url (
        "tftp://" + ops.tftp_host () + '/' + upload_archive.string ());

      try
      {
        tftp_curl c (trace,
                     upload_archive,
                     nullfd,
                     curl::put,
                     url,
                     "--tftp-blksize", tftp_blksize,
                     "--max-time", tftp_put_timeout);

        if (!c.wait ())
          fail << "curl " << *c.exit;
      }
      catch (const process_error& e)
      {
        fail << "unable to execute curl: " << e;
      }
      catch (const system_error& e)
      {
        fail << "unable to upload build artifacts to " << url << ": " << e;
      }
    }
  }

  // Upload the result.
  //
  const string url ("tftp://" + ops.tftp_host () + "/result.manifest.lz4");

  try
  {
    upload_manifest (trace, url, rm, "result");

    // We use exit code 2 to signal abnormal termination but where we managed
    // to upload the result manifest. See startup() for details.
    //
    return rm.status != result_status::abnormal ? 0 : 2;
  }
  //
  // We use exit code 3 to signal an unsuccessful attempt to upload the result
  // manifest and exit code 4 to singal that there was no disk space to
  // serialize the manifest. See startup() for details.
  //
  catch (const io_error& e)
  {
    error << "unable to upload result manifest to " << url << ": " << e;
    return 3;
  }
  catch (const system_error& e)
  {
    assert (e.code ().category () == std::generic_category () &&
            e.code ().value () == ENOSPC);

    error << "unable to serialize result manifest: " << e;
    return 4;
  }
}

// Parse the task_manifest::auxiliary_environment value into the list of
// environment variable assignments as expected by the process API. Throw
// invalid_argument if the auxiliary environment is invalid.
//
// If comment is not NULL, then add blank and comment lines prefixed with this
// string (which is normally either '#' or 'rem'). This mode is used to print
// the environment into the build log.
//
static strings
parse_auxiliary_environment (const string& s, const char* comment = nullptr)
{
  strings r;

  // Note: parse observing blanks.
  //
  for (size_t b (0), e (0), m (0), n (s.size ());
       next_word (s, n, b, e, m, '\n', '\r'), b != n; )
  {
    string line (s, b, e - b);

    if (trim (line).empty ()) // Blank.
    {
      if (comment != nullptr)
        r.push_back (comment);

      continue;
    }

    if (line.front () == '#') // Comment.
    {
      if (comment != nullptr)
      {
        line.erase (0, 1);
        line.insert (0, comment);
        r.push_back (move (line));
      }

      continue;
    }

    size_t p (line.find ('='));

    if (p == string::npos)
      throw invalid_argument ("missing '=' in '" + line + '\'');

    string name (line, 0, p);

    if (trim_right (name).empty () ||
        name.find_first_not_of (
          "ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") != string::npos)
    {
      throw invalid_argument ("invalid variable name '" + name + '\'');
    }

    // Disallow certain well-known environment variables.
    //
    if (name == "PATH"
#if   defined(_WIN32)
#elif defined(__APPLE__)
        || name == "DYLD_LIBRARY_PATH"
#else // Linux, FreeBSD, NetBSD, OpenBSD
        || name == "LD_LIBRARY_PATH"
#endif
    )
    {
      throw invalid_argument ("disallowed variable name '" + name + '\'');
    }

    line.erase (0, p + 1); // Value.

    // Note: we allow empty values.
    //
    if (!trim_left (line).empty ())
    {
      // Unquote.
      //
      char c (line.front ());
      if (c == '"' || c == '\'')
      {
        if (line.size () == 1 || line.back () != c)
          throw invalid_argument ("invalid quoted value '" + line + '\'');

        line.pop_back ();
        line.erase (0, 1);
      }
    }

    // Reassemble.
    //
    line.insert (0, 1, '=');
    line.insert (0, name);

    r.push_back (move (line));
  }

  // Pop the final blank line comment.
  //
  if (comment != nullptr && r.back () == comment)
    r.pop_back ();

  return r;
}

static int
startup ()
{
  tracer trace ("startup");

  // Our overall plan is as follows:
  //
  // 1. Download the task manifest into the build directory (CWD).
  //
  // 2. Parse it and get the target, environment name, and auxiliary
  //    environment.
  //
  // 3. Find the environment setup executable for this name.
  //
  // 4. Execute the environment setup executable for this target in the
  //    auxiliary environment.
  //
  // 5. If the environment setup executable fails, then upload the (failed)
  //    result ourselves.
  //
  const string url ("tftp://" + ops.tftp_host () + "/task.manifest");
  const path mf ("task.manifest");

  // If we fail, try to upload the result manifest (abnormal termination). The
  // idea is that the machine gets suspended and we can investigate what's
  // going on by logging in and examining the diagnostics (e.g., via
  // journalctl, etc).
  //
  task_manifest tm;

  auto upload_result = [&trace, &tm] (result_status rs,
                                      operation_results&& ors,
                                      bool disk = true)
  {
    const string url ("tftp://" + ops.tftp_host () + "/result.manifest.lz4");

    // If we failed before being able to parse the task manifest, use the
    // "unknown" values for the package name and version.
    //
    result_manifest rm {
      tm.name.empty ()    ? bpkg::package_name ("unknown") : tm.name,
      tm.version.empty () ? bpkg::version ("0")            : tm.version,
      rs,
      move (ors),
      worker_checksum,
      nullopt /* dependency_checksum */
    };

    try
    {
      upload_manifest (trace, url, rm, "result", disk);
    }
    catch (const io_error& e)
    {
      fail << "unable to upload result manifest to " << url << ": " << e;
    }
    catch (const system_error& e)
    {
      fail << "unable to serialize result manifest: " << e;
    }
  };

  try
  {
    // Download the task.
    //
    // We are downloading from our host so there shouldn't normally be any
    // connectivity issues. Unless, of course, we are on Windows where all
    // kinds of flakiness is business as usual. Note that having a long enough
    // timeout is not enough: if we try to connect before the network is up,
    // we will keep waiting forever, even after it is up. So we have to
    // timeout and try again. This is also pretty bad (unlike, say during
    // bootstrap which doesn't happen very often) since we are wasting the
    // machine time. So we are going to log it as a warning and not merely a
    // trace since if this is a common occurrence, then something has to be
    // done about it.
    //
    for (size_t retry (1);; ++retry)
    {
      try
      {
        tftp_curl c (trace,
                     nullfd,
                     mf,
                     curl::get,
                     url,
                     "--tftp-blksize", tftp_blksize,
                     "--max-time", tftp_get_timeout);

        if (!c.wait ())
          throw_generic_error (EIO);

        break;
      }
      catch (const system_error& e)
      {
        bool bail (retry > tftp_get_retries);
        diag_record dr (bail ? error : warn);

        dr << "unable to download task manifest from " << url << " on "
           << retry << " try: " << e;

        if (bail)
          throw failed ();
      }
    }

    // Parse it.
    //
    tm = parse_manifest<task_manifest> (mf, "task");

    // Find the environment setup executable.
    //
    // While the executable path contains a directory (so the PATH search does
    // not apply) we still use process::path_search() to automatically handle
    // appending platform-specific executable extensions (.exe/.bat, etc).
    //
    process_path pp;

    if (tm.environment)
    {
      try
      {
        pp = process::try_path_search (env_dir / *tm.environment,
                                       false /* init */);
      }
      catch (const invalid_path& e)
      {
        fail << "invalid environment name '" << e.path << "': " << e;
      }

      if (pp.empty ())
        fail << "no environment setup executable in " << env_dir << " "
             << "for environment name '" << *tm.environment << "'";
    }
    else
    {
      pp = process::try_path_search (env_dir / "default", false /* init */);

      if (pp.empty ())
        fail << "no default environment setup executable in " << env_dir;
    }

    // Auxiliary environment.
    //
    strings aux_env;
    if (tm.auxiliary_environment)
    {
      try
      {
        aux_env = parse_auxiliary_environment (*tm.auxiliary_environment);
      }
      catch (const invalid_argument& e)
      {
        // Note: include (unparsed) environment into the log so that we can
        // see what we are dealing with.
        //
        operation_result r {
          "configure",
          result_status::abort,
          *tm.auxiliary_environment + "\n" +
          "error: invalid auxiliary environment: " + e.what () + '\n'};

        upload_result (result_status::abort, {move (r)});
        return 1;
      }
    }

    // Run it.
    //
    strings os;

    string tg (tm.target.string ());

    // Use the name=value notation for options to minimize the number of
    // arguments passed to the environment setup executable. Note that the
    // etc/environments/default-*.bat scripts can only handle the limited
    // number of arguments.
    //
    if (ops.systemd_daemon ())
      os.push_back ("--systemd-daemon");

    if (ops.verbose_specified ())
      os.push_back ("--verbose=" + to_string (ops.verbose ()));

    if (ops.tftp_host_specified ())
      os.push_back ("--tftp-host=" + ops.tftp_host ());

    os.push_back (string ("--env-script=") + pp.effect_string ());
    os.push_back ("--env-target=" + tg);

    // Note that we use the effective (absolute) path instead of recall since
    // we may have changed the CWD.
    //
    // Also note that the worker can ask the user if to continue the task
    // execution when the interactive build breakpoint is reached. Thus, we
    // don't redirect stdin to /dev/null.
    //
    // Exit code 1 signals abnormal worker termination.
    //
    // Exit code 2 signals abnormal termination but where the worker uploaded
    // the result itself.
    //
    // Exit code 3 signals an unsuccessful attempt by the worker to upload the
    // result manifest. There is no reason to retry (most likely there is
    // nobody listening on the other end anymore).
    //
    // Exit code 4 signals the inability to serialize the result manifest due
    // to insufficient disk space.
    //
    switch (run_io_exit (trace,
                         0 /* stdin */, 2 /* stdout */, 2 /* stderr */,
                         process_env (pp, aux_env),
                         tg,
                         argv0.effect_string (),
                         os))
    {
    case 4:
      {
        // Note that while it may seem like abnormal is the more appropriate
        // result, experience shows running out of disk space is not that
        // uncommon and suspending the machine every time we hit this makes it
        // unusable for the rest of the users.
        //
        operation_result r {
          "configure",
          result_status::abort,
          "error: no disk space left to serialize result manifest\n"};

        upload_result (result_status::abort, {move (r)}, false /* disk */);
        return 1;
      }
    case 3:
    case 2:  return 1;
    case 0:  return 0;
    default: fail << "process " << pp << " exited with non-zero code" << endf;
    }
  }
  catch (const failed&)
  {
    upload_result (result_status::abnormal, operation_results {});
    return 1;
  }
}

static int
bootstrap ()
{
  bootstrap_manifest bm {
    bootstrap_manifest::versions_type {
      {"bbot",    standard_version (BBOT_VERSION_STR)},
      {"libbbot", standard_version (LIBBBOT_VERSION_STR)},
      {"libbpkg", standard_version (LIBBPKG_VERSION_STR)},
      {"libbutl", standard_version (LIBBUTL_VERSION_STR)}
    }
  };

  serialize_manifest (bm, cout, "stdout", "bootstrap");

  return 0;
}

int bbot::
main (int argc, char* argv[])
try
{
  tracer trace ("main");

  // This is a little hack to make our baseutils for Windows work when called
  // with absolute path. In a nutshell, MSYS2's exec*p() doesn't search in the
  // parent's executable directory, only in PATH. And since we are running
  // without a shell (that would read /etc/profile which sets PATH to some
  // sensible values), we are only getting Win32 PATH values. And MSYS2 /bin
  // is not one of them. So what we are going to do is add /bin at the end of
  // PATH (which will be passed as is by the MSYS2 machinery). This will make
  // MSYS2 search in /bin (where our baseutils live). And for everyone else
  // this should be harmless since it is not a valid Win32 path.
  //
#ifdef _WIN32
  {
    string mp;
    if (optional<string> p = getenv ("PATH"))
    {
      mp = move (*p);
      mp += ';';
    }
    mp += "/bin";

    setenv ("PATH", mp);
  }
#endif

  // On POSIX ignore SIGPIPE which is signaled to a pipe-writing process if
  // the pipe reading end is closed. Note that by default this signal
  // terminates a process. Also note that there is no way to disable this
  // behavior on a file descriptor basis or for the write() function call.
  //
  // On Windows disable displaying error reporting dialog box. Note that the
  // error mode is inherited by child processes.
  //
#ifndef _WIN32
  if (signal (SIGPIPE, SIG_IGN) == SIG_ERR)
    fail << "unable to ignore broken pipe (SIGPIPE) signal: "
         << system_error (errno, std::generic_category ()); // Sanitize.
#else
  SetErrorMode (SetErrorMode (0) | // Returns the current mode.
                SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif

  cli::argv_scanner scan (argc, argv, true);
  ops.parse (scan);

  verb = ops.verbose ();

  // @@ systemd 231 added JOURNAL_STREAM environment variable which allows
  //    detecting if stderr is connected to the journal.
  //
  if (ops.systemd_daemon ())
    systemd_diagnostics (false);

  // Version.
  //
  if (ops.version ())
  {
    cout << "bbot-worker " << BBOT_VERSION_ID << endl
         << "libbbot " << LIBBBOT_VERSION_ID << endl
         << "libbpkg " << LIBBPKG_VERSION_ID << endl
         << "libbutl " << LIBBUTL_VERSION_ID << endl
         << "Copyright (c) " << BBOT_COPYRIGHT << "." << endl
         << "This is free software released under the MIT license." << endl;

    return 0;
  }

  // Help.
  //
  if (ops.help ())
  {
    pager p ("bbot-worker help", false);
    print_bbot_worker_usage (p.stream ());

    // If the pager failed, assume it has issued some diagnostics.
    //
    return p.wait () ? 0 : 1;
  }

  // Figure out our mode.
  //
  if (ops.bootstrap () && ops.startup ())
    fail << "--bootstrap and --startup are mutually exclusive";

  enum class mode {boot, start, build} m (mode::build);

  if (ops.bootstrap ()) m = mode::boot;
  if (ops.startup ())   m = mode::start;

  if (ops.systemd_daemon ())
  {
    info << "bbot worker " << BBOT_VERSION_ID;
  }

  // Figure out our path (used for re-exec).
  //
  argv0 = process::path_search (argv[0], true);

  // Sort out the build directory.
  //
  if (ops.build_specified ())
    change_wd (trace,
               nullptr /* log */,
               ops.build (),
               true /* create */);

  // Sort out the environment directory.
  //
  try
  {
    env_dir = ops.environments_specified ()
      ? ops.environments ()
      : dir_path::home_directory ();

    if (!dir_exists (env_dir))
      throw_generic_error (ENOENT);
  }
  catch (const system_error& e)
  {
    fail << "invalid environment directory: " << e;
  }

  int r (1);
  switch (m)
  {
  case mode::boot:  r = bootstrap ();                            break;
  case mode::start: r = startup ();                              break;
  case mode::build: r = build (static_cast<size_t> (argc),
                               const_cast<const char**> (argv)); break;
  }

  return r;
}
catch (const failed&)
{
  return 1; // Diagnostics has already been issued.
}
catch (const cli::exception& e)
{
  error << e;
  return 1;
}

int
main (int argc, char* argv[])
{
  return bbot::main (argc, argv);
}