File: zkg

package info (click to toggle)
zkg 2.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 1,444 kB
  • sloc: python: 5,114; sh: 270; makefile: 265; cpp: 24
file content (2744 lines) | stat: -rwxr-xr-x 100,779 bytes parent folder | download
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
#! /usr/bin/env python3

import argparse
import configparser
import errno
import filecmp
import io
import json
import logging
import os
import shutil
import subprocess
import sys
import threading

from collections import OrderedDict

try:
    import git
    import semantic_version as semver # lgtm[py/unused-import]
except ImportError as error:
    print("error: zkg failed to import one or more dependencies:\n"
          "\n"
          "* GitPython:        https://pypi.org/project/GitPython\n"
          "* semantic-version: https://pypi.org/project/semantic-version\n"
          "\n"
          "If you use 'pip', they can be installed like:\n"
          "\n"
          "     pip3 install GitPython semantic-version\n"
          "\n"
          "Also check the following exception output for possible alternate explanations:\n\n"
          "{}: {}".format(type(error).__name__, error),
          file=sys.stderr)
    sys.exit(1)

# For Zeek-bundled installation, prepend the Python path of the Zeek
# installation. This ensures we find the matching zeekpkg module
# first, avoiding potential conflicts with installations elsewhere on
# the system.
ZEEK_PYTHON_DIR = '@PY_MOD_INSTALL_DIR@'
if os.path.isdir(ZEEK_PYTHON_DIR):
    sys.path.insert(0, os.path.abspath(ZEEK_PYTHON_DIR))
else:
    ZEEK_PYTHON_DIR = None

# Similarly, make Zeek's binary installation path available by
# default. This helps package installations succeed that require
# e.g. zeek-config for their build process.
ZEEK_BIN_DIR = '@ZEEK_BIN_DIR@'
if os.path.isdir(ZEEK_BIN_DIR):
    try:
        if ZEEK_BIN_DIR not in os.environ['PATH'].split(os.pathsep):
            os.environ['PATH'] = ZEEK_BIN_DIR + os.pathsep + os.environ['PATH']
    except KeyError:
        os.environ['PATH'] = ZEEK_BIN_DIR
else:
    ZEEK_BIN_DIR = None

# Also when bundling with Zeek, use directories in the install tree
# for storing the zkg configuration and its variable state. Support
# for overrides via environment variables simplifies testing.
ZEEK_ZKG_CONFIG_DIR = os.getenv('ZEEK_ZKG_CONFIG_DIR') or '@ZEEK_ZKG_CONFIG_DIR@'
if not os.path.isdir(ZEEK_ZKG_CONFIG_DIR):
    ZEEK_ZKG_CONFIG_DIR = None

ZEEK_ZKG_STATE_DIR = os.getenv('ZEEK_ZKG_STATE_DIR') or '@ZEEK_ZKG_STATE_DIR@'
if not os.path.isdir(ZEEK_ZKG_STATE_DIR):
    ZEEK_ZKG_STATE_DIR = None

# The default package source we fall back to as needed
ZKG_DEFAULT_SOURCE = 'https://github.com/zeek/packages'

# The default package template
ZKG_DEFAULT_TEMPLATE = 'https://github.com/zeek/package-template'

from zeekpkg._util import (
    delete_path,
    make_dir,
    make_symlink,
    find_program,
    read_zeek_config_line,
    std_encoding,
)
from zeekpkg.package import (
    TRACKING_METHOD_VERSION,
)
from zeekpkg.template import (
    LoadError,
    Template,
)
from zeekpkg.uservar import (
    UserVar,
)

import zeekpkg


def confirmation_prompt(prompt, default_to_yes=True):
    yes = {'y', 'ye', 'yes'}

    if default_to_yes:
        prompt += ' [Y/n] '
    else:
        prompt += ' [N/y] '

    choice = input(prompt).lower()

    if not choice:
        if default_to_yes:
            return True
        else:
            print('Abort.')
            return False

    if choice in yes:
        return True

    print('Abort.')
    return False


def prompt_for_user_vars(manager, config, configfile, args, pkg_infos):
    answers = {}

    for info in pkg_infos:
        name = info.package.qualified_name()
        requested_user_vars = info.user_vars()

        if requested_user_vars is None:
            print_error(str.format('error: malformed user_vars in "{}"', name))
            sys.exit(1)

        for uvar in requested_user_vars:
            try:
                answers[uvar.name()] = uvar.resolve(name, config, args.user_var, args.force)
            except ValueError:
                print_error(str.format('error: could not determine value of user variable "{}",'
                                       ' provide via environment or --user-var', uvar.name()))
                sys.exit(1)

    if not args.force and answers:
        for key, value in answers.items():
            if not config.has_section('user_vars'):
                config.add_section('user_vars')

            config.set('user_vars', key, value)

        if configfile:
            with io.open(configfile, 'w', encoding=std_encoding(sys.stdout)) as f:
                config.write(f)

            print('Saved answers to config file: {}'.format(configfile))

    manager.user_vars = answers


def print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


def config_items(config, section):
    # Same as config.items(section), but exclude default keys.
    defaults = {key for key, _ in config.items('DEFAULT')}
    items = sorted(config.items(section))
    return [(key, value) for (key, value) in items if key not in defaults]


def file_is_not_empty(path):
    return os.path.isfile(path) and os.path.getsize(path) > 0


def find_configfile(args):
    if args.user:
        configfile = os.path.join(home_config_dir(), 'config')

        if file_is_not_empty(configfile):
            return configfile

        return None

    configfile = os.environ.get('ZKG_CONFIG_FILE')

    if not configfile:
        # For backward compatibility with old bro-pkg.
        configfile = os.environ.get('BRO_PKG_CONFIG_FILE')

    if configfile and file_is_not_empty(configfile):
        return configfile

    configfile = os.path.join(default_config_dir(), 'config')

    if file_is_not_empty(configfile):
        return configfile

    configfile = os.path.join(legacy_config_dir(), 'config')

    if file_is_not_empty(configfile):
        return configfile

    return None


def home_config_dir():
    return os.path.join(os.path.expanduser('~'), '.zkg')


def default_config_dir():
    return ZEEK_ZKG_CONFIG_DIR or home_config_dir()


def legacy_config_dir():
    return os.path.join(os.path.expanduser('~'), '.bro-pkg')


def default_state_dir():
    return ZEEK_ZKG_STATE_DIR or home_config_dir()


def legacy_state_dir():
    return os.path.join(os.path.expanduser('~'), '.bro-pkg')


def create_config(args, configfile):
    config = configparser.ConfigParser()

    if configfile:
        if not os.path.isfile(configfile):
            print_error('error: invalid config file "{}"'.format(configfile))
            sys.exit(1)

        config.read(configfile)

    if not config.has_section('sources'):
        config.add_section('sources')

    if not config.has_section('paths'):
        config.add_section('paths')

    if not config.has_section('templates'):
        config.add_section('templates')

    if not configfile:
        default = os.getenv('ZKG_DEFAULT_SOURCE', ZKG_DEFAULT_SOURCE)
        if default:
            config.set('sources', 'zeek', default)

    if not configfile or not config.has_option('templates', 'default'):
        default = os.getenv('ZKG_DEFAULT_TEMPLATE', ZKG_DEFAULT_TEMPLATE)
        if default:
            config.set('templates', 'default', default)

    def config_option_set(config, section, option):
        return config.has_option(section, option) and config.get(section,
                                                                 option)

    def get_option(config, section, option, default):
        if config_option_set(config, section, option):
            return config.get(section, option)

        return default

    if args.user:
        def_state_dir = home_config_dir()
    else:
        def_state_dir = default_state_dir()

    state_dir = get_option(config, 'paths', 'state_dir',
                           os.path.join(def_state_dir))
    script_dir = get_option(config, 'paths', 'script_dir',
                            os.path.join(state_dir, 'script_dir'))
    plugin_dir = get_option(config, 'paths', 'plugin_dir',
                            os.path.join(state_dir, 'plugin_dir'))
    bin_dir = get_option(config, 'paths', 'bin_dir',
                         os.path.join(state_dir, 'bin'))
    zeek_dist = get_option(config, 'paths', 'zeek_dist', '')

    if not zeek_dist:
        zeek_dist = get_option(config, 'paths', 'bro_dist', '')

    config.set('paths', 'state_dir', state_dir)
    config.set('paths', 'script_dir', script_dir)
    config.set('paths', 'plugin_dir', plugin_dir)
    config.set('paths', 'bin_dir', bin_dir)
    config.set('paths', 'zeek_dist', zeek_dist)

    def expand_config_values(config, section):
        for key, value in config.items(section):
            value = os.path.expandvars(os.path.expanduser(value))
            config.set(section, key, value)

    expand_config_values(config, 'sources')
    expand_config_values(config, 'paths')
    expand_config_values(config, 'templates')

    for key, value in config.items('paths'):
        if value and not os.path.isabs(value):
            print_error(str.format('error: invalid config file value for key'
                                   ' "{}" in section [paths]: "{}" is not'
                                   ' an absolute path', key, value))
            sys.exit(1)

    return config


def active_git_branch(path):
    try:
        repo = git.Repo(path)
    except git.exc.NoSuchPathError as error:
        return None

    if not repo.working_tree_dir:
        return None

    try:
        rval = repo.active_branch
    except TypeError as error:
        # return detached commit
        rval = repo.head.commit

    if not rval:
        return None

    rval = str(rval)
    return rval


def is_local_git_repo_url(git_url):
    return git_url.startswith('.') or git_url.startswith('/')


def is_local_git_repo(git_url):
    try:
        # The Repo class takes a file system path as first arg. This
        # can fail in two ways: (1) the path doesn't exist or isn't
        # accessible, (2) it's not the root directory of a git repo.
        git.Repo(git_url)
        return True
    except (git.exc.InvalidGitRepositoryError, git.exc.NoSuchPathError) as error:
        return False


def is_local_git_repo_dirty(git_url):
    if not is_local_git_repo(git_url):
        return False
    try:
        repo = git.Repo(git_url)
    except git.exc.NoSuchPathError as error:
        return False

    return repo.is_dirty(untracked_files=True)


def check_local_git_repo(git_url):
    if is_local_git_repo_url(git_url):
        if not is_local_git_repo(git_url):
            print_error('error: path {} is not a git repository'.format(git_url))
            return False
        if is_local_git_repo_dirty(git_url):
            print_error('error: local git clone at {} is dirty'.format(git_url))
            return False

    return True


def create_manager(args, config):
    state_dir = config.get('paths', 'state_dir')
    script_dir = config.get('paths', 'script_dir')
    plugin_dir = config.get('paths', 'plugin_dir')
    bin_dir = config.get('paths', 'bin_dir')
    zeek_dist = config.get('paths', 'zeek_dist')

    if state_dir == default_state_dir():
        if not os.path.exists(state_dir) and os.path.exists(legacy_state_dir()):
            make_symlink(legacy_state_dir(), state_dir)

    try:
        manager = zeekpkg.Manager(state_dir=state_dir, script_dir=script_dir,
                                 plugin_dir=plugin_dir, bin_dir=bin_dir,
                                 zeek_dist=zeek_dist)
    except (OSError, IOError) as error:
        if error.errno == errno.EACCES:
            print_error('{}: {}'.format(type(error).__name__, error))

            def check_permission(d):
                if os.access(d, os.W_OK):
                    return True

                print_error(
                    'error: user does not have write access in {}'.format(d))
                return False

            permissions_trouble = not all([check_permission(state_dir),
                                           check_permission(script_dir),
                                           check_permission(plugin_dir),
                                           check_permission(bin_dir)])

            if permissions_trouble and not args.user:
                print_error(
                    'Consider the --user flag to manage zkg state via {}/config'
                    .format(home_config_dir()))
            sys.exit(1)

        raise

    extra_sources = []

    for key_value in args.extra_source or []:
        if "=" not in key_value:
            print_error('warning: invalid extra source: "{}"'.format(key_value))
            continue

        key, value = key_value.split("=", 1)

        if not key or not value:
            print_error('warning: invalid extra source: "{}"'.format(key_value))
            continue

        extra_sources.append((key, value))

    for key, value in extra_sources + config_items(config, 'sources'):
        error = manager.add_source(name=key, git_url=value)

        if error:
            print_error(str.format(
                'warning: skipped using package source named "{}": {}',
                key, error))

    return manager


def get_changed_state(manager, saved_state, pkg_lst):
    """Returns the list of packages that have changed loaded state.

    Args:
        saved_state (dict): dictionary of saved load state for installed
        packages.

        pkg_lst (list): list of package names to be skipped

    Returns:
        dep_listing (str): string installed packages that have changed state

    """
    _lst = [zeekpkg.package.name_from_path(_pkg_path) for _pkg_path in pkg_lst]
    dep_listing = ''

    for _pkg_name in sorted(manager.installed_package_dependencies()):
        if _pkg_name in _lst:
            continue

        _ipkg = manager.find_installed_package(_pkg_name)

        if not _ipkg or _ipkg.status.is_loaded == saved_state[_pkg_name]:
            continue

        dep_listing += '  {}\n'.format(_pkg_name)

    return dep_listing


class InstallWorker(threading.Thread):

    def __init__(self, manager, package_name, package_version):
        super(InstallWorker, self).__init__()
        self.manager = manager
        self.package_name = package_name
        self.package_version = package_version
        self.error = ''

    def run(self):
        self.error = self.manager.install(
            self.package_name, self.package_version)


def cmd_test(manager, args, config, configfile):
    if args.version and len(args.package) > 1:
        print_error(
            'error: "install --version" may only be used for a single package')
        sys.exit(1)

    package_infos = []

    for name in args.package:
        if not check_local_git_repo(name):
            sys.exit(1)

        version = args.version if args.version else active_git_branch(name)
        package_info = manager.info(name, version=version,
                                    prefer_installed=False)

        if package_info.invalid_reason:
            print_error(str.format('error: invalid package "{}": {}', name,
                                   package_info.invalid_reason))
            sys.exit(1)

        if not version:
            version = package_info.best_version()

        package_infos.append((package_info, version))

    all_passed = True

    for info, version in package_infos:
        name = info.package.qualified_name()

        if 'test_command' not in info.metadata:
            print(str.format('{}: no test_command found in metadata, skipping',
                             name))
            continue

        error_msg, passed, test_dir = manager.test(name, version)

        if error_msg:
            all_passed = False
            print_error(str.format('error: failed to run tests for "{}": {}',
                                   name, error_msg))
            continue

        if passed:
            print(str.format('{}: all tests passed', name))
        else:
            all_passed = False
            clone_dir = os.path.join(os.path.join(test_dir, "clones"),
                                     info.package.name)
            print_error(str.format('error: package "{}" tests failed, inspect'
                                   ' contents of {} for details, especially'
                                   ' any "zkg.test_command.{{stderr,stdout}}"'
                                   ' files within {}',
                                   name, test_dir, clone_dir))

    if not all_passed:
        sys.exit(1)


def cmd_install(manager, args, config, configfile):
    if args.version and len(args.package) > 1:
        print_error(
            'error: "install --version" may only be used for a single package')
        sys.exit(1)

    package_infos = []

    for name in args.package:
        if not check_local_git_repo(name):
            sys.exit(1)

        version = args.version if args.version else active_git_branch(name)
        package_info = manager.info(name, version=version,
                                    prefer_installed=False)

        if package_info.invalid_reason:
            print_error(str.format('error: invalid package "{}": {}', name,
                                   package_info.invalid_reason))
            sys.exit(1)

        if not version:
            version = package_info.best_version()

        package_infos.append((package_info, version, False))

    orig_pkgs, new_pkgs = package_infos, []

    if not args.nodeps:
        to_validate = [(info.package.qualified_name(), version)
                       for info, version, _ in package_infos]
        invalid_reason, new_pkgs = manager.validate_dependencies(
            to_validate, ignore_suggestions=args.nosuggestions)

        if invalid_reason:
            print_error('error: failed to resolve dependencies:',
                        invalid_reason)
            sys.exit(1)

    if not args.force:
        package_listing = ''

        for info, version, _ in sorted(package_infos, key=lambda x: x[0].package.name):
            name = info.package.qualified_name()
            package_listing += '  {} ({})\n'.format(name, version)

        print('The following packages will be INSTALLED:')
        print(package_listing)

        if new_pkgs:
            dependency_listing = ''

            for info, version, suggested in sorted(new_pkgs, key=lambda x: x[0].package.name):
                name = info.package.qualified_name()
                dependency_listing += '  {} ({})'.format(
                    name, version)

                if suggested:
                    dependency_listing += ' (suggested)'

                dependency_listing += '\n'

            print('The following dependencies will be INSTALLED:')
            print(dependency_listing)

        allpkgs = package_infos + new_pkgs
        extdep_listing = ''

        for info, version, _ in sorted(allpkgs, key=lambda x: x[0].package.name):
            name = info.package.qualified_name()
            extdeps = info.dependencies(field='external_depends')

            if extdeps is None:
                extdep_listing += '  from {} ({}):\n    <malformed>\n'.format(
                    name, version)
                continue

            if extdeps:
                extdep_listing += '  from {} ({}):\n'.format(name, version)

                for extdep, semver in sorted(extdeps.items()):
                    extdep_listing += '    {} {}\n'.format(extdep, semver)

        if extdep_listing:
            print('Verify the following REQUIRED external dependencies:\n'
                  '(Ensure their installation on all relevant systems before'
                  ' proceeding):')
            print(extdep_listing)

        if not confirmation_prompt('Proceed?'):
            return

    package_infos += new_pkgs

    prompt_for_user_vars(manager, config, configfile, args,
                         [info for info, _, _ in package_infos])

    if not args.skiptests:
        for info, version, _ in package_infos:
            name = info.package.qualified_name()

            if 'test_command' not in info.metadata:
                zeekpkg.LOG.info(
                    'Skipping unit tests for "%s": no test_command in metadata',
                    name)
                continue

            print('Running unit tests for "{}"'.format(name))
            error, passed, test_dir = manager.test(name, version)
            error_msg = ''

            if error:
                error_msg = str.format(
                    'failed to run tests for {}: {}', name, error)
            elif not passed:
                clone_dir = os.path.join(os.path.join(test_dir, "clones"),
                                         info.package.name)
                error_msg = str.format('"{}" tests failed, inspect contents of'
                                       ' {} for details, especially any'
                                       ' "zkg.test_command.{{stderr,stdout}}"'
                                       ' files within {}',
                                       name, test_dir, clone_dir)

            if error_msg:
                print_error('error: {}'.format(error_msg))

                if args.force:
                    continue

                if not confirmation_prompt('Proceed to install anyway?',
                                           default_to_yes=False):
                    return

    installs_failed = []

    for info, version, _ in sorted(package_infos, key=lambda x: x[0].package.name):
        name = info.package.qualified_name()

        is_overwriting = False
        ipkg = manager.find_installed_package(name)

        if ipkg:
            is_overwriting = True
            modifications = manager.modified_config_files(ipkg)
            backup_files = manager.backup_modified_files(name, modifications)
            prev_upstream_config_files = manager.save_temporary_config_files(
                ipkg)

        worker = InstallWorker(manager, name, version)
        worker.start()
        print('Installing "{}"'.format(name), end='')
        sys.stdout.flush()

        while True:
            worker.join(1.0)

            if not worker.is_alive():
                break

            print('.', end='')
            sys.stdout.flush()

        print('')

        if worker.error:
            print('Failed installing "{}": {}'.format(name, worker.error))
            installs_failed.append((name, version))
            continue

        ipkg = manager.find_installed_package(name)
        print('Installed "{}" ({})'.format(name, ipkg.status.current_version))

        if is_overwriting:
            for i, mf in enumerate(modifications):
                next_upstream_config_file = mf[1]

                if not os.path.isfile(next_upstream_config_file):
                    print("\tConfig file no longer exists:")
                    print("\t\t" + next_upstream_config_file)
                    print("\tPrevious, locally modified version backed up to:")
                    print("\t\t" + backup_files[i])
                    continue

                prev_upstream_config_file = prev_upstream_config_files[i][1]

                if filecmp.cmp(prev_upstream_config_file, next_upstream_config_file):
                    # Safe to restore user's version
                    shutil.copy2(backup_files[i], next_upstream_config_file)
                    continue

                print("\tConfig file has been overwritten with a different version:")
                print("\t\t" + next_upstream_config_file)
                print("\tPrevious, locally modified version backed up to:")
                print("\t\t" + backup_files[i])

        if manager.has_scripts(ipkg):
            load_error = manager.load(name)

            if load_error:
                print('Failed loading "{}": {}'.format(name, load_error))
            else:
                print('Loaded "{}"'.format(name))

    if not args.nodeps:
        # Now load runtime dependencies after all depends and suggested
        # packages have been installed and loaded.
        for info, ver, _ in sorted(orig_pkgs, key=lambda x: x[0].package.name):
            _listing, saved_state = '', manager.loaded_package_states()
            name = info.package.qualified_name()

            load_error = manager.load_with_dependencies(zeekpkg.package.name_from_path(name))

            for _name, _error in load_error:
                if not _error:
                    _listing += '  {}\n'.format(_name)

            if not _listing:
                dep_listing = get_changed_state(manager, saved_state, [name])

                if dep_listing:
                    print('The following installed packages were additionally '
                          'loaded to satisfy runtime dependencies')
                    print(dep_listing)

            else:
                print('The following installed packages could NOT be loaded '
                      'to satisfy runtime dependencies for "{}"'.format(name))
                print(_listing)
                manager.restore_loaded_package_states(saved_state)

    if installs_failed:
        print_error('error: incomplete installation, the follow packages'
                    ' failed to be installed:')

        for n, v in installs_failed:
            print_error('  {} ({})'.format(n, v))

        sys.exit(1)


def cmd_bundle(manager, args, config, configfile):
    packages_to_bundle = []
    prefer_existing_clones = False

    if args.manifest:
        if len(args.manifest) == 1 and os.path.isfile(args.manifest[0]):
            config = configparser.ConfigParser(delimiters='=')
            config.optionxform = str

            if config.read(args.manifest[0]) and config.has_section('bundle'):
                packages = config.items('bundle')
            else:
                print_error('error: "{}" is not a valid manifest file'.format(
                    args.manifest[0]))
                sys.exit(1)

        else:
            packages = [(name, '') for name in args.manifest]

        to_validate = []
        new_pkgs = []

        for name, version in packages:
            if not check_local_git_repo(name):
                sys.exit(1)

            if not version:
                version = active_git_branch(name)

            info = manager.info(name, version=version, prefer_installed=False)

            if info.invalid_reason:
                print_error(str.format('error: invalid package "{}": {}', name,
                                       info.invalid_reason))
                sys.exit(1)

            if not version:
                version = info.best_version()

            to_validate.append((info.package.qualified_name(), version))
            packages_to_bundle.append((info.package.qualified_name(),
                                       info.package.git_url, version, False,
                                       False))

        if not args.nodeps:
            invalid_reason, new_pkgs = manager.validate_dependencies(
                to_validate, True, ignore_suggestions=args.nosuggestions)

            if invalid_reason:
                print_error('error: failed to resolve dependencies:',
                            invalid_reason)
                sys.exit(1)

        for info, version, suggested in new_pkgs:
            packages_to_bundle.append((info.package.qualified_name(),
                                       info.package.git_url, version, True,
                                       suggested))
    else:
        prefer_existing_clones = True

        for ipkg in manager.installed_packages():
            packages_to_bundle.append((ipkg.package.qualified_name(),
                                       ipkg.package.git_url,
                                       ipkg.status.current_version, False,
                                       False))

    if not packages_to_bundle:
        print_error('error: no packages to put in bundle')
        sys.exit(1)

    if not args.force:
        package_listing = ''

        for name, _, version, is_dependency, is_suggestion in packages_to_bundle:
            package_listing += '  {} ({})'.format(name, version)

            if is_suggestion:
                package_listing += ' (suggested)'
            elif is_dependency:
                package_listing += ' (dependency)'

            package_listing += '\n'

        print('The following packages will be BUNDLED into {}:'.format(
            args.bundle_filename))
        print(package_listing)

        if not confirmation_prompt('Proceed?'):
            return

    git_urls = [(git_url, version)
                for _, git_url, version, _, _ in packages_to_bundle]
    error = manager.bundle(args.bundle_filename, git_urls,
                           prefer_existing_clones=prefer_existing_clones)

    if error:
        print_error('error: failed to create bundle: {}'.format(error))
        sys.exit(1)

    print('Bundle successfully written: {}'.format(args.bundle_filename))


def cmd_unbundle(manager, args, config, configfile):
    prev_load_status = {}

    for ipkg in manager.installed_packages():
        prev_load_status[ipkg.package.git_url] = ipkg.status.is_loaded

    if args.replace:
        cmd_purge(manager, args, config, configfile)

    error, bundle_info = manager.bundle_info(args.bundle_filename)

    if error:
        print_error('error: failed to unbundle {}: {}'.format(
            args.bundle_filename, error))
        sys.exit(1)

    for git_url, version, pkg_info in bundle_info:
        if pkg_info.invalid_reason:
            name = pkg_info.package.qualified_name()
            print_error('error: bundle {} contains invalid package {}: {}'.format(
                args.bundle_filename, name, pkg_info.invalid_reason))
            sys.exit(1)

    if not bundle_info:
        print('No packages in bundle.')
        return

    if not args.force:
        package_listing = ''

        for git_url, version, _ in bundle_info:
            name = git_url

            for pkg in manager.source_packages():
                if pkg.git_url == git_url:
                    name = pkg.qualified_name()
                    break

            package_listing += '  {} ({})\n'.format(name, version)

        print('The following packages will be INSTALLED:')
        print(package_listing)

        extdep_listing = ''

        for git_url, version, info in bundle_info:
            name = git_url

            for pkg in manager.source_packages():
                if pkg.git_url == git_url:
                    name = pkg.qualified_name()
                    break

            extdeps = info.dependencies(field='external_depends')

            if extdeps is None:
                extdep_listing += '  from {} ({}):\n    <malformed>\n'.format(
                    name, version)
                continue

            if extdeps:
                extdep_listing += '  from {} ({}):\n'.format(name, version)

                for extdep, semver in sorted(extdeps.items()):
                    extdep_listing += '    {} {}\n'.format(extdep, semver)

        if extdep_listing:
            print('Verify the following REQUIRED external dependencies:\n'
                  '(Ensure their installation on all relevant systems before'
                  ' proceeding):')
            print(extdep_listing)

        if not confirmation_prompt('Proceed?'):
            return

    prompt_for_user_vars(manager, config, configfile, args,
                         [info for _, _, info in bundle_info])

    error = manager.unbundle(args.bundle_filename)

    if error:
        print_error('error: failed to unbundle {}: {}'.format(
            args.bundle_filename, error))
        sys.exit(1)

    for git_url, _, _ in bundle_info:
        if git_url in prev_load_status:
            need_load = prev_load_status[git_url]
        else:
            need_load = True

        ipkg = manager.find_installed_package(git_url)

        if not ipkg:
            print('Skipped loading "{}": failed to install'.format(git_url))
            continue

        name = ipkg.package.qualified_name()

        if not need_load:
            print('Skipped loading "{}"'.format(name))
            continue

        load_error = manager.load(name)

        if load_error:
            print('Failed loading "{}": {}'.format(name, load_error))
        else:
            print('Loaded "{}"'.format(name))

    print('Unbundling complete.')

def cmd_remove(manager, args, config, configfile):
    packages_to_remove = []

    def package_will_be_removed(pkg_name):
        for _ipkg in packages_to_remove:
            if _ipkg.package.name == pkg_name:
                return True

        return False

    for name in args.package:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            print_error(
                'error: package "{}" is not installed'.format(name))
            sys.exit(1)

        packages_to_remove.append(ipkg)

    dependers_to_unload = set()

    if not args.nodeps:
        for ipkg in packages_to_remove:
            for pkg_name in manager.list_depender_pkgs(ipkg.package.name):
                ipkg = manager.find_installed_package(pkg_name)

                if ipkg and not package_will_be_removed(ipkg.package.name):
                    if ipkg.status.is_loaded:
                        dependers_to_unload.add(ipkg.package.name)

    if not args.force:
        print('The following packages will be REMOVED:')

        for ipkg in packages_to_remove:
            print('  {}'.format(ipkg.package.qualified_name()))

        print()

        if dependers_to_unload:
            print('The following dependent packages will be UNLOADED:')

            for pkg_name in sorted(dependers_to_unload):
                ipkg = manager.find_installed_package(pkg_name)
                print('  {}'.format(ipkg.package.qualified_name()))

            print()

        if not confirmation_prompt('Proceed?'):
            return

    for pkg_name in sorted(dependers_to_unload):
        ipkg = manager.find_installed_package(pkg_name)
        name = ipkg.package.qualified_name()

        if manager.unload(name):
            print('Unloaded "{}"'.format(name))
        else:
            # Weird that it failed, but if it's not installed and there's
            # nothing to unload, not worth using a non-zero exit-code to
            # reflect an overall failure of the package removal operation
            print('Failed unloading "{}": no such package installed'.format(name))

    had_failure = False

    for ipkg in packages_to_remove:
        name = ipkg.package.qualified_name()
        modifications = manager.modified_config_files(ipkg)
        backup_files = manager.backup_modified_files(name, modifications)

        if manager.remove(name):
            print('Removed "{}"'.format(name))

            if backup_files:
                print('\tCreated backups of locally modified config files:')

                for backup_file in backup_files:
                    print('\t' + backup_file)

        else:
            print('Failed removing "{}": no such package installed'.format(name))
            had_failure = True

    if had_failure:
        sys.exit(1)


def cmd_purge(manager, args, config, configfile):
    packages_to_remove = manager.installed_packages()

    if not packages_to_remove:
        print('No packages to remove.')
        return

    if not args.force:
        package_listing = ''
        names_to_remove = [ipkg.package.qualified_name()
                           for ipkg in packages_to_remove]

        for name in names_to_remove:
            package_listing += '  {}\n'.format(name)

        print('The following packages will be REMOVED:')
        print(package_listing)

        if not confirmation_prompt('Proceed?'):
            return

    had_failure = False

    for ipkg in packages_to_remove:
        name = ipkg.package.qualified_name()
        modifications = manager.modified_config_files(ipkg)
        backup_files = manager.backup_modified_files(name, modifications)

        if manager.remove(name):
            print('Removed "{}"'.format(name))

            if backup_files:
                print('\tCreated backups of locally modified config files:')

                for backup_file in backup_files:
                    print('\t' + backup_file)

        else:
            print('Unknown error removing "{}"'.format(name))
            had_failure = True

    if had_failure:
        sys.exit(1)


def outdated(manager):
    return [ipkg.package.qualified_name()
            for ipkg in manager.installed_packages()
            if ipkg.status.is_outdated]


def cmd_refresh(manager, args, config, configfile):
    if not args.sources:
        args.sources = list(manager.sources.keys())

    if args.fail_on_aggregate_problems and not args.aggregate:
        print_error('warning: --fail-on-aggregate-problems without --aggregate'
                    ' has no effect.')

    had_failure = False
    had_aggregation_failure = False

    for source in args.sources:
        print('Refresh package source: {}'.format(source))

        src_pkgs_before = {i.qualified_name()
                           for i in manager.source_packages()}

        error = ''
        aggregation_issues = []

        if args.aggregate:
            res = manager.aggregate_source(source, args.push)
            error = res.refresh_error
            aggregation_issues = res.package_issues
        else:
            error = manager.refresh_source(source, False, args.push)

        if error:
            had_failure = True
            print_error(
                'error: failed to refresh "{}": {}'.format(source, error))
            continue

        src_pkgs_after = {i.qualified_name()
                          for i in manager.source_packages()}

        if src_pkgs_before == src_pkgs_after:
            print('\tNo membership changes')
        else:
            print('\tChanges:')
            diff = src_pkgs_before.symmetric_difference(src_pkgs_after)

            for name in diff:
                change = 'Added' if name in src_pkgs_after else 'Removed'
                print('\t\t{} {}'.format(change, name))

        if args.aggregate:
            if aggregation_issues:
                print('\tWARNING: Metadata aggregated, but excludes the '
                      'following packages due to described problems:')

                for url, issue in aggregation_issues:
                    print('\t\t{}: {}'.format(url, issue))
                if args.fail_on_aggregate_problems:
                    had_aggregation_failure = True
            else:
                print('\tMetadata aggregated')

        if args.push:
            print('\tPushed aggregated metadata')

    outdated_before = {i for i in outdated(manager)}
    print('Refresh installed packages')
    manager.refresh_installed_packages()
    outdated_after = {i for i in outdated(manager)}

    if outdated_before == outdated_after:
        print('\tNo new outdated packages')
    else:
        print('\tNew outdated packages:')
        diff = outdated_before.symmetric_difference(outdated_after)

        for name in diff:
            ipkg = manager.find_installed_package(name)
            version_change = version_change_string(manager, ipkg)
            print('\t\t{} {}'.format(name, version_change))

    if had_failure:
        sys.exit(1)
    if had_aggregation_failure:
        sys.exit(2)


def version_change_string(manager, installed_package):
    old_version = installed_package.status.current_version
    new_version = old_version
    version_change = ''

    if installed_package.status.tracking_method == TRACKING_METHOD_VERSION:
        versions = manager.package_versions(installed_package)

        if len(versions):
            new_version = versions[-1]

        version_change = '({} -> {})'.format(old_version, new_version)
    else:
        version_change = '({})'.format(new_version)

    return version_change


def cmd_upgrade(manager, args, config, configfile):
    if args.package:
        pkg_list = args.package
    else:
        pkg_list = outdated(manager)

    outdated_packages = []
    package_listing = ''

    for name in pkg_list:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            print_error('error: package "{}" is not installed'.format(name))
            sys.exit(1)

        name = ipkg.package.qualified_name()

        if not ipkg.status.is_outdated:
            continue

        if not manager.match_source_packages(name):
            name = ipkg.package.git_url

        info = manager.info(name, version=ipkg.status.current_version,
                            prefer_installed=False)

        if info.invalid_reason:
            print_error(str.format('error: invalid package "{}": {}', name,
                                   info.invalid_reason))
            sys.exit(1)

        next_version = ipkg.status.current_version

        if ( ipkg.status.tracking_method == TRACKING_METHOD_VERSION and
             info.versions ):
            next_version = info.versions[-1]

        outdated_packages.append((info, next_version, False))
        version_change = version_change_string(manager, ipkg)
        package_listing += '  {} {}\n'.format(name, version_change)

    if not outdated_packages:
        print('All packages already up-to-date.')
        return

    new_pkgs = []

    if not args.nodeps:
        to_validate = [(info.package.qualified_name(), next_version)
                       for info, next_version, _ in outdated_packages]
        invalid_reason, new_pkgs = manager.validate_dependencies(
            to_validate, ignore_suggestions=args.nosuggestions)

        if invalid_reason:
            print_error('error: failed to resolve dependencies:',
                        invalid_reason)
            sys.exit(1)

    allpkgs = outdated_packages + new_pkgs

    if not args.force:
        print('The following packages will be UPGRADED:')
        print(package_listing)

        if new_pkgs:
            dependency_listing = ''

            for info, version, suggestion in new_pkgs:
                name = info.package.qualified_name()
                dependency_listing += '  {} ({})'.format(name, version)

                if suggestion:
                    dependency_listing += ' (suggested)'

                dependency_listing += '\n'


            print('The following dependencies will be INSTALLED:')
            print(dependency_listing)

        extdep_listing = ''

        for info, version, _ in allpkgs:
            name = info.package.qualified_name()
            extdeps = info.dependencies(field='external_depends')

            if extdeps is None:
                extdep_listing += '  from {} ({}):\n    <malformed>\n'.format(
                    name, version)
                continue

            if extdeps:
                extdep_listing += '  from {} ({}):\n'.format(name, version)

                for extdep, semver in sorted(extdeps.items()):
                    extdep_listing += '    {} {}\n'.format(extdep, semver)

        if extdep_listing:
            print('Verify the following REQUIRED external dependencies:\n'
                  '(Ensure their installation on all relevant systems before'
                  ' proceeding):')
            print(extdep_listing)

        if not confirmation_prompt('Proceed?'):
            return

    prompt_for_user_vars(manager, config, configfile, args,
                         [info for info, _, _ in allpkgs])

    if not args.skiptests:
        to_test = [(info, next_version)
                   for info, next_version, _ in outdated_packages]

        for info, version, _ in new_pkgs:
            to_test.append((info, version))

        for info, version in to_test:
            name = info.package.qualified_name()

            if 'test_command' not in info.metadata:
                zeekpkg.LOG.info(
                    'Skipping unit tests for "%s": no test_command in metadata',
                    name)
                continue

            print('Running unit tests for "{}"'.format(name))
            error, passed, test_dir = manager.test(name, version)
            error_msg = ''

            if error:
                error_msg = str.format(
                    'failed to run tests for {}: {}', name, error)
            elif not passed:
                clone_dir = os.path.join(os.path.join(test_dir, "clones"),
                                         info.package.name)
                error_msg = str.format('"{}" tests failed, inspect contents of'
                                       ' {} for details, especially any'
                                       ' "zkg.test_command.{{stderr,stdout}}"'
                                       ' files within {}',
                                       name, test_dir, clone_dir)


            if error_msg:
                print_error('error: {}'.format(error_msg))

                if args.force:
                    continue

                if not confirmation_prompt('Proceed to install anyway?',
                                           default_to_yes=False):
                    return

    join_timeout = 0.01
    tick_interval = 1

    for info, version, _ in new_pkgs:
        name = info.package.qualified_name()
        time_accumulator = 0
        tick_count = 0
        worker = InstallWorker(manager, name, version)
        worker.start()

        while worker.is_alive():
            worker.join(join_timeout)
            time_accumulator += join_timeout

            if time_accumulator >= tick_interval:
                if tick_count == 0:
                    print('Installing "{}"'.format(name), end='')
                else:
                    print('.', end='')

                sys.stdout.flush()
                tick_count += 1
                time_accumulator -= tick_interval

        if tick_count != 0:
            print('')

        if worker.error:
            print('Failed installing "{}": {}'.format(name, worker.error))
            continue

        ipkg = manager.find_installed_package(name)
        print('Installed "{}" ({})'.format(name, ipkg.status.current_version))

        if manager.has_scripts(ipkg):
            load_error = manager.load(name)

            if load_error:
                print('Failed loading "{}": {}'.format(name, load_error))
            else:
                print('Loaded "{}"'.format(name))

    had_failure = False

    for info, next_version, _ in outdated_packages:
        name = info.package.qualified_name()
        bdir = name

        if not manager.match_source_packages(name):
            name = info.package.git_url
            bdir = zeekpkg.package.name_from_path(name)

        ipkg = manager.find_installed_package(name)
        modifications = manager.modified_config_files(ipkg)
        backup_files = manager.backup_modified_files(name, modifications)
        prev_upstream_config_files = manager.save_temporary_config_files(ipkg)

        res = manager.upgrade(name)

        if res:
            print('Failed upgrading "{}": {}'.format(name, res))
            had_failure = True
        else:
            ipkg = manager.find_installed_package(name)
            print('Upgraded "{}" ({})'.format(
                name, ipkg.status.current_version))

        for i, mf in enumerate(modifications):
            next_upstream_config_file = mf[1]

            if not os.path.isfile(next_upstream_config_file):
                print("\tConfig file no longer exists:")
                print("\t\t" + next_upstream_config_file)
                print("\tPrevious, locally modified version backed up to:")
                print("\t\t" + backup_files[i])
                continue

            prev_upstream_config_file = prev_upstream_config_files[i][1]

            if filecmp.cmp(prev_upstream_config_file, next_upstream_config_file):
                # Safe to restore user's version
                shutil.copy2(backup_files[i], next_upstream_config_file)
                continue

            print("\tConfig file has been updated to a newer version:")
            print("\t\t" + next_upstream_config_file)
            print("\tPrevious, locally modified version backed up to:")
            print("\t\t" + backup_files[i])

    if had_failure:
        sys.exit(1)


def cmd_load(manager, args, config, configfile):
    had_failure = False
    load_error = False
    dep_error_listing = ''

    for name in args.package:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            had_failure = True
            print('Failed to load "{}": no such package installed'.format(name))
            continue

        if not manager.has_scripts(ipkg):
            print('The package "{}" does not contain scripts to load.'.format(name))
            continue

        name = ipkg.package.qualified_name()

        if args.nodeps:
            load_error = manager.load(name)
        else:
            saved_state = manager.loaded_package_states()
            dep_error_listing, load_error = '', False

            loaded_dep_list = manager.load_with_dependencies(zeekpkg.package.name_from_path(name))

            for _name, _error in loaded_dep_list:
                if _error:
                    load_error = True
                    dep_error_listing += '  {}: {}\n'.format(_name, _error)

            if not load_error:
                dep_listing = get_changed_state(manager, saved_state, [name])

                if dep_listing:
                    print('The following installed packages were additionally loaded to satisfy' \
                        ' runtime dependencies for "{}".'.format(name))
                    print(dep_listing)

        if load_error:
            had_failure = True

            if not args.nodeps:
                if dep_error_listing:
                    print('The following installed dependencies could not be loaded for "{}".'.format(name))
                    print(dep_error_listing)
                    manager.restore_loaded_package_states(saved_state)

            print('Failed to load "{}": {}'.format(name, load_error))
        else:
            print('Loaded "{}"'.format(name))

    if had_failure:
        sys.exit(1)


def cmd_unload(manager, args, config, configfile):
    had_failure = False
    packages_to_unload = []
    dependers_to_unload = set()

    def package_will_be_unloaded(pkg_name):
        for _ipkg in packages_to_unload:
            if _ipkg.package.name == pkg_name:
                return True

        return False

    for name in args.package:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            had_failure = True
            print('Failed to unload "{}": no such package installed'.format(name))
            continue

        if not ipkg.status.is_loaded:
            continue

        packages_to_unload.append(ipkg)

    if not args.nodeps:
        for ipkg in packages_to_unload:
            for pkg_name in manager.list_depender_pkgs(ipkg.package.name):
                ipkg = manager.find_installed_package(pkg_name)

                if ipkg and not package_will_be_unloaded(ipkg.package.name):
                    if ipkg.status.is_loaded:
                        dependers_to_unload.add(ipkg.package.name)


    if packages_to_unload and not args.force:
        print('The following packages will be UNLOADED:')

        for ipkg in packages_to_unload:
            print('  {}'.format(ipkg.package.qualified_name()))

        print()

        if dependers_to_unload:
            print('The following dependent packages will be UNLOADED:')

            for pkg_name in sorted(dependers_to_unload):
                ipkg = manager.find_installed_package(pkg_name)
                print('  {}'.format(ipkg.package.qualified_name()))

            print()

        if not confirmation_prompt('Proceed?'):
            if had_failure:
                sys.exit(1)
            else:
                return

    for pkg_name in sorted(dependers_to_unload):
        packages_to_unload.append(manager.find_installed_package(pkg_name))

    for ipkg in packages_to_unload:
        name = ipkg.package.qualified_name()

        if manager.unload(name):
            print('Unloaded "{}"'.format(name))
        else:
            had_failure = True
            print('Failed unloading "{}": no such package installed'.format(name))

    if had_failure:
        sys.exit(1)


def cmd_pin(manager, args, config, configfile):
    had_failure = False

    for name in args.package:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            had_failure = True
            print('Failed to pin "{}": no such package installed'.format(name))
            continue

        name = ipkg.package.qualified_name()
        ipkg = manager.pin(name)

        if ipkg:
            print('Pinned "{}" at version: {} ({})'.format(
                name, ipkg.status.current_version, ipkg.status.current_hash))
        else:
            had_failure = True
            print('Failed pinning "{}": no such package installed'.format(name))

    if had_failure:
        sys.exit(1)


def cmd_unpin(manager, args, config, configfile):
    had_failure = False

    for name in args.package:
        ipkg = manager.find_installed_package(name)

        if not ipkg:
            had_failure = True
            print('Failed to unpin "{}": no such package installed'.format(name))
            continue

        name = ipkg.package.qualified_name()
        ipkg = manager.unpin(name)

        if ipkg:
            print('Unpinned "{}" from version: {} ({})'.format(
                name, ipkg.status.current_version, ipkg.status.current_hash))
        else:
            had_failure = True
            print(
                'Failed unpinning "{}": no such package installed'.format(name))

    if had_failure:
        sys.exit(1)


def _get_filtered_packages(manager, category):
    pkg_dict = dict()

    for ipkg in manager.installed_packages():
        pkg_dict[ipkg.package.qualified_name()] = ipkg

    for pkg in manager.source_packages():
        pkg_qn = pkg.qualified_name()

        if pkg_qn not in pkg_dict:
            pkg_dict[pkg_qn] = pkg

    if category == 'all':
        filtered_pkgs = pkg_dict
    elif category == 'installed':
        filtered_pkgs = {key: value for key, value in pkg_dict.items()
                         if isinstance(value, zeekpkg.InstalledPackage)}
    elif category == 'not_installed':
        filtered_pkgs = {key: value for key, value in pkg_dict.items()
                         if not isinstance(value, zeekpkg.InstalledPackage)}
    elif category == 'loaded':
        filtered_pkgs = {key: value for key, value in pkg_dict.items()
                         if isinstance(value, zeekpkg.InstalledPackage) and
                         value.status.is_loaded}
    elif category == 'unloaded':
        filtered_pkgs = {key: value for key, value in pkg_dict.items()
                         if isinstance(value, zeekpkg.InstalledPackage) and
                         not value.status.is_loaded}
    elif category == 'outdated':
        filtered_pkgs = {key: value for key, value in pkg_dict.items()
                         if isinstance(value, zeekpkg.InstalledPackage) and
                         value.status.is_outdated}
    else:
        raise NotImplementedError

    return filtered_pkgs


def cmd_list(manager, args, config, configfile):
    filtered_pkgs = _get_filtered_packages(manager, args.category)

    for pkg_name, val in sorted(filtered_pkgs.items()):
        if isinstance(val, zeekpkg.InstalledPackage):
            pkg = val.package
            out = '{} (installed: {})'.format(
                pkg_name, val.status.current_version)
        else:
            pkg = val
            out = pkg_name

        if not args.nodesc:
            desc = pkg.short_description()

            if desc:
                out += ' - ' + desc

        print(out)


def cmd_search(manager, args, config, configfile):
    src_pkgs = manager.source_packages()
    matches = set()

    for search_text in args.search_text:
        if search_text[0] == '/' and search_text[-1] == '/':
            import re

            try:
                regex = re.compile(search_text[1:-1])
            except re.error as error:
                print('invalid regex: {}'.format(error))
                sys.exit(1)
            else:
                for pkg in src_pkgs:
                    if regex.search(pkg.name_with_source_directory()):
                        matches.add(pkg)

                    for tag in pkg.tags():
                        if regex.search(tag):
                            matches.add(pkg)

        else:
            for pkg in src_pkgs:
                if search_text in pkg.name_with_source_directory():
                    matches.add(pkg)

                for tag in pkg.tags():
                    if search_text in tag:
                        matches.add(pkg)

    if matches:
        for match in sorted(matches):
            out = match.qualified_name()

            ipkg = manager.find_installed_package(match.qualified_name())

            if ipkg:
                out += ' (installed: {})'.format(ipkg.status.current_version)

            desc = match.short_description()

            if desc:
                out += ' - ' + desc

            print(out)

    else:
        print("no matches")


def cmd_info(manager, args, config, configfile):
    if args.version and len(args.package) > 1:
        print_error(
            'error: "info --version" may only be used for a single package')
        sys.exit(1)

    # Dictionary for storing package info to output as JSON
    pkginfo = dict()
    had_invalid_package = False

    if len(args.package) == 1:
        try:
            filtered_pkgs = _get_filtered_packages(manager, args.package[0])
            package_names = [pkg_name
                             for pkg_name, _ in sorted(filtered_pkgs.items())]
        except NotImplementedError:
            package_names = args.package
    else:
        package_names = args.package

    for name in package_names:
        info = manager.info(name,
                            version=args.version,
                            prefer_installed=(args.nolocal != True))

        if info.package:
            name = info.package.qualified_name()

        if args.json:
            pkginfo[name] = dict()
            pkginfo[name]['metadata'] = dict()
        else:
            print('"{}" info:'.format(name))

        if info.invalid_reason:
            if args.json:
                pkginfo[name]['invalid'] = info.invalid_reason
            else:
                print('\tinvalid package: {}\n'.format(info.invalid_reason))

            had_invalid_package = True
            continue

        if args.json:
            pkginfo[name]['url'] = info.package.git_url
            pkginfo[name]['versions'] = info.versions
        else:
            print('\turl: {}'.format(info.package.git_url))
            print('\tversions: {}'.format(info.versions))

        if info.status:
            if args.json:
                pkginfo[name]['install_status'] = dict()

                for key, value in sorted(info.status.__dict__.items()):
                    pkginfo[name]['install_status'][key] = value
            else:
                print('\tinstall status:')

                for key, value in sorted(info.status.__dict__.items()):
                    print('\t\t{} = {}'.format(key, value))

        if args.json:
            if info.metadata_file:
                pkginfo[name]['metadata_file'] = info.metadata_file
            pkginfo[name]['metadata'][info.metadata_version] = dict()
        else:
            if info.metadata_file:
                print('\tmetadata file: {}'.format(info.metadata_file))
            print('\tmetadata (from version "{}"):'.format(
                info.metadata_version))

        if len(info.metadata) == 0:
            if args.json != True:
                print('\t\t<empty metadata file>')
        else:
            if args.json:
                _fill_metadata_version(
                    pkginfo[name]['metadata'][info.metadata_version],
                    info.metadata)
            else:
                for key, value in sorted(info.metadata.items()):
                    value = value.replace('\n', '\n\t\t\t')
                    print('\t\t{} = {}'.format(key, value))

        # If --json and --allvers given, check for multiple versions and
        # add the metadata for each version to the pkginfo.
        if args.json and args.allvers:
            for vers in info.versions:
                # Skip the version that was already processed
                if vers != info.metadata_version:
                    info2 = manager.info(name,
                                         vers,
                                         prefer_installed=(args.nolocal != True))
                    pkginfo[name]['metadata'][info2.metadata_version] = dict()
                    if info2.metadata_file:
                        pkginfo[name]['metadata_file'] = info2.metadata_file
                    _fill_metadata_version(
                        pkginfo[name]['metadata'][info2.metadata_version],
                        info2.metadata)

        if not args.json:
            print()

    if args.json:
        print(json.dumps(pkginfo, indent=args.jsonpretty, sort_keys=True))

    if had_invalid_package:
        sys.exit(1)


def _fill_metadata_version(pkginfo_name_metadata_version, info_metadata):
    """ Fill a dict with metadata information.

        This helper function is called by cmd_info to fill metadata information
        for a specific package version.

    Args:
        pkginfo_name_metadata_version (dict of str -> dict): Corresponds
            to pkginfo[name]['metadata'][info.metadata_version] in cmd_info.

        info_metadata (dict of str->str): Corresponds to info.metadata
            in cmd_info.

    Side effect:
        New dict entries are added to pkginfo_name_metadata_version.
    """
    for key, value in info_metadata.items():
        if key == 'depends' or key == 'suggests':
            pkginfo_name_metadata_version[key] = dict()
            deps = value.split('\n')

            for i in range(1, len(deps)):
                deplist = deps[i].split(' ')
                pkginfo_name_metadata_version[key][deplist[0]] =\
                    deplist[1]
        else:
            pkginfo_name_metadata_version[key] = value


def cmd_config(manager, args, config, configfile):
    if args.config_param == 'all':
        out = io.StringIO()
        config.write(out)
        print(out.getvalue())
        out.close()
    elif args.config_param == 'sources':
        for key, value in config_items(config, 'sources'):
            print('{} = {}'.format(key, value))
    elif args.config_param == 'user_vars':
        if config.has_section('user_vars'):
            for key, value in config_items(config, 'user_vars'):
                print('{} = {}'.format(key, value))
    else:
        print(config.get('paths', args.config_param))


def cmd_autoconfig(manager, args, config, configfile):
    if args.user:
        configfile = os.path.join(home_config_dir(), 'config')
        with io.open(configfile, 'w', encoding=std_encoding(sys.stdout)) as f:
            config.write(f)
        print('Successfully wrote config file to {}'.format(configfile))
        return

    zeek_config = find_program('zeek-config')

    if zeek_config:
        have_zeek_config = True
    else:
        have_zeek_config = False
        zeek_config = find_program('bro-config')

    if not zeek_config:
        print_error('error: no "zeek-config" or "bro-config" in PATH')
        sys.exit(1)

    dist_option = '--zeek_dist' if have_zeek_config else '--bro_dist'

    cmd = subprocess.Popen([zeek_config,
                            '--site_dir', '--plugin_dir', '--prefix', dist_option],
                           stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                           bufsize=1, universal_newlines=True)

    script_dir = read_zeek_config_line(cmd.stdout)
    plugin_dir = read_zeek_config_line(cmd.stdout)
    bin_dir = os.path.join(read_zeek_config_line(cmd.stdout), 'bin')
    zeek_dist = read_zeek_config_line(cmd.stdout)

    if configfile:
        config_dir = os.path.dirname(configfile)
    else:
        config_dir = default_config_dir()
        configfile = os.path.join(config_dir, 'config')

    make_dir(config_dir)

    config_file_exists = os.path.isfile(configfile)

    def change_config_value(config, section, option, new_value, use_prompt):
        if not use_prompt:
            config.set(section, option, new_value)
            return

        old_value = config.get(section, option)

        if old_value == new_value:
            return

        prompt = u'Set "{}" config option to: {} ?'.format(option, new_value)

        if old_value:
            prompt += u'\n(previous value: {})'.format(old_value)

        if args.force or confirmation_prompt(prompt):
            config.set(section, option, new_value)

    change_config_value(config, 'paths', 'script_dir',
                        script_dir, config_file_exists)
    change_config_value(config, 'paths', 'plugin_dir',
                        plugin_dir, config_file_exists)
    change_config_value(config, 'paths', 'bin_dir',
                        bin_dir, config_file_exists)
    change_config_value(config, 'paths', 'zeek_dist',
                        zeek_dist, config_file_exists)

    with io.open(configfile, 'w', encoding=std_encoding(sys.stdout)) as f:
        config.write(f)

    print('Successfully wrote config file to {}'.format(configfile))


def cmd_env(manager, args, config, configfile):

    zeek_config = find_program('zeek-config')
    path_option = '--zeekpath'

    if not zeek_config:
        path_option = '--bropath'
        zeek_config = find_program('bro-config')

    zeekpath = os.environ.get('ZEEKPATH')

    if not zeekpath:
        zeekpath = os.environ.get('BROPATH')

    pluginpath = os.environ.get('ZEEK_PLUGIN_PATH')

    if not pluginpath:
        pluginpath = os.environ.get('BRO_PLUGIN_PATH')

    if zeek_config:
        cmd = subprocess.Popen([zeek_config, path_option, '--plugin_dir'],
                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                               bufsize=1, universal_newlines=True)
        line1 = read_zeek_config_line(cmd.stdout)
        line2 = read_zeek_config_line(cmd.stdout)

        if not zeekpath:
            zeekpath = line1

        if not pluginpath:
            pluginpath = line2

    zeekpaths = [p for p in zeekpath.split(':')] if zeekpath else []
    pluginpaths = [p for p in pluginpath.split(':')] if pluginpath else []

    zeekpaths.append(manager.zeekpath())
    pluginpaths.append(manager.zeek_plugin_path())

    def remove_redundant_paths(paths):
        return list(OrderedDict.fromkeys(paths))

    zeekpaths = remove_redundant_paths(zeekpaths)
    pluginpaths = remove_redundant_paths(pluginpaths)

    if os.environ.get('SHELL', '').endswith('csh'):
        print(u'setenv BROPATH {}'.format(':'.join(zeekpaths)))
        print(u'setenv BRO_PLUGIN_PATH {}'.format(':'.join(pluginpaths)))
        print(u'setenv ZEEKPATH {}'.format(':'.join(zeekpaths)))
        print(u'setenv ZEEK_PLUGIN_PATH {}'.format(':'.join(pluginpaths)))
        print(u'setenv PATH {}:$PATH'.format(manager.bin_dir))
    else:
        print(u'export BROPATH={}'.format(':'.join(zeekpaths)))
        print(u'export BRO_PLUGIN_PATH={}'.format(':'.join(pluginpaths)))
        print(u'export ZEEKPATH={}'.format(':'.join(zeekpaths)))
        print(u'export ZEEK_PLUGIN_PATH={}'.format(':'.join(pluginpaths)))
        print(u'export PATH={}:$PATH'.format(manager.bin_dir))


def cmd_create(manager, args, config, configfile):

    tmplname = (args.template
                or config.get('templates', 'default', fallback=None)
                or ZKG_DEFAULT_TEMPLATE)
    try:
        tmpl = Template.load(config, tmplname, args.version)
    except LoadError as error:
        msg = 'problem while loading template {}: {}'.format(tmplname, error)
        zeekpkg.LOG.exception(msg)
        print_error('error: ' + msg)
        sys.exit(1)

    try:
        package = tmpl.package()
        uvars = tmpl.define_user_vars()
        uvar_names = set(package.needed_user_vars())

        # Overlay any requested features onto the package.
        if args.features:
            # If the user provided comma-separated values, split the
            # strings. (Argparse expects space separation.) Also
            # filter any duplicates.
            fnames = set()
            for feat in args.features:
                fnames |= set([f.strip() for f in feat.split(',') if f])
            features = tmpl.features()
            for feature in features:
                if feature.name() in fnames:
                    package.add_feature(feature)
                    uvar_names |= set(feature.needed_user_vars())
                    fnames.remove(feature.name())
            if len(fnames) > 0:
                # Alert if the user requested an unknown feature.
                knowns = ', '.join([f'"{f.name()}"' for f in features])
                unknowns = ', '.join([f'"{name}"' for name in fnames])
                print_error('error: the following features are unknown: {}.'
                            ' Template "{}" offers {}.'.format(
                                unknowns, tmpl.name(), knowns or 'no features'))
                sys.exit(1)

        # Remove user vars we don't actually require from consideration
        uvars = [uvar for uvar in uvars if uvar.name() in uvar_names]

        # Resolve the variables via user input, args, etc
        for uvar in uvars:
            try:
                uvar.resolve(tmpl.name(), config, args.user_var, args.force)
            except ValueError:
                print_error(str.format('error: could not determine value of user variable "{}",'
                                       ' provide via environment or --user-var', uvar.name()))
                sys.exit(1)

        # Apply them to the template. After this, any parameter can be
        # retrieved from the template via tmpl.lookup_param().
        tmpl._set_user_vars(uvars)

        # Verify that resulting template parameters are formatted correctly
        try:
            package.do_validate(tmpl)
        except zeekpkg.template.InputError as error:
            print_error('error: template input invalid, ' + str(error))
            sys.exit(1)

        # And finally, instantiate the package.
        try:
            if os.path.isdir(args.packagedir):
                if not args.force:
                    print('Package directory {} already exists.'
                          .format(args.packagedir))
                    if not confirmation_prompt('Delete?'):
                        sys.exit(1)
                try:
                    delete_path(args.packagedir)
                    zeekpkg.LOG.info('Removed existing package directory %s', args.packagedir)
                except OSError as err:
                    print_error('error: could not remove package directory {}: {}'
                                .format(args.packagedir, err))
                    sys.exit(1)

            package.do_instantiate(tmpl, args.packagedir, args.force)
        except zeekpkg.template.OutputError as error:
            print_error('error: template instantiation failed, ' + str(error))
            sys.exit(1)
    except Exception as error:
        msg = 'problem during template instantiation: {}'.format(error)
        zeekpkg.LOG.exception(msg)
        print_error('error: ' + msg)
        sys.exit(1)


def cmd_template_info(manager, args, config, configfile):
    tmplname = (args.template
                or config.get('templates', 'default', fallback=None)
                or ZKG_DEFAULT_TEMPLATE)

    try:
        tmpl = Template.load(config, tmplname, args.version)
    except LoadError as error:
        msg = 'problem while loading template {}: {}'.format(tmplname, error)
        zeekpkg.LOG.exception(msg)
        print_error('error: ' + msg)
        sys.exit(1)

    tmplinfo = tmpl.info()

    if args.json:
        print(json.dumps(tmplinfo, indent=args.jsonpretty, sort_keys=True))
    else:
        print('API version: ' + tmplinfo['api_version'])
        print('features: ' + ', '.join(tmplinfo['features']))
        print('origin: ' + tmplinfo['origin'])
        print('provides package: ' + str(tmplinfo['provides_package']).lower())
        print('user vars:')
        for uvar_name, uvar_info in tmplinfo['user_vars'].items():
            print('\t{}: {}, {}, used by {}'.format(
                uvar_name, uvar_info['description'],
                uvar_info['default'] or 'no default',
                ', '.join(uvar_info['used_by']) or 'not used'))
        print('versions: ' + ', '.join(tmplinfo['versions']))


class BundleHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    # Workaround for underlying argparse bug: https://bugs.python.org/issue9338
    def _format_args(self, action, default_metavar):
        rval = super(BundleHelpFormatter, self)._format_args(
                action, default_metavar)

        if action.nargs == argparse.ZERO_OR_MORE:
            rval += " --"
        elif action.nargs == argparse.ONE_OR_MORE:
            rval += " --"

        return rval


def top_level_parser():
    top_parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='A command-line package manager for Zeek.',
        epilog='Environment Variables:\n\n'
        '    ``ZKG_CONFIG_FILE``:\t'
        'Same as ``--configfile`` option, but has less precedence.\n'
        '    ``ZKG_DEFAULT_SOURCE``:\t'
        'The default package source to use (normally {}).\n'
        '    ``ZKG_DEFAULT_TEMPLATE``:\t'
        'The default package template to use (normally {}).\n'
        .format(ZKG_DEFAULT_SOURCE, ZKG_DEFAULT_TEMPLATE)
    )
    top_parser.add_argument('--version', action='version',
                            version='%(prog)s ' + zeekpkg.__version__)

    group = top_parser.add_mutually_exclusive_group()
    group.add_argument('--configfile', metavar='FILE',
                       help='Path to Zeek Package Manager config file. Precludes --user.')
    group.add_argument('--user', action='store_true',
                       help='Store all state in user\'s home directory. Precludes --configfile.')

    top_parser.add_argument('--verbose', '-v', action='count', default=0,
                            help='Increase program output for debugging.'
                            ' Use multiple times for more output (e.g. -vvv).')
    top_parser.add_argument('--extra-source', action='append',
                            metavar='NAME=URL', help='Add an extra source.')
    return top_parser


def argparser():
    pkg_name_help = 'The name(s) of package(s) to operate on.  The package' \
                    ' may be named in several ways.  If the package is part' \
                    ' of a package source, it may be referred to by the' \
                    ' base name of the package (last component of git URL)' \
                    ' or its path within the package source.' \
                    ' If two packages in different package sources' \
                    ' have conflicting paths, then the package source' \
                    ' name may be prepended to the package path to resolve' \
                    ' the ambiguity. A full git URL may also be used to refer' \
                    ' to a package that does not belong to a source. E.g. for' \
                    ' a package source called "zeek" that has a package named' \
                    ' "foo" located in either "alice/zkg.index" or' \
                    ' "alice/bro-pkg.index", the following' \
                    ' names work: "foo", "alice/foo", "zeek/alice/foo".'

    def add_uservar_args(parser, force_help=None):
        parser.add_argument(
            '--force', action='store_true',
            help=force_help or "Don't prompt for confirmation or user variables.")
        parser.add_argument(
            '--user-var', action='append', metavar='NAME=VAL', type=UserVar.parse_arg,
            help='A user variable assignment. This avoids prompting'
            ' for input and lets you provide a value when using --force.'
            ' Use repeatedly as needed for multiple values.')

    def add_json_args(parser, help_text):
        parser.add_argument('--json', action='store_true', help=help_text)
        parser.add_argument(
            '--jsonpretty', type=int, default=None, metavar='SPACES',
            help='Optional number of spaces to indent for pretty-printed'
            ' JSON output.')

    top_parser = top_level_parser()
    command_parser = top_parser.add_subparsers(
        title='commands', dest='command',
        help='See `%(prog)s <command> -h` for per-command usage info.')
    command_parser.required = True

    # test
    sub_parser = command_parser.add_parser(
        'test',
        help='Runs unit tests for Zeek packages.',
        description='Runs the unit tests for the specified Zeek packages.'
                    ' In most cases, the "zeek" and "zeek-config" programs will'
                    ' need to be in PATH before running this command.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_test)
    sub_parser.add_argument(
        'package', nargs='+', help=pkg_name_help)
    sub_parser.add_argument(
        '--version', default=None,
        help='The version of the package to test.  Only one package may be'
        ' specified at a time when using this flag.  A version tag, branch'
        ' name, or commit hash may be specified here.'
        ' If the package name refers to a local git repo with a working tree,'
        ' then its currently active branch is used.'
        ' The default for other cases is to use'
        ' the latest version tag, or if a package has none,'
        ' the default branch, like "main" or "master".')

    # install
    sub_parser = command_parser.add_parser(
        'install',
        help='Installs Zeek packages.',
        description='Installs packages from a configured package source or'
                    ' directly from a git URL.  After installing, the package'
                    ' is marked as being "loaded" (see the ``load`` command).',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_install)
    sub_parser.add_argument(
        'package', nargs='+', help=pkg_name_help)
    sub_parser.add_argument(
        '--skiptests', action='store_true',
        help='Skip running unit tests for packages before installation.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks putting your installed package collection into a'
        ' broken or unusable state.')
    sub_parser.add_argument(
        '--nosuggestions', action='store_true',
        help='Skip automatically installing suggested packages.')
    sub_parser.add_argument(
        '--version', default=None,
        help='The version of the package to install.  Only one package may be'
        ' specified at a time when using this flag.  A version tag, branch'
        ' name, or commit hash may be specified here.'
        ' If the package name refers to a local git repo with a working tree,'
        ' then its currently active branch is used.'
        ' The default for other cases is to use'
        ' the latest version tag, or if a package has none,'
        ' the default branch, like "main" or "master".')
    add_uservar_args(sub_parser)

    # bundle
    sub_parser = command_parser.add_parser(
        'bundle',
        help='Creates a bundle file containing a collection of Zeek packages.',
        description='This command creates a bundle file containing a collection'
                    ' of Zeek packages.  If ``--manifest`` is used, the user'
                    ' supplies the list of packages to put in the bundle, else'
                    ' all currently installed packages are put in the bundle.'
                    ' A bundle file can be unpacked on any target system,'
                    ' resulting in a repeatable/specific set of packages'
                    ' being installed on that target system (see the'
                    ' ``unbundle`` command).  This command may be useful for'
                    ' those that want to manage packages on a system that'
                    ' otherwise has limited network connectivity.  E.g. one can'
                    ' use a system with an internet connection to create a'
                    ' bundle, transport that bundle to the target machine'
                    ' using whatever means are appropriate, and finally'
                    ' unbundle/install it on the target machine.',
        formatter_class=BundleHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_bundle)
    sub_parser.add_argument(
        'bundle_filename',
        metavar='filename.bundle',
        help='The path of the bundle file to create.  It will be overwritten'
             ' if it already exists.  Note that if --manifest is used before'
             ' this filename is specified, you should use a double-dash, --,'
             ' to first terminate that argument list.')
    sub_parser.add_argument(
        '--force', action='store_true',
        help='Skip the confirmation prompt.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks creating a bundle of packages that is in a'
        ' broken or unusable state.')
    sub_parser.add_argument(
        '--nosuggestions', action='store_true',
        help='Skip automatically bundling suggested packages.')
    sub_parser.add_argument(
        '--manifest', nargs='+',
        help='This may either be a file name or a list of packages to include'
        ' in the bundle.  If a file name is supplied, it should be in INI'
        ' format with a single ``[bundle]`` section.  The keys in that section'
        ' correspond to package names and their values correspond to git'
        ' version tags, branch names, or commit hashes.  The values may be'
        ' left blank to indicate that the latest available version should be'
        ' used.')

    # unbundle
    sub_parser = command_parser.add_parser(
        'unbundle',
        help='Unpacks Zeek packages from a bundle file and installs them.',
        description='This command unpacks a bundle file formerly created by the'
                    ' ``bundle`` command and installs all the packages'
                    ' contained within.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_unbundle)
    sub_parser.add_argument(
        'bundle_filename',
        metavar='filename.bundle',
        help='The path of the bundle file to install.')
    sub_parser.add_argument(
        '--replace', action='store_true',
        help='Using this flag first removes all installed packages before then'
        ' installing the packages from the bundle.')
    add_uservar_args(sub_parser)

    # remove
    sub_parser = command_parser.add_parser(
        'remove',
        help='Uninstall a package.',
        description='Unloads (see the ``unload`` command) and uninstalls a'
        ' previously installed package.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_remove)
    sub_parser.add_argument('package', nargs='+', help=pkg_name_help)
    sub_parser.add_argument(
        '--force', action='store_true',
        help='Skip the confirmation prompt.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks putting your installed package collection into a'
        ' broken or unusable state.')

    # purge
    sub_parser = command_parser.add_parser(
        'purge',
        help='Uninstall all packages.',
        description='Unloads (see the ``unload`` command) and uninstalls all'
        ' previously installed packages.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_purge)
    sub_parser.add_argument(
        '--force', action='store_true',
        help='Skip the confirmation prompt.')

    # refresh
    sub_parser = command_parser.add_parser(
        'refresh',
        help='Retrieve updated package metadata.',
        description='Retrieve latest package metadata from sources and checks'
        ' whether any installed packages have available upgrades.'
        ' Note that this does not actually upgrade any packages (see the'
        ' ``upgrade`` command for that).',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_refresh)
    sub_parser.add_argument(
        '--aggregate', action='store_true',
        help='Crawls the urls listed in package source zkg.index'
        ' (or legacy bro-pkg.index) files and'
        ' aggregates the metadata found in their zkg.meta (or legacy'
        ' bro-pkg.meta) files.  The aggregated metadata is stored in the local'
        ' clone of the package source that zkg uses internally for locating'
        ' package metadata.'
        ' For each package, the metadata is taken from the highest available'
        ' git version tag or the default branch, like "main" or "master", if no version tags exist')
    sub_parser.add_argument(
        '--fail-on-aggregate-problems', action='store_true',
        help='When using --aggregate, exit with error when any packages trigger'
        ' metadata problems. Normally such problems only cause a warning.')
    sub_parser.add_argument(
        '--push', action='store_true',
        help='Push all local changes to package sources to upstream repos')
    sub_parser.add_argument('--sources', nargs='+',
                            help='A list of package source names to operate on.  If this argument'
                            ' is not used, then the command will operate on all configured'
                            ' sources.')

    # upgrade
    sub_parser = command_parser.add_parser(
        'upgrade',
        help='Upgrade installed packages to latest versions.',
        description='Uprades the specified package(s) to latest available'
        ' version.  If no specific packages are specified, then all installed'
        ' packages that are outdated and not pinned are upgraded.  For packages'
        ' that are installed with ``--version`` using a git branch name, the'
        ' package is updated to the latest commit on that branch, else the'
        ' package is updated to the highest available git version tag.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_upgrade)
    sub_parser.add_argument(
        'package', nargs='*', default=[], help=pkg_name_help)
    sub_parser.add_argument(
        '--skiptests', action='store_true',
        help='Skip running unit tests for packages before installation.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks putting your installed package collection into a'
        ' broken or unusable state.')
    sub_parser.add_argument(
        '--nosuggestions', action='store_true',
        help='Skip automatically installing suggested packages.')
    add_uservar_args(sub_parser)

    # load
    sub_parser = command_parser.add_parser(
        'load',
        help='Register packages to be be auto-loaded by Zeek.',
        description='The Zeek Package Manager keeps track of all packages that'
        ' are marked as "loaded" and maintains a single Zeek script that, when'
        ' loaded by Zeek (e.g. via ``@load packages``), will load the scripts'
        ' from all "loaded" packages at once.'
        ' This command adds a set of packages to the "loaded packages" list.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_load)
    sub_parser.add_argument(
        'package', nargs='+', default=[],
        help='Name(s) of package(s) to load.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks putting your installed package collection into a'
        ' broken or unusable state.')

    # unload
    sub_parser = command_parser.add_parser(
        'unload',
        help='Unregister packages to be be auto-loaded by Zeek.',
        description='The Zeek Package Manager keeps track of all packages that'
        ' are marked as "loaded" and maintains a single Zeek script that, when'
        ' loaded by Zeek, will load the scripts from all "loaded" packages at'
        ' once.  This command removes a set of packages from the "loaded'
        ' packages" list.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_unload)
    sub_parser.add_argument(
        'package', nargs='+', default=[], help=pkg_name_help)
    sub_parser.add_argument(
        '--force', action='store_true',
        help='Skip the confirmation prompt.')
    sub_parser.add_argument(
        '--nodeps', action='store_true',
        help='Skip all dependency resolution/checks.  Note that using this'
        ' option risks putting your installed package collection into a'
        ' broken or unusable state.')

    # pin
    sub_parser = command_parser.add_parser(
        'pin',
        help='Prevent packages from being automatically upgraded.',
        description='Pinned packages are ignored by the ``upgrade`` command.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_pin)
    sub_parser.add_argument(
        'package', nargs='+', default=[], help=pkg_name_help)

    # unpin
    sub_parser = command_parser.add_parser(
        'unpin',
        help='Allows packages to be automatically upgraded.',
        description='Packages that are not pinned are automatically upgraded'
        ' by the ``upgrade`` command',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_unpin)
    sub_parser.add_argument(
        'package', nargs='+', default=[], help=pkg_name_help)

    # list
    sub_parser = command_parser.add_parser(
        'list',
        help='Lists packages.',
        description='Outputs a list of packages that match a given category.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_list)
    sub_parser.add_argument('category', nargs='?', default='installed',
                            choices=['all', 'installed', 'not_installed',
                                     'loaded', 'unloaded', 'outdated'],
                            help='Package category used to filter listing.')
    sub_parser.add_argument(
        '--nodesc', action='store_true',
        help='Do not display description text, just the package name(s).')

    # search
    sub_parser = command_parser.add_parser(
        'search',
        help='Search packages for matching names.',
        description='Perform a substring search on package names and metadata'
        ' tags.  Surround search text with slashes to indicate it is a regular'
        ' expression (e.g. ``/text/``).',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_search)
    sub_parser.add_argument(
        'search_text', nargs='+', default=[],
        help='The text(s) or pattern(s) to look for.')

    # info
    sub_parser = command_parser.add_parser(
        'info',
        help='Display package information.',
        description='Shows detailed information/metadata for given packages.'
        ' If the package is currently installed, additional information about'
        ' the status of it is displayed.  E.g. the installed version or whether'
        ' it is currently marked as "pinned" or "loaded."',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_info)
    sub_parser.add_argument(
        'package', nargs='+', default=[], help=pkg_name_help +
        ' If a single name is given and matches one of the same categories'
        ' as the "list" command, then it is automatically expanded to be the'
        ' names of all packages which match the given category.')
    sub_parser.add_argument(
        '--version', default=None,
        help='The version of the package metadata to inspect.  A version tag,'
        ' branch name, or commit hash and only one package at a time may be'
        ' given when using this flag.  If unspecified, the behavior depends'
        ' on whether the package is currently installed.  If installed,'
        ' the metadata will be pulled from the installed version.  If not'
        ' installed, the latest version tag is used, or if a package has no'
        ' version tags, the default branch, like "main" or "master", is used.')
    sub_parser.add_argument(
        '--nolocal', action='store_true',
        help='Do not read information from locally installed packages.'
        ' Instead read info from remote GitHub.')
    add_json_args(sub_parser, 'Output package information as JSON.')
    sub_parser.add_argument(
        '--allvers', action='store_true',
        help='When outputting package information as JSON, show metadata for'
        ' all versions. This option can be slow since remote repositories'
        ' may be cloned multiple times. Also, installed packages will show'
        ' metadata only for the installed version unless the --nolocal '
        ' option is given.')

    # config
    sub_parser = command_parser.add_parser(
        'config',
        help='Show Zeek Package Manager configuration info.',
        description='The default output of this command is a valid package'
        ' manager config file that corresponds to the one currently being used,'
        ' but also with any defaulted field values filled in.  This command'
        ' also allows for only the value of a specific field to be output if'
        ' the name of that field is given as an argument to the command.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_config)
    sub_parser.add_argument(
        'config_param', nargs='?', default='all',
        choices=['all', 'sources', 'user_vars', 'state_dir', 'script_dir',
                 'plugin_dir', 'bin_dir', 'zeek_dist', 'bro_dist'],
        help='Name of a specific config file field to output.')

    # autoconfig
    sub_parser = command_parser.add_parser(
        'autoconfig',
        help='Generate a Zeek Package Manager configuration file.',
        description='The output of this command is a valid package manager'
        ' config file that is generated by using the ``zeek-config`` script'
        ' that is installed along with Zeek.  It is the suggested configuration'
        ' to use for most Zeek installations.  For this command to work, the'
        ' ``zeek-config`` (or ``bro-config``) script must be in ``PATH``,'
        ' unless the --user option is given, in which case this creates'
        ' a config that does not touch the Zeek installation.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_autoconfig)
    sub_parser.add_argument(
        '--force', action='store_true',
        help='Skip any confirmation prompt.')

    # env
    sub_parser = command_parser.add_parser(
        'env',
        help='Show the value of environment variables that need to be set for'
        ' Zeek to be able to use installed packages.',
        description='This command returns shell commands that, when executed,'
        ' will correctly set ``ZEEKPATH`` and ``ZEEK_PLUGIN_PATH`` (also'
        ' ``BROPATH`` and ``BRO_PLUGIN_PATH`` for legacy compatibility) to use'
        ' scripts and plugins from packages installed by the package manager.'
        ' For this command to function properly, either have the ``zeek-config``'
        ' script (installed by zeek) in ``PATH``, or have the ``ZEEKPATH`` and'
        ' ``ZEEK_PLUGIN_PATH`` (or ``BROPATH`` and ``BRO_PLUGIN_PATH``)'
        ' environment variables already set so this command'
        ' can append package-specific paths to them.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.set_defaults(run_cmd=cmd_env)

    # create
    sub_parser = command_parser.add_parser(
        'create', help='Create a new Zeek package.',
        description='This command creates a new Zeek package in the directory'
        ' provided via --packagedir. If this directory exists, zkg will not'
        ' modify it unless you provide --force.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sub_parser.add_argument(
        '--packagedir', metavar='DIR', required=True,
        help='Output directory into which to produce the new package. Required.')
    sub_parser.add_argument(
        '--version',
        help='The template version to use.  A version tag, branch name, or'
        ' commit hash may be specified here.  If --template refers to a local'
        ' git repo with a working tree, then zkg uses it as-is and the version'
        ' is ignored.  The default for other cases is to use the latest'
        ' version tag, or if a template has none, the default branch, like'
        ' "main" or "master".')
    sub_parser.add_argument(
        '--features', nargs='+', metavar='FEATURE',
        help='Additional features to include in your package. Use the ``template'
        ' info`` command for information about available features.')
    sub_parser.add_argument(
        '--template', metavar='URL',
        help='By default, zkg uses its own package template. This makes it'
        ' select an alternative.')
    sub_parser.set_defaults(run_cmd=cmd_create)
    add_uservar_args(sub_parser)

    # Template management commands

    sub_parser = command_parser.add_parser(
        'template', help='Manage package templates.')

    template_command_parser = sub_parser.add_subparsers(
        title='template commands', dest='command',
        help='See %(prog)s <command> -h for per-command usage info.')
    template_command_parser.required = True

    # template info

    sub_parser = template_command_parser.add_parser(
        'info', help='Shows information about a package template.',
        description='This command shows versions and supported features for'
        ' a given package.')
    add_json_args(sub_parser, 'Output template information as JSON.')
    sub_parser.add_argument(
        '--version',
        help='The template version to report on.  A version tag, branch name,'
        ' or commit hash may be specified here.  If the selected template'
        ' refers to a local git repo, the version is ignored.  The default'
        ' for other cases is to use the latest version tag, or if a template'
        ' has none, the default branch, like "main" or "master".')
    sub_parser.add_argument(
        'template', metavar='URL', nargs='?',
        help='URL of a package template repository, or local path to one.'
        ' When not provided, the configured default template is used.')
    sub_parser.set_defaults(run_cmd=cmd_template_info)

    return top_parser


def main():
    args = argparser().parse_args()

    if args.verbose > 0:
        formatter = logging.Formatter(
            '%(asctime)s %(levelname)-8s %(message)s', '%Y-%m-%d %H:%M:%S')
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)

        if args.verbose == 1:
            zeekpkg.LOG.setLevel(logging.WARNING)
        elif args.verbose == 2:
            zeekpkg.LOG.setLevel(logging.INFO)
        elif args.verbose >= 3:
            zeekpkg.LOG.setLevel(logging.DEBUG)

        zeekpkg.LOG.addHandler(handler)

    configfile = args.configfile

    if not configfile:
        configfile = find_configfile(args)

    config = create_config(args, configfile)
    manager = create_manager(args, config)

    args.run_cmd(manager, args, config, configfile)

if __name__ == '__main__':
    main()
    sys.exit(0)