|
root / src / commands
commands Plain Text 6885 lines 210.6 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: build.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Build command - compile packages from ports

******************************************************************************/

module commands.build

import sys.args
import sys.process
import io.file
import io.dir
import io.path
import io.console
import core.str
import core.port
import core.config
import core.database
import core.resolver
import util.version as ver
import types
import util.color
import util.prompt
import util.checksum
import util.archive
import util.mtree
import util.http as uhttp
import exitcodes as ec
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

// Build context
type BuildContext = struct
    port: types.Port
    work_dir: string
    pkg_dir: string
    src_dir: string
    cfg: config.Config
    noclean: bool
    force_clean: bool
    log_file: string
    logging: bool
    quiet: bool
end BuildContext

// Load a port from path or find it by name
fn load_or_find_port(port_path: string): types.PortResult
    // Check if it's a valid port directory (must contain package.toml)
    // This prevents confusion with binary files or other directories with same name
    if dir.dir_exists(port_path)
        let toml_path = path.join_path(port_path, "package.toml")
        if file.fileExists(toml_path)
            color.print_action("Loading port from: " + port_path)
            return port.load(port_path)
        end if
    end if

    // Not a valid port directory, search by name
    color.print_action("Finding port: " + port_path)
    return port.find(port_path)
end load_or_find_port

fn execute(opts: types.GlobalOptions): int
    // Parse arguments
    let argc = args.count()

    // Port argument should be after the command
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Parse flags
    mut noclean = false
    mut force_clean = false
    mut quiet_flag = false
    mut verbose_flag = false
    mut install_flag = false
    mut port_path = ""

    mut i = opts.cmd_index + 1
    while i < argc
        let arg = args.get(i)
        // Skip global flags with values
        if arg == "--root" or arg == "--prefix"
            i = i + 2
            continue
        elif arg == "--no-chroot-scripts"
            i = i + 1  // valueless flag: skip only itself
            continue
        end if
        if arg == "--noclean" or arg == "-n"
            noclean = true
        elif arg == "--clean" or arg == "-c"
            force_clean = true
        elif arg == "--quiet" or arg == "-q"
            quiet_flag = true
        elif arg == "--verbose" or arg == "-v"
            verbose_flag = true
        elif arg == "--install"
            install_flag = true
        elif arg == "--no-install"
            install_flag = false
        elif not str.starts_with(arg, "-")
            if str.length(port_path) == 0
                port_path = arg
            end if
        end if
        i = i + 1
    end while

    if str.length(port_path) == 0
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Handle "." for current directory
    if port_path == "."
        port_path = res.unwrap_or(dir.current_dir(), "")
    end if

    // Load configuration
    let cfg = config.load()
    uhttp.enable_proxy(config.get_use_proxy(cfg))

    // Try to find the port by name if path doesn't exist
    let result = load_or_find_port(port_path)

    if not result.success
        color.print_error(result.error)
        return ec.EXIT_PKG_NOT_FOUND()
    end if

    let p = result.port
    color.print_success("Loaded port: " + p.info.name + " " + p.info.version)

    // Dry-run: show build plan without executing
    if opts.dry_run
        color.print_info("Dry run — would build: " + p.info.name + " " + p.info.version)
        let dry_resolve = resolver.resolve_build_deps(p.info.name)
        if dry_resolve.success and dry_resolve.count > 1
            color.print_info("Dependencies to build first:")
            mut di = 0
            while di < dry_resolve.count - 1
                let dep_port = port.find(dry_resolve.packages[di])
                if dep_port.success
                    color.print_info("  " + dry_resolve.packages[di] + " " + dep_port.port.info.version)
                else
                    color.print_info("  " + dry_resolve.packages[di])
                end if
                di = di + 1
            end while
        end if
        color.print_info("Dry run — no changes made")
        return ec.EXIT_SUCCESS()
    end if

    // Resolve, build, and install missing dependencies before building
    if not resolve_and_build_deps(p, opts, cfg)
        // Check if the failure was due to circular dependencies
        let check_result = resolver.resolve_build_deps(p.info.name)
        if not check_result.success and str.starts_with(check_result.error, "Circular")
            color.print_error("Cannot build " + p.info.name + " — circular dependency")
            return ec.EXIT_DEPS_CIRCULAR()
        end if
        color.print_error("Cannot build " + p.info.name + " — missing dependencies")
        return ec.EXIT_DEPS_UNMET()
    end if

    // Determine quiet mode: CLI flag overrides config, verbose overrides quiet
    mut quiet_mode = config.get_quiet(cfg)
    if quiet_flag
        quiet_mode = true
    end if
    if verbose_flag
        quiet_mode = false
    end if

    // Create build context
    let ctx = create_context(p, cfg, noclean, force_clean, quiet_mode)

    // Step 1: Setup directories
    if not setup_directories(ctx)
        color.print_error("Failed to create build directories")
        return ec.EXIT_ERROR()
    end if

    // Initialize logging after directories are created
    init_log(ctx)
    if ctx.logging and str.length(ctx.log_file) > 0
        log_info(ctx, "Log file: " + ctx.log_file)
    end if

    // Step 2: Download sources
    if not download_sources(ctx)
        log_error(ctx, "Failed to download sources")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_DOWNLOAD_FAILED()
    end if

    // Step 3: Verify checksums
    if not verify_checksums(ctx)
        log_error(ctx, "Checksum verification failed")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_CHECKSUM_FAILED()
    end if

    // Step 4: Extract sources
    if not extract_sources(ctx)
        log_error(ctx, "Failed to extract sources")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_EXTRACT_FAILED()
    end if

    // Step 5: Apply patches
    if not apply_patches(ctx)
        log_error(ctx, "Failed to apply patches")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_PATCH_FAILED()
    end if

    // Step 6: Run build script
    if not run_build(ctx)
        log_error(ctx, "Build failed")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_BUILD_FAILED()
    end if

    // Step 7: Compress man pages (if enabled)
    if config.get_compress_man(ctx.cfg)
        compress_man_pages(ctx)
    end if

    // Step 8: Create package
    if not create_package(ctx)
        log_error(ctx, "Failed to create package")
        print_log_location(ctx)
        cleanup_build(ctx)
        return ec.EXIT_PACKAGE_FAILED()
    end if

    // Success!
    let pkg_name = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
    let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_name)
    log_success(ctx, "Package created: " + pkg_path)

    // Cleanup work directory on success
    cleanup_build(ctx)

    // Step 9: Install the built package (only with --install)
    if install_flag
        color.print_action("Installing " + p.info.name + "...")
        let self_exe = args.get(0)
        let install_cmd = self_exe + " install -y -f \"" + pkg_path + "\""
        let install_pid = process.process_spawn_shell(install_cmd)
        if install_pid < 0
            color.print_error("Failed to launch installer for " + p.info.name)
            return ec.EXIT_INSTALL_FAILED()
        end if
        let install_exit = process.process_wait(install_pid)
        if install_exit != 0
            color.print_error("Failed to install " + p.info.name)
            return ec.EXIT_INSTALL_FAILED()
        end if
    else
        color.print_success("Package ready (use --install to install, or: coral install \"" + pkg_path + "\")")
    end if

    return ec.EXIT_SUCCESS()
end execute

proc print_usage()
    println("Usage: coral build [options] <port-path>")
    println("")
    println("Build a package from a port directory.")
    println("")
    println("Arguments:")
    println("  <port-path>    Path to port directory (use . for current)")
    println("")
    println("Options:")
    println("  --install      Install the package after building")
    println("  --no-install   Build only, do not install (default)")
    println("  -n, --noclean  Don't clean work/pkg directories after build")
    println("  -c, --clean    Force cleanup even if disabled in config")
    println("  -q, --quiet    Hide subprocess output (still logged to file)")
    println("  -v, --verbose  Show all output (overrides quiet)")
    println("")
    println("Examples:")
    println("  coral build /usr/zports/base/vim")
    println("  coral build --install base/vim")
    println("  coral build --noclean .")
    println("  coral build --quiet vim")
end print_usage

// Resolve all build dependencies recursively, build from source, and install each.
// Returns true if all dependencies are satisfied (either already installed or built+installed).
fn resolve_and_build_deps(p: types.Port, opts: types.GlobalOptions, cfg: config.Config): bool
    // Resolve the full dependency tree (runtime + build deps, recursive)
    let resolve_result = resolver.resolve_build_deps(p.info.name)

    if not resolve_result.success
        color.print_error("Dependency resolution failed: " + resolve_result.error)
        return false
    end if

    // The result includes the target package as the last element — strip it
    mut dep_count = resolve_result.count
    if dep_count > 0
        let last = resolve_result.packages[dep_count - 1]
        if str.equals(last, p.info.name)
            dep_count = dep_count - 1
        end if
    end if

    // No deps to build
    if dep_count == 0
        return true
    end if

    // Look up version info for each dep to display in the build plan
    mut dep_versions: [string] = new [string](256)
    mut i = 0
    while i < dep_count
        let dep_port_result = port.find(resolve_result.packages[i])
        if dep_port_result.success
            dep_versions[i] = dep_port_result.port.info.version
        else
            dep_versions[i] = ""
        end if
        i = i + 1
    end while

    // Show build plan and ask for confirmation
    if not prompt.confirm_build_plan(resolve_result.packages, dep_versions, dep_count, p.info.name, opts)
        color.print_info("Build cancelled")
        return false
    end if

    // Build and install each dependency in topological order
    i = 0
    while i < dep_count
        let dep_name = resolve_result.packages[i]
        println("")
        color.print_action("[" + int_to_str(i + 1) + "/" + int_to_str(dep_count) + "] Building dependency: " + dep_name)

        // Build the dependency from source
        if not build_single_port(dep_name, cfg, opts)
            color.print_error("Failed to build dependency: " + dep_name)
            return false
        end if

        // Install the built package
        let dep_port_result = port.find(dep_name)
        if not dep_port_result.success
            color.print_error("Cannot find port after build: " + dep_name)
            return false
        end if

        let dp = dep_port_result.port
        let pkg_filename = dp.info.name + "-" + dp.info.version + "-" + int_to_str(dp.info.release) + ".pkg.tar.xz"
        let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_filename)

        if not file.fileExists(pkg_path)
            color.print_error("Built package not found: " + pkg_path)
            return false
        end if

        color.print_action("Installing " + dep_name + "...")
        let self_exe = args.get(0)
        let install_cmd = self_exe + " install -y \"" + pkg_path + "\""
        let pid = process.process_spawn_shell(install_cmd)
        if pid < 0
            color.print_error("Failed to launch installer for " + dep_name)
            return false
        end if
        let exit_code = process.process_wait(pid)
        if exit_code != 0
            color.print_error("Failed to install " + dep_name)
            return false
        end if

        color.print_success("Dependency ready: " + dep_name)
        i = i + 1
    end while

    println("")
    color.print_success("All " + int_to_str(dep_count) + " dependencies built and installed")
    return true
end resolve_and_build_deps

// Build a single port from source. Used for dependency builds.
// Returns true if build succeeds and package archive is created.
fn build_single_port(name: string, cfg: config.Config, opts: types.GlobalOptions): bool
    let port_result = port.find(name)
    if not port_result.success
        color.print_error("Port not found: " + name)
        return false
    end if

    let p = port_result.port

    // Determine quiet mode
    mut quiet_mode = config.get_quiet(cfg)
    if opts.verbose
        quiet_mode = false
    end if
    if opts.quiet
        quiet_mode = true
    end if

    let ctx = create_context(p, cfg, false, false, quiet_mode)

    // Run the full build pipeline
    if not setup_directories(ctx)
        color.print_error("Failed to create build directories for " + name)
        return false
    end if

    init_log(ctx)

    if not download_sources(ctx)
        log_error(ctx, "Failed to download sources for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    if not verify_checksums(ctx)
        log_error(ctx, "Checksum verification failed for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    if not extract_sources(ctx)
        log_error(ctx, "Failed to extract sources for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    if not apply_patches(ctx)
        log_error(ctx, "Failed to apply patches for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    if not run_build(ctx)
        log_error(ctx, "Build failed for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    // Compress man pages (if enabled)
    if config.get_compress_man(cfg)
        compress_man_pages(ctx)
    end if

    if not create_package(ctx)
        log_error(ctx, "Failed to create package for " + name)
        print_log_location(ctx)
        cleanup_build(ctx)
        return false
    end if

    let pkg_filename = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
    let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_filename)
    log_success(ctx, "Package created: " + pkg_path)

    cleanup_build(ctx)
    return true
end build_single_port

fn create_context(p: types.Port, cfg: config.Config, noclean: bool, force_clean: bool, quiet: bool): BuildContext
    // New directory structure:
    //   /usr/zports/pkgs/build/<pkgname>/src/   - extracted sources, compilation
    //   /usr/zports/pkgs/build/<pkgname>/stage/ - DESTDIR for make install
    let build_base = config.get_build_dir(cfg)
    let pkg_build_dir = path.join_path(build_base, p.info.name)
    let work_dir = path.join_path(pkg_build_dir, "src")
    let pkg_dir = path.join_path(pkg_build_dir, "stage")

    // Generate log file path with timestamp (in package build root, not src/)
    let logging_enabled = config.get_logging(cfg)
    mut log_path = ""
    if logging_enabled
        log_path = path.join_path(pkg_build_dir, "coral-build-" + p.info.name + "-" + get_timestamp() + ".log")
    end if

    return BuildContext{
        port: p,
        work_dir: work_dir,
        pkg_dir: pkg_dir,
        src_dir: "",
        cfg: cfg,
        noclean: noclean,
        force_clean: force_clean,
        log_file: log_path,
        logging: logging_enabled,
        quiet: quiet
    }
end create_context

// Get current timestamp for log filename
fn get_timestamp(): string
    // Use date command to get timestamp
    let tmp_file = "/tmp/coral_ts_" + int_to_str(process.getpid()) + ".txt"
    let cmd = "date '+%Y%m%d-%H%M%S' > \"" + tmp_file + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    let ts = res.unwrap_or(file.readFile(tmp_file), "")

    // Cleanup
    let rm_cmd = "rm -f \"" + tmp_file + "\""
    let rm_pid = process.process_spawn_shell(rm_cmd)
    if rm_pid > 0
        process.process_wait(rm_pid)
    end if

    return str.trim(ts, '\n')
end get_timestamp

// Initialize log file with header
proc init_log(ctx: BuildContext)
    if not ctx.logging
        return
    end if

    mut header = "=== Coral Build Log ===\n"
    header = header + "Package: " + ctx.port.info.name + "\n"
    header = header + "Version: " + ctx.port.info.version + "\n"
    header = header + "Work Dir: " + ctx.work_dir + "\n"
    header = header + "Log File: " + ctx.log_file + "\n"
    header = header + "========================\n\n"

    file.writeFile(ctx.log_file, header)
end init_log

// Log a message to file and optionally to screen
proc log_msg(ctx: BuildContext, msg: string, show_screen: bool)
    // Always write to log file if logging enabled
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, msg + "\n")
    end if

    // Show on screen unless quiet mode suppresses it
    if show_screen
        println(msg)
    end if
end log_msg

// Log info message (always show on screen)
proc log_info(ctx: BuildContext, msg: string)
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[INFO] " + msg + "\n")
    end if
    color.print_info(msg)
end log_info

// Log success message (always show on screen)
proc log_success(ctx: BuildContext, msg: string)
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[OK] " + msg + "\n")
    end if
    color.print_success(msg)
end log_success

// Log error message (always show on screen)
proc log_error(ctx: BuildContext, msg: string)
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[ERROR] " + msg + "\n")
    end if
    color.print_error(msg)
end log_error

// Log action message (always show on screen)
proc log_action(ctx: BuildContext, msg: string)
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[ACTION] " + msg + "\n")
    end if
    color.print_action(msg)
end log_action

// Log warning message (always show on screen)
proc log_warning(ctx: BuildContext, msg: string)
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[WARN] " + msg + "\n")
    end if
    color.print_warning(msg)
end log_warning

// Print log file location (for debugging failed builds)
proc print_log_location(ctx: BuildContext)
    if ctx.logging and str.length(ctx.log_file) > 0
        color.print_info("Build log: " + ctx.log_file)
    end if
end print_log_location

// Run a shell command with output captured to log
// Returns exit code
fn run_logged_cmd(ctx: BuildContext, cmd: string): int
    if ctx.logging and str.length(ctx.log_file) > 0
        file.appendFile(ctx.log_file, "[CMD] " + cmd + "\n")
    end if

    // Build command that logs output to file
    // Redirects all output to log file to avoid tee pipeline issues
    // (tee caused SIGPIPE on long builds and masked exit codes)
    mut full_cmd = cmd
    if ctx.logging and str.length(ctx.log_file) > 0
        // Both quiet and normal mode: log to file only
        // Real-time terminal output is sacrificed for build reliability
        full_cmd = "(" + cmd + ") >> \"" + ctx.log_file + "\" 2>&1"
    else
        if ctx.quiet
            // No logging, quiet mode: suppress output
            full_cmd = "(" + cmd + ") >/dev/null 2>&1"
        end if
        // No logging, not quiet: just run normally
    end if

    // Flush stdout before spawning subprocess to ensure proper output ordering
    console.flushOutput()

    let pid = process.process_spawn_shell(full_cmd)
    if pid < 0
        return -1
    end if

    return process.process_wait(pid)
end run_logged_cmd

fn setup_directories(ctx: BuildContext): bool
    color.print_info("Setting up build directories...")

    // Create work directory
    if dir.dir_exists(ctx.work_dir)
        // Clean existing work dir
        let cmd = "rm -rf \"" + ctx.work_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            process.process_wait(pid)
        end if
    end if

    if not res.is_ok(dir.create_dir_all(ctx.work_dir))
        return false
    end if

    // Create pkg directory (for DESTDIR)
    if dir.dir_exists(ctx.pkg_dir)
        let cmd = "rm -rf \"" + ctx.pkg_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            process.process_wait(pid)
        end if
    end if

    if not res.is_ok(dir.create_dir_all(ctx.pkg_dir))
        return false
    end if

    // Ensure sources directory exists
    let sources_dir = config.get_sources_dir(ctx.cfg)
    if not dir.dir_exists(sources_dir)
        if not res.is_ok(dir.create_dir_all(sources_dir))
            return false
        end if
    end if

    // Ensure packages directory exists
    let packages_dir = config.get_packages_dir(ctx.cfg)
    if not dir.dir_exists(packages_dir)
        if not res.is_ok(dir.create_dir_all(packages_dir))
            return false
        end if
    end if

    return true
end setup_directories

fn download_sources(ctx: BuildContext): bool
    if ctx.port.sources.count == 0
        color.print_info("No sources to download")
        return true
    end if

    color.print_info("Downloading sources...")

    let sources_dir = config.get_sources_dir(ctx.cfg)

    mut i = 0
    while i < ctx.port.sources.count
        let src = ctx.port.sources.sources[i]
        let filename = src.file
        let dest = path.join_path(sources_dir, filename)

        // Check if already cached with valid checksum
        if file.fileExists(dest)
            if verify_single_checksum(dest, src.checksum)
                color.print_info("Using cached: " + filename)
                i = i + 1
                continue
            else
                // Cached file has wrong checksum, re-download
                color.print_warning("Cached file checksum mismatch, re-downloading: " + filename)
            end if
        end if

        // Try each mirror URL in order
        mut download_success = false
        mut url_idx = 0
        while url_idx < src.url_count
            let url = src.urls[url_idx]

            if url_idx > 0
                color.print_info("Trying mirror: " + url)
            end if

            // Check if this is a local file (no http:// or https:// prefix)
            if is_local_source(url)
                // Local file - copy from port directory to sources cache
                if copy_local_source(url, dest, ctx.port.port_dir)
                    if verify_single_checksum(dest, src.checksum)
                        download_success = true
                        break
                    else
                        color.print_warning("Checksum mismatch for local file, trying next...")
                        let rm_cmd = "rm -f \"" + dest + "\""
                        let rm_pid = process.process_spawn_shell(rm_cmd)
                        if rm_pid > 0
                            process.process_wait(rm_pid)
                        end if
                    end if
                end if
            else
                // Remote URL - download via HTTP
                if uhttp.download(url, dest)
                    // Verify checksum after download
                    if verify_single_checksum(dest, src.checksum)
                        download_success = true
                        break
                    else
                        color.print_warning("Checksum mismatch from mirror, trying next...")
                        // Delete bad file
                        let rm_cmd = "rm -f \"" + dest + "\""
                        let rm_pid = process.process_spawn_shell(rm_cmd)
                        if rm_pid > 0
                            process.process_wait(rm_pid)
                        end if
                    end if
                end if
            end if

            url_idx = url_idx + 1
        end while

        if not download_success
            color.print_error("Failed to download: " + filename + " (all sources failed)")
            return false
        end if

        i = i + 1
    end while

    return true
end download_sources

// Check if a URL is a local file path (not http:// or https://)
fn is_local_source(url: string): bool
    if str.starts_with(url, "http://")
        return false
    end if
    if str.starts_with(url, "https://")
        return false
    end if
    return true
end is_local_source

// Copy a local source file from port directory to sources cache
fn copy_local_source(source_path: string, dest: string, port_dir: string): bool
    // Resolve the source path
    mut full_path = source_path

    // If it's a relative path, resolve relative to port directory
    if not str.starts_with(source_path, "/")
        full_path = path.join_path(port_dir, source_path)
    end if

    // Check if file exists
    if not file.fileExists(full_path)
        color.print_error("Local source file not found: " + full_path)
        return false
    end if

    color.print_info("Copying local source: " + source_path)

    // Copy the file
    let cmd = "cp \"" + full_path + "\" \"" + dest + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Failed to copy local source: " + source_path)
        return false
    end if

    color.print_success("Copied: " + source_path)
    return true
end copy_local_source

// Verify a single file's checksum
fn verify_single_checksum(file_path: string, expected: string): bool
    // Handle special checksum values
    if str.equals(expected, "SKIP") or str.equals(expected, "BOOTSTRAP") or str.equals(expected, "skip")
        return true
    end if

    if str.length(expected) == 0
        return true
    end if

    return checksum.verify_checksum_with_algo(file_path, expected)
end verify_single_checksum

fn verify_checksums(ctx: BuildContext): bool
    if ctx.port.sources.count == 0
        return true
    end if

    color.print_info("Verifying checksums...")

    let sources_dir = config.get_sources_dir(ctx.cfg)

    mut i = 0
    while i < ctx.port.sources.count
        let src = ctx.port.sources.sources[i]
        let filename = src.file
        let file_path = path.join_path(sources_dir, filename)
        let expected = src.checksum

        // Handle special checksum values
        if str.equals(expected, "SKIP") or str.equals(expected, "BOOTSTRAP") or str.equals(expected, "skip")
            color.print_warning("Checksum verification skipped: " + filename)
        elif str.length(expected) > 0
            if not checksum.verify_checksum_with_algo(file_path, expected)
                color.print_error("Checksum mismatch: " + filename)
                return false
            end if
            color.print_success("Checksum verified: " + filename)
        else
            color.print_warning("No checksum for: " + filename)
        end if

        i = i + 1
    end while

    return true
end verify_checksums

fn extract_sources(ctx: BuildContext): bool
    if ctx.port.sources.count == 0
        return true
    end if

    color.print_info("Extracting sources...")

    let sources_dir = config.get_sources_dir(ctx.cfg)

    mut i = 0
    while i < ctx.port.sources.count
        let src = ctx.port.sources.sources[i]
        let filename = src.file
        let archive_path = path.join_path(sources_dir, filename)

        // Check extract flag
        if not src.extract
            // Copy file to work_dir instead of extracting (for patches, etc.)
            let dest_path = path.join_path(ctx.work_dir, filename)
            let cp_cmd = "cp \"" + archive_path + "\" \"" + dest_path + "\""
            let cp_pid = process.process_spawn_shell(cp_cmd)
            if cp_pid > 0
                let exit_code = process.process_wait(cp_pid)
                if exit_code != 0
                    color.print_error("Failed to copy: " + filename)
                    return false
                end if
            end if
            color.print_info("Copied (no extract): " + filename)
            i = i + 1
            continue
        end if

        if not archive.extract(archive_path, ctx.work_dir)
            color.print_error("Failed to extract: " + filename)
            return false
        end if

        color.print_success("Extracted: " + filename)
        i = i + 1
    end while

    return true
end extract_sources

fn apply_patches(ctx: BuildContext): bool
    if ctx.port.patches.count == 0
        return true
    end if

    log_info(ctx, "Applying patches...")

    let strip = ctx.port.patches.strip

    // Find the source directory (first subdirectory in work_dir)
    let find_srcdir = "cd \"" + ctx.work_dir + "\" && ls -d */ 2>/dev/null | head -1 | tr -d '/'"

    mut i = 0
    while i < ctx.port.patches.count
        let patch_file = ctx.port.patches.files[i]
        let patch_path = path.join_path(ctx.port.port_dir, patch_file)

        if not file.fileExists(patch_path)
            log_error(ctx, "Patch file not found: " + patch_file)
            return false
        end if

        // Apply patch from within the source directory
        let cmd = "cd \"" + ctx.work_dir + "/$(" + find_srcdir + ")\" && patch -p" + int_to_str(strip) + " < \"" + patch_path + "\""
        let exit_code = run_logged_cmd(ctx, cmd)
        if exit_code != 0
            log_error(ctx, "Failed to apply patch: " + patch_file)
            return false
        end if

        log_success(ctx, "Applied patch: " + patch_file)
        i = i + 1
    end while

    return true
end apply_patches

fn run_build(ctx: BuildContext): bool
    log_action(ctx, "Building " + ctx.port.info.name + "...")

    // Look for build.sh in port directory
    let build_script = path.join_path(ctx.port.port_dir, "build.sh")

    if not file.fileExists(build_script)
        log_error(ctx, "No build.sh found in port directory")
        return false
    end if

    // Set up environment
    let destdir = ctx.pkg_dir
    let cflags = config.get_cflags(ctx.cfg)
    let cxxflags = config.get_cxxflags(ctx.cfg)
    let jobs = config.get_jobs(ctx.cfg)

    mut jobs_str = ""
    if jobs > 0
        jobs_str = int_to_str(jobs)
    else
        // Auto-detect: use getconf (portable across illumos/Linux, unlike nproc)
        jobs_str = "$(getconf NPROCESSORS_ONLN 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)"
    end if

    // Find the extracted source directory (first directory in work_dir)
    // Typically the tarball extracts to a subdirectory like "zlib-1.3.1"
    let find_srcdir_cmd = "cd \"" + ctx.work_dir + "\" && ls -d */ 2>/dev/null | head -1 | tr -d '/'"

    // Determine PREFIX: package.toml override → coral.conf → default (/usr)
    mut prefix = config.get_prefix(ctx.cfg)
    if str.length(ctx.port.prefix) > 0
        prefix = ctx.port.prefix
    end if

    // Determine SYSCONFDIR: package.toml override → coral.conf → default (/etc)
    mut sysconfdir = config.get_sysconfdir(ctx.cfg)
    if str.length(ctx.port.sysconfdir) > 0
        sysconfdir = ctx.port.sysconfdir
    end if

    // PKG_ROOT is the alternate root (empty means /)
    let pkg_root = config.get_root(ctx.cfg)

    // Build the command with all environment variables
    // Per Hammerhead porting guide: no uname wrappers, replace bundled config.guess/config.sub,
    // use system config.guess for BUILD_TRIPLE (returns x86_64-zygaena-hammerhead)
    mut cmd = "cd \"" + ctx.work_dir + "\" && "
    cmd = cmd + "export SRCDIR=\"" + ctx.work_dir + "/$(" + find_srcdir_cmd + ")\" && "
    cmd = cmd + "export PKGDIR=\"" + destdir + "\" && "
    cmd = cmd + "export DESTDIR=\"" + destdir + "\" && "
    cmd = cmd + "export PREFIX=\"" + prefix + "\" && "
    cmd = cmd + "export SYSCONFDIR=\"" + sysconfdir + "\" && "
    cmd = cmd + "export PKG_ROOT=\"" + pkg_root + "\" && "
    cmd = cmd + "export JOBS=\"" + jobs_str + "\" && "
    cmd = cmd + "export CFLAGS=\"" + cflags + "\" && "
    cmd = cmd + "export CXXFLAGS=\"" + cxxflags + "\" && "
    cmd = cmd + "export LDFLAGS=\"-R" + prefix + "/lib\" && "
    cmd = cmd + "export PKG_CONFIG_PATH=\"" + prefix + "/lib/pkgconfig\" && "
    cmd = cmd + "export MAKEFLAGS=\"-j" + jobs_str + "\" && "
    cmd = cmd + "export PKG_NAME=\"" + ctx.port.info.name + "\" && "
    cmd = cmd + "export PKG_VERSION=\"" + ctx.port.info.version + "\" && "
    cmd = cmd + "export BUILD_TRIPLE=\"$(/usr/share/autoconf/build-aux/config.guess 2>/dev/null || echo x86_64-zygaena-hammerhead)\" && "
    cmd = cmd + "export PATH=\"/usr/gnu/bin:$PATH\" && "
    cmd = cmd + "export MAKE=gmake && "
    cmd = cmd + "export TAR=gtar && "
    cmd = cmd + "for _f in config.guess config.sub; do find \"$SRCDIR\" -name \"$_f\" -exec cp /usr/share/autoconf/build-aux/\"$_f\" {} \\; 2>/dev/null; done; "
    cmd = cmd + "zsh \"" + build_script + "\""

    log_info(ctx, "Running build script...")

    let exit_code = run_logged_cmd(ctx, cmd)
    if exit_code != 0
        log_error(ctx, "Build script failed with exit code: " + int_to_str(exit_code))
        return false
    end if

    log_success(ctx, "Build completed successfully")
    return true
end run_build

// Compress uncompressed man pages in the staging directory
proc compress_man_pages(ctx: BuildContext)
    // Find uncompressed man pages and gzip them
    // Uses -exec {} + (batch mode) to avoid shell escaping issues with \;
    // Uses -type f to skip symlinks (avoids creating dangling refs)
    let script = "find '" + ctx.pkg_dir + "' -type f -path '*/man/man*/*' ! -name '*.gz' ! -name '*.bz2' ! -name '*.xz' -exec gzip -9 {} +"

    let pid = process.process_spawn_shell(script)
    if pid > 0
        let exit_code = process.process_wait(pid)
        if exit_code == 0
            log_info(ctx, "Compressed man pages")
        end if
    end if
end compress_man_pages

fn create_package(ctx: BuildContext): bool
    color.print_action("Creating package...")

    // Validate that staging directory has content (not just metadata files)
    if not validate_staging_dir(ctx.pkg_dir)
        color.print_error("Staging directory is empty - build produced no files")
        color.print_error("Check that build.sh installs files to $DESTDIR or $PKGDIR")
        return false
    end if

    // Generate .PKGINFO
    if not generate_pkginfo(ctx)
        return false
    end if

    // Generate .MANIFEST (mtree file inventory)
    if not generate_manifest_file(ctx)
        return false
    end if

    // Create the package archive
    let pkg_name = ctx.port.info.name + "-" + ctx.port.info.version + "-" + int_to_str(ctx.port.info.release) + ".pkg.tar.xz"
    let pkg_path = path.join_path(config.get_packages_dir(ctx.cfg), pkg_name)

    if not archive.create_package(ctx.pkg_dir, pkg_path)
        color.print_error("Failed to create package archive")
        return false
    end if

    return true
end create_package

// Validate that staging directory has actual content (not empty)
fn validate_staging_dir(pkg_dir: string): bool
    // Count files in staging directory, excluding metadata files
    // A valid package should have at least one real file
    let cmd = "find \"" + pkg_dir + "\" -type f ! -name '.PKGINFO' ! -name '.MANIFEST' ! -name '.FOOTPRINT' | head -1"
    let tmp_file = "/tmp/coral_validate_" + int_to_str(process.getpid()) + ".txt"
    let full_cmd = cmd + " > \"" + tmp_file + "\""

    let pid = process.process_spawn_shell(full_cmd)
    if pid < 0
        return false
    end if

    process.process_wait(pid)

    // Read result
    let content = res.unwrap_or(file.readFile(tmp_file), "")

    // Clean up
    let rm_cmd = "rm -f \"" + tmp_file + "\""
    let rm_pid = process.process_spawn_shell(rm_cmd)
    if rm_pid > 0
        process.process_wait(rm_pid)
    end if

    // If content is empty, staging dir has no real files
    if str.length(content) == 0
        return false
    end if

    // Trim newlines and check again
    let trimmed = str.trim(content, '\n')
    if str.length(trimmed) == 0
        return false
    end if

    return true
end validate_staging_dir

fn generate_pkginfo(ctx: BuildContext): bool
    let pkginfo_path = path.join_path(ctx.pkg_dir, ".PKGINFO")

    mut content = "[package]\n"
    content = content + "name = \"" + ctx.port.info.name + "\"\n"
    content = content + "version = \"" + ctx.port.info.version + "\"\n"
    content = content + "release = " + int_to_str(ctx.port.info.release) + "\n"
    content = content + "description = \"" + ctx.port.info.description + "\"\n"
    content = content + "url = \"" + ctx.port.info.url + "\"\n"
    content = content + "license = \"" + ctx.port.info.license + "\"\n"
    content = content + "maintainer = \"" + ctx.port.info.maintainer + "\"\n"
    content = content + "arch = \"" + ctx.port.info.arch + "\"\n"

    // Emit [dependencies] section if there are any
    let has_runtime = ctx.port.deps.runtime_count > 0
    let has_build = ctx.port.deps.build_count > 0

    if has_runtime or has_build
        content = content + "\n[dependencies]\n"

        if has_runtime
            content = content + "runtime = ["
            mut i = 0
            while i < ctx.port.deps.runtime_count
                if i > 0
                    content = content + ", "
                end if
                content = content + "\"" + ctx.port.deps.runtime[i] + "\""
                i = i + 1
            end while
            content = content + "]\n"
        end if

        if has_build
            content = content + "build = ["
            mut i = 0
            while i < ctx.port.deps.build_count
                if i > 0
                    content = content + ", "
                end if
                content = content + "\"" + ctx.port.deps.build[i] + "\""
                i = i + 1
            end while
            content = content + "]\n"
        end if
    end if

    return res.is_ok(file.writeFile(pkginfo_path, content))
end generate_pkginfo

fn generate_manifest_file(ctx: BuildContext): bool
    let manifest_path = path.join_path(ctx.pkg_dir, ".MANIFEST")

    // Generate mtree manifest using native fs operations
    // BUG-033 (GC candidate overflow) fixed in Reef 0.5.6
    // uid/gid resolution now uses zero-allocation stat.uid_name()/gid_name()
    let content = mtree.generate_manifest(ctx.pkg_dir)
    if str.length(content) == 0
        return false
    end if

    return res.is_ok(file.writeFile(manifest_path, content))
end generate_manifest_file

proc cleanup_build(ctx: BuildContext)
    // Check if cleanup is disabled by --noclean flag
    if ctx.noclean
        color.print_info("Skipping cleanup (--noclean specified)")
        return
    end if

    // Determine cleanup behavior from config and flags
    mut clean_work = config.get_clean_work(ctx.cfg)
    mut clean_pkg = config.get_clean_pkg(ctx.cfg)

    // --clean flag forces cleanup
    if ctx.force_clean
        clean_work = true
        clean_pkg = true
    end if

    // Clean work directory
    if clean_work and dir.dir_exists(ctx.work_dir)
        color.print_info("Cleaning work directory: " + ctx.work_dir)
        let cmd = "rm -rf \"" + ctx.work_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            let exit_code = process.process_wait(pid)
            if exit_code == 0
                color.print_success("Cleaned work directory")
            else
                color.print_warning("Failed to clean work directory")
            end if
        end if
    end if

    // Clean pkg directory (DESTDIR staging)
    if clean_pkg and dir.dir_exists(ctx.pkg_dir)
        color.print_info("Cleaning pkg directory: " + ctx.pkg_dir)
        let cmd = "rm -rf \"" + ctx.pkg_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            let exit_code = process.process_wait(pid)
            if exit_code == 0
                color.print_success("Cleaned pkg directory")
            else
                color.print_warning("Failed to clean pkg directory")
            end if
        end if
    end if
end cleanup_build

// Helper: extract filename from URL
fn extract_filename(url: string): string
    let last_slash = str.last_index_of_char(url, '/')
    if last_slash < 0
        return url
    end if

    let filename = str.substring(url, last_slash + 1, str.length(url) - last_slash - 1)

    // Remove query string if present
    let query_pos = str.index_of_char(filename, '?')
    if query_pos > 0
        return str.substring(filename, 0, query_pos)
    end if

    return filename
end extract_filename

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: clean.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Clean command - remove build artifacts and caches

******************************************************************************/

module commands.clean

import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import types
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let subcommand = args.get(2)

    // Load config
    let cfg = config.load()

    if subcommand == "status"
        return show_status(cfg)
    elif subcommand == "sources"
        return clean_sources(cfg)
    elif subcommand == "packages"
        return clean_packages(cfg)
    elif subcommand == "build"
        return clean_build(cfg)
    elif subcommand == "all"
        return clean_all(cfg)
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

fn show_status(cfg: config.Config): int
    color.print_action("Build artifact status:")
    println("")

    // Built packages
    let packages_dir = config.get_packages_dir(cfg)
    let pkg_count = count_files(packages_dir, ".pkg.tar.xz")
    mut pkg_protected = ""
    if config.get_keep_packages(cfg)
        pkg_protected = " [protected]"
    end if
    println("  Packages (" + packages_dir + "):" + pkg_protected)
    println("    " + int_to_str(pkg_count) + " built package(s)")

    // Source tarballs
    let sources_dir = config.get_sources_dir(cfg)
    let src_count = count_files(sources_dir, "")
    mut src_protected = ""
    if config.get_keep_sources(cfg)
        src_protected = " [protected]"
    end if
    println("  Sources (" + sources_dir + "):" + src_protected)
    println("    " + int_to_str(src_count) + " source archive(s)")

    // Build workspace
    let build_dir = config.get_build_dir(cfg)
    let build_count = count_subdirs(build_dir)
    println("  Build (" + build_dir + "):")
    println("    " + int_to_str(build_count) + " build workspace(s)")

    return ec.EXIT_SUCCESS()
end show_status

fn clean_sources(cfg: config.Config): int
    // Respect keep_sources config unless --force is passed
    if config.get_keep_sources(cfg) and not args.has_flag("force")
        color.print_warning("Source cache is configured to be preserved (keep_sources = true)")
        color.print_info("Use --force to override")
        return ec.EXIT_SUCCESS()
    end if

    let sources_dir = config.get_sources_dir(cfg)
    color.print_action("Cleaning source archives...")
    println("  Location: " + sources_dir)

    if not dir.dir_exists(sources_dir)
        color.print_info("No sources directory to clean")
        return ec.EXIT_SUCCESS()
    end if

    let cmd = "rm -rf \"" + sources_dir + "\"/*"
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Source archives cleaned")
    return ec.EXIT_SUCCESS()
end clean_sources

fn clean_packages(cfg: config.Config): int
    // Respect keep_packages config unless --force is passed
    if config.get_keep_packages(cfg) and not args.has_flag("force")
        color.print_warning("Package cache is configured to be preserved (keep_packages = true)")
        color.print_info("Use --force to override")
        return ec.EXIT_SUCCESS()
    end if

    let packages_dir = config.get_packages_dir(cfg)
    color.print_action("Cleaning built packages...")
    println("  Location: " + packages_dir)

    if not dir.dir_exists(packages_dir)
        color.print_info("No packages directory to clean")
        return ec.EXIT_SUCCESS()
    end if

    let cmd = "rm -rf \"" + packages_dir + "\"/*"
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Built packages cleaned")
    return ec.EXIT_SUCCESS()
end clean_packages

fn clean_build(cfg: config.Config): int
    let build_dir = config.get_build_dir(cfg)
    color.print_action("Cleaning build workspaces...")
    println("  Location: " + build_dir)

    if not dir.dir_exists(build_dir)
        color.print_info("No build directory to clean")
        return ec.EXIT_SUCCESS()
    end if

    let cmd = "rm -rf \"" + build_dir + "\"/*"
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Build workspaces cleaned")
    return ec.EXIT_SUCCESS()
end clean_build

fn clean_all(cfg: config.Config): int
    color.print_action("Cleaning all build artifacts...")
    println("")

    clean_sources(cfg)
    clean_packages(cfg)
    clean_build(cfg)

    println("")
    color.print_success("All build artifacts cleaned")
    return ec.EXIT_SUCCESS()
end clean_all

fn count_files(dir_path: string, extension: string): int
    if not dir.dir_exists(dir_path)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(dir_path), new [string](0))
    let count = entries.length()

    if str.length(extension) == 0
        return count
    end if

    mut matched = 0
    mut i = 0
    while i < count
        if str.ends_with(entries[i], extension)
            matched = matched + 1
        end if
        i = i + 1
    end while

    return matched
end count_files

fn count_subdirs(dir_path: string): int
    if not dir.dir_exists(dir_path)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(dir_path), new [string](0))
    let count = entries.length()

    // Count only directories (packages being built)
    mut dirs = 0
    mut i = 0
    while i < count
        let entry = entries[i]
        if str.length(entry) > 0 and entry[0] != '.'
            let full_path = path.join_path(dir_path, entry)
            if dir.dir_exists(full_path)
                dirs = dirs + 1
            end if
        end if
        i = i + 1
    end while

    return dirs
end count_subdirs

proc print_usage()
    println("Usage: coral clean <target>")
    println("")
    println("Remove build artifacts and cached files.")
    println("")
    println("Targets:")
    println("  status    Show what can be cleaned")
    println("  sources   Remove downloaded source archives")
    println("  packages  Remove built binary packages")
    println("  build     Remove build workspaces")
    println("  all       Remove all of the above")
    println("")
    println("Locations:")
    println("  sources:  /usr/zports/pkgs/sources/")
    println("  packages: /usr/zports/pkgs/packages/")
    println("  build:    /usr/zports/pkgs/build/")
    println("")
    println("Options:")
    println("  --force   Override keep_packages/keep_sources config protection")
    println("")
    println("Note: This does NOT affect installed packages or the package database.")
    println("      Use 'coral remove' to uninstall packages.")
    println("")
    println("Examples:")
    println("  coral clean status")
    println("  coral clean build")
    println("  coral clean all")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: db.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Database command - manage package database indexes

******************************************************************************/

module commands.db

import sys.args
import io.file
import io.dir
import core.str
import core.config
import core.pkgdb
import core.portindex
import types
import util.color
import exitcodes as ec

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Subcommand should be at cmd_index + 1
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    let subcommand = args.get(opts.cmd_index + 1)

    if subcommand == "init"
        return db_init(root_path)
    elif subcommand == "rebuild"
        return db_rebuild(root_path)
    elif subcommand == "status"
        return db_status(root_path)
    elif subcommand == "dump"
        return db_dump(root_path)
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

fn db_init(root_path: string): int
    if str.length(root_path) > 0
        color.print_action("Initializing package database in " + root_path + "...")
    else
        color.print_action("Initializing package database...")
    end if
    println("")

    // Check if database already exists (use rooted version if root is set)
    let exists = check_indexes_exist(root_path)
    if exists
        color.print_warning("Database indexes already exist")
        color.print_info("Use 'coral db rebuild' to regenerate indexes")
        return ec.EXIT_SUCCESS()
    end if

    // Initialize the database directory (use rooted version if root is set)
    if not init_pkgdb(root_path)
        color.print_error("Failed to create database directory")
        return ec.EXIT_DB_ERROR()
    end if

    // Build initial indexes (use rooted version if root is set)
    if not rebuild_pkgdb(root_path)
        color.print_error("Failed to build initial indexes")
        return ec.EXIT_DB_ERROR()
    end if

    // Build ports index
    portindex.rebuild_port_index()

    let stats = get_pkgdb_stats(root_path)
    let port_count = portindex.get_port_count()
    color.print_success("Database initialized successfully")
    println("  Packages indexed: " + int_to_str(stats.package_count))
    println("  Files indexed: " + int_to_str(stats.file_count))
    println("  Ports indexed: " + int_to_str(port_count))

    return ec.EXIT_SUCCESS()
end db_init

fn db_rebuild(root_path: string): int
    if str.length(root_path) > 0
        color.print_action("Rebuilding package database indexes in " + root_path + "...")
    else
        color.print_action("Rebuilding package database indexes...")
    end if
    println("")

    // Check if db directory exists (use rooted version if root is set)
    if not init_pkgdb(root_path)
        color.print_error("Failed to access database directory")
        color.print_info("Run 'coral db init' first")
        return ec.EXIT_DB_ERROR()
    end if

    // Rebuild indexes from source of truth (use rooted version if root is set)
    if not rebuild_pkgdb(root_path)
        color.print_error("Failed to rebuild indexes")
        return ec.EXIT_DB_ERROR()
    end if

    // Rebuild ports index
    portindex.rebuild_port_index()

    let stats = get_pkgdb_stats(root_path)
    let port_count = portindex.get_port_count()
    color.print_success("Database indexes rebuilt successfully")
    println("  Packages indexed: " + int_to_str(stats.package_count))
    println("  Files indexed: " + int_to_str(stats.file_count))
    println("  Ports indexed: " + int_to_str(port_count))

    return ec.EXIT_SUCCESS()
end db_rebuild

fn db_dump(root_path: string): int
    color.print_action("Dumping files index contents...")
    println("")

    mut paths: [string] = new [string](256)
    mut owners: [string] = new [string](256)
    let count = pkgdb.dump_files_index_rooted(root_path, paths, owners, 256)

    if count == 0
        color.print_warning("No files in index or index not loaded")
        return ec.EXIT_DB_ERROR()
    end if

    println("Files in index: " + int_to_str(count))
    println("")

    mut i = 0
    while i < count
        println("  [" + int_to_str(i) + "] '" + paths[i] + "' -> '" + owners[i] + "'")
        i = i + 1
    end while

    return ec.EXIT_SUCCESS()
end db_dump

fn db_status(root_path: string): int
    if str.length(root_path) > 0
        color.print_action("Package database status for " + root_path + ":")
    else
        color.print_action("Package database status:")
    end if
    println("")

    let stats = get_pkgdb_stats(root_path)

    if not check_indexes_exist(root_path)
        color.print_warning("Database indexes not found")
        color.print_info("Run 'coral db init' to create indexes")
        println("")
        if str.length(root_path) > 0
            println("  Source of truth: " + root_path + "/var/lib/coral/installed/")
        else
            println("  Source of truth: /var/lib/coral/installed/")
        end if
        println("  Packages installed: " + int_to_str(stats.package_count))
        return ec.EXIT_DB_INDEX_STALE()
    end if

    if str.length(root_path) > 0
        println("  Index location: " + root_path + types.get_index_dir())
    else
        println("  Index location: " + types.get_index_dir())
    end if
    println("  Packages indexed: " + int_to_str(stats.package_count))
    println("  Files indexed: " + int_to_str(stats.file_count))

    if stats.packages_db_size > 0
        println("  packages.db size: " + format_size(stats.packages_db_size))
    end if
    if stats.files_db_size > 0
        println("  files.db size: " + format_size(stats.files_db_size))
    end if

    // Ports index status
    if portindex.port_index_exists()
        let port_count = portindex.get_port_count()
        println("  Ports indexed: " + int_to_str(port_count))
    else
        println("  Ports index: not built")
    end if

    return ec.EXIT_SUCCESS()
end db_status

// Helper functions for rooted pkgdb operations
fn check_indexes_exist(root_path: string): bool
    if str.length(root_path) > 0
        return pkgdb.indexes_exist_rooted(root_path)
    end if
    return pkgdb.indexes_exist()
end check_indexes_exist

fn init_pkgdb(root_path: string): bool
    if str.length(root_path) > 0
        return pkgdb.init_db_rooted(root_path)
    end if
    return pkgdb.init_db()
end init_pkgdb

fn rebuild_pkgdb(root_path: string): bool
    if str.length(root_path) > 0
        return pkgdb.rebuild_indexes_rooted(root_path)
    end if
    return pkgdb.rebuild_indexes()
end rebuild_pkgdb

fn get_pkgdb_stats(root_path: string): pkgdb.IndexStats
    if str.length(root_path) > 0
        return pkgdb.get_index_stats_rooted(root_path)
    end if
    return pkgdb.get_index_stats()
end get_pkgdb_stats

fn format_size(bytes: int): string
    if bytes < 1024
        return int_to_str(bytes) + " B"
    elif bytes < 1024 * 1024
        return int_to_str(bytes / 1024) + " KB"
    elif bytes < 1024 * 1024 * 1024
        return int_to_str(bytes / (1024 * 1024)) + " MB"
    else
        return int_to_str(bytes / (1024 * 1024 * 1024)) + " GB"
    end if
end format_size

proc print_usage()
    println("Usage: coral db <command>")
    println("")
    println("Manage package database indexes.")
    println("")
    println("Commands:")
    println("  init      Initialize database (run once during system setup)")
    println("  rebuild   Rebuild indexes from installed packages")
    println("  status    Show database status and statistics")
    println("")
    println("The package database provides fast lookups for installed packages")
    println("and file ownership. The source of truth is always the installed/")
    println("directory; indexes can be safely rebuilt at any time.")
    println("")
    println("Examples:")
    println("  coral db init")
    println("  coral db rebuild")
    println("  coral db status")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: depends.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Depends command - show package dependency tree

******************************************************************************/

module commands.depends

import sys.args
import core.str
import core.port
import core.portindex
import core.database
import core.resolver
import types
import util.color
import exitcodes as ec

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let pkg_name = args.get(2)

    // Check for --reverse flag (show what depends on this package)
    if args.has_flag("reverse") or args.has_flag("r")
        show_reverse_deps(pkg_name)
        return ec.EXIT_SUCCESS()
    end if

    // Show forward dependencies
    show_deps(pkg_name)
    return ec.EXIT_SUCCESS()
end execute

proc show_deps(name: string)
    // Find the port
    let result = port.find(name)
    if not result.success
        color.print_error("Port not found: " + name)
        return
    end if

    let p = result.port

    color.print_action("Dependencies for " + name + ":")
    println("")

    // Show runtime dependencies
    if p.deps.runtime_count == 0
        color.print_info("No runtime dependencies")
    else
        color.print_info("Runtime dependencies:")
        show_dep_tree(name, 0)
    end if

    println("")

    // Show build dependencies
    if p.deps.build_count > 0
        color.print_info("Build dependencies:")
        mut i = 0
        while i < p.deps.build_count
            print("  ")
            let dep = p.deps.build[i]
            print(dep)
            if database.is_installed(dep)
                println(" [installed]")
            else
                println("")
            end if
            i = i + 1
        end while
    end if
end show_deps

proc show_dep_tree(name: string, depth: int)
    if depth > 10
        return
    end if

    let result = port.find(name)
    if not result.success
        return
    end if

    let p = result.port

    mut i = 0
    while i < p.deps.runtime_count
        let dep = p.deps.runtime[i]

        // Print with indentation
        print_indent(depth)
        print(dep)
        if database.is_installed(dep)
            println(" [installed]")
        else
            println("")
        end if

        // Recurse
        show_dep_tree(dep, depth + 1)

        i = i + 1
    end while
end show_dep_tree

proc show_reverse_deps(name: string)
    color.print_action("Packages that depend on " + name + ":")
    println("")

    mut found = 0

    // Try ports index first (fast path)
    if portindex.port_index_exists()
        mut results: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](512)
        let result_count = portindex.find_reverse_deps(name, results, 512)

        mut i = 0
        while i < result_count
            let entry = results[i]
            print("  ")
            print(entry.category)
            print("/")
            print(entry.name)
            if database.is_installed(entry.name)
                println(" [installed]")
            else
                println("")
            end if
            found = found + 1
            i = i + 1
        end while
    else
        // Fall back to filesystem scan
        mut cats: [string] = new [string](32)
        let cat_count = port.get_categories(cats, 32)

        mut i = 0
        while i < cat_count
            let category = cats[i]
            mut ports: [string] = new [string](256)
            let port_count = port.list_category(category, ports, 256)

            mut j = 0
            while j < port_count
                let port_name = ports[j]
                if depends_on(port_name, name)
                    print("  ")
                    print(category)
                    print("/")
                    print(port_name)
                    if database.is_installed(port_name)
                        println(" [installed]")
                    else
                        println("")
                    end if
                    found = found + 1
                end if
                j = j + 1
            end while

            i = i + 1
        end while
    end if

    if found == 0
        color.print_info("No packages depend on " + name)
    else
        println("")
        color.print_info("Total: " + int_to_str(found) + " package(s)")
    end if
end show_reverse_deps

fn depends_on(pkg_name: string, dep_name: string): bool
    let result = port.find(pkg_name)
    if not result.success
        return false
    end if

    let p = result.port

    // Check runtime deps
    mut i = 0
    while i < p.deps.runtime_count
        if p.deps.runtime[i] == dep_name
            return true
        end if
        i = i + 1
    end while

    // Check build deps
    i = 0
    while i < p.deps.build_count
        if p.deps.build[i] == dep_name
            return true
        end if
        i = i + 1
    end while

    return false
end depends_on

proc print_indent(depth: int)
    mut i = 0
    while i < depth
        print("  ")
        i = i + 1
    end while
    print("  ")  // Base indent
end print_indent

proc print_usage()
    println("Usage: coral depends <package> [options]")
    println("")
    println("Show dependency tree for a package.")
    println("")
    println("Arguments:")
    println("  <package>    Name of package to show dependencies for")
    println("")
    println("Options:")
    println("  -r, --reverse    Show packages that depend on this package")
    println("")
    println("Examples:")
    println("  coral depends vim")
    println("  coral depends vim --reverse")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: files.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Files command - list files owned by a package

******************************************************************************/

module commands.files

import sys.args
import core.str
import core.config
import core.database
import types
import util.color
import exitcodes as ec

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Package name should be at cmd_index + 1
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    let pkg_name = args.get(opts.cmd_index + 1)

    // Check if installed (use rooted version if root is set)
    if not check_installed(pkg_name, root_path)
        color.print_error(pkg_name + " is not installed")
        return ec.EXIT_PKG_NOT_FOUND()
    end if

    // Get files (use rooted version if root is set)
    mut files: [string] = new [string](4096)
    let file_count = get_files_list(pkg_name, files, 4096, root_path)

    if file_count == 0
        color.print_info("No files recorded for " + pkg_name)
        return ec.EXIT_SUCCESS()
    end if

    color.print_action("Files owned by " + pkg_name + ":")
    println("")

    mut i = 0
    while i < file_count
        println("/" + files[i])
        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(file_count) + " files")
    return ec.EXIT_SUCCESS()
end execute

// Helper functions for rooted operations
fn check_installed(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end check_installed

fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.get_files_rooted(name, files, max_count, root_path)
    end if
    return database.get_files(name, files, max_count)
end get_files_list

proc print_usage()
    println("Usage: coral files <package>")
    println("")
    println("List all files owned by an installed package.")
    println("")
    println("Arguments:")
    println("  <package>    Name of installed package")
    println("")
    println("Examples:")
    println("  coral files vim")
    println("  coral files hello")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: info.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Info command - display package information

******************************************************************************/

module commands.info

import sys.args
import core.str
import core.config
import core.database
import core.port
import types
import util.color
import exitcodes as ec

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Package name should be at cmd_index + 1
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    let pkg_name = args.get(opts.cmd_index + 1)

    // Check if installed (use rooted version if root is set)
    let is_installed = check_installed(pkg_name, root_path)

    // Find port
    let port_result = port.find(pkg_name)

    if not is_installed and not port_result.success
        color.print_error("Package not found: " + pkg_name)
        return ec.EXIT_PKG_NOT_FOUND()
    end if

    // Print package info
    if is_installed
        let installed_pkg = get_installed_pkg(pkg_name, root_path)
        print_installed_info(installed_pkg)

        if port_result.success
            let p = port_result.port
            // Check if upgrade available
            if str.compare(installed_pkg.info.version, p.info.version) < 0
                println("")
                color.print_info("Upgrade available: " + p.info.version)
            end if
        end if
    else
        // Not installed, show port info
        let p = port_result.port
        print_port_info(p)
    end if
    return ec.EXIT_SUCCESS()
end execute

// Helper functions for rooted operations
fn check_installed(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end check_installed

fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_installed_pkg

proc print_usage()
    println("Usage: coral info <package>")
    println("")
    println("Display detailed information about a package.")
    println("")
    println("Arguments:")
    println("  <package>    Name of package to show info for")
    println("")
    println("Examples:")
    println("  coral info vim")
    println("  coral info hello")
end print_usage

proc print_installed_info(pkg: types.InstalledPackage)
    color.print_action("Package: " + pkg.info.name)
    println("")
    println("Status:       installed")
    println("Version:      " + pkg.info.version + "-" + int_to_str(pkg.info.release))
    println("Description:  " + pkg.info.description)
    println("URL:          " + pkg.info.url)
    println("License:      " + pkg.info.license)
    println("Maintainer:   " + pkg.info.maintainer)
    println("Architecture: " + pkg.info.arch)
    println("")
    println("Install date: " + pkg.install_date)
    println("Reason:       " + pkg.install_reason)
    println("Files:        " + int_to_str(pkg.files_count))
end print_installed_info

proc print_port_info(p: types.Port)
    color.print_action("Port: " + p.info.name)
    println("")
    println("Status:       not installed")
    println("Version:      " + p.info.version + "-" + int_to_str(p.info.release))
    println("Description:  " + p.info.description)
    println("URL:          " + p.info.url)
    println("License:      " + p.info.license)
    println("Maintainer:   " + p.info.maintainer)
    println("Architecture: " + p.info.arch)

    // Show dependencies if any
    if p.deps.runtime_count > 0
        println("")
        print("Depends on:   ")
        mut i = 0
        while i < p.deps.runtime_count
            if i > 0
                print(", ")
            end if
            print(p.deps.runtime[i])
            i = i + 1
        end while
        println("")
    end if

    if p.deps.build_count > 0
        println("")
        print("Build deps:   ")
        mut i = 0
        while i < p.deps.build_count
            if i > 0
                print(", ")
            end if
            print(p.deps.build[i])
            i = i + 1
        end while
        println("")
    end if
end print_port_info

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: install.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Install command - install packages from archives

******************************************************************************/

module commands.install

import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.pkgdb
import core.package
import core.groups
import core.repository
import core.signing
import core.resolver
import core.port
import core.portindex
import util.checksum
import util.mtree
import util.http as uhttp
import util.prompt
import util.version as ver
import types
import util.color
import util.priv
import exitcodes as ec
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Package arguments start after the command
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    uhttp.enable_proxy(config.get_use_proxy(cfg))

    // Auto-refresh port index if configured
    if config.get_auto_refresh(cfg)
        portindex.rebuild_port_index()
    end if

    // Show root/prefix if set (verbose mode)
    if opts.verbose
        let root = config.get_root(cfg)
        let prefix = config.get_prefix(cfg)
        if str.length(root) > 0
            color.print_info("Using root: " + root)
        end if
        if str.length(prefix) > 0
            color.print_info("Using prefix: " + prefix)
        end if
    end if

    // Collect all packages to install (expanding groups)
    mut packages: [string] = new [string](256)
    mut pkg_count = 0
    mut direct_files: [string] = new [string](16)
    mut direct_count = 0

    // Process each package argument (starting after the command)
    mut i = opts.cmd_index + 1
    while i < argc and pkg_count < 256
        let pkg_arg = args.get(i)

        // Skip flags and their values
        if pkg_arg == "--root" or pkg_arg == "--prefix"
            i = i + 2  // Skip flag and its value
            continue
        elif pkg_arg == "--no-chroot-scripts"
            i = i + 1  // valueless flag: skip only itself
            continue
        end if
        if str.starts_with(pkg_arg, "-")
            i = i + 1
            continue
        end if

        // Check if this is a direct file path to a .pkg.tar.xz
        if str.ends_with(pkg_arg, ".pkg.tar.xz") and file.fileExists(pkg_arg)
            direct_files[direct_count] = pkg_arg
            direct_count = direct_count + 1
            i = i + 1
            continue
        end if

        // Check if this is a group reference
        if groups.is_group(pkg_arg)
            // Expand group to member packages
            mut group_members: [string] = new [string](128)
            let member_count = groups.expand_group(pkg_arg, group_members, 128)

            if member_count == 0
                color.print_error("Group not found or empty: " + pkg_arg)
                i = i + 1
                continue
            end if

            color.print_info("Expanding group " + pkg_arg + " (" + int_to_str(member_count) + " packages)")

            // Add all group members to packages list
            mut j = 0
            while j < member_count and pkg_count < 256
                packages[pkg_count] = group_members[j]
                pkg_count = pkg_count + 1
                j = j + 1
            end while
        else
            // Regular package
            packages[pkg_count] = pkg_arg
            pkg_count = pkg_count + 1
        end if

        i = i + 1
    end while

    // Handle direct file installs — bypass resolver, install immediately
    if direct_count > 0
        let root = get_root(cfg)
        let root_for_db = config.get_root(cfg)
        if str.length(root_for_db) > 0
            if not database.init_db_rooted(root_for_db)
                color.print_error("Failed to initialize database in " + root_for_db)
                return ec.EXIT_DB_ERROR()
            end if
        else
            if not database.init_db()
                color.print_error("Failed to initialize package database")
                return ec.EXIT_DB_ERROR()
            end if
        end if

        mut di = 0
        while di < direct_count
            if not install_package(direct_files[di], cfg, root_for_db, opts)
                color.print_error("Failed to install: " + direct_files[di])
                return ec.EXIT_INSTALL_FAILED()
            end if
            di = di + 1
        end while

        if pkg_count == 0
            return ec.EXIT_SUCCESS()
        end if
    end if

    // Resolve dependencies for all packages
    // Use rooted resolver if installing to alternate root
    mut install_order: [string] = new [string](512)
    let root_for_resolve = config.get_root(cfg)
    mut install_count = 0
    if str.length(root_for_resolve) > 0
        install_count = resolver.get_install_order_rooted(packages, pkg_count, install_order, 512, root_for_resolve)
    else
        install_count = resolver.get_install_order(packages, pkg_count, install_order, 512)
    end if

    // When force/reinstall is set, add requested packages that the resolver
    // skipped (because they're already installed) back into the install order
    if opts.force and install_count < pkg_count
        mut fi = 0
        while fi < pkg_count
            let pkg = packages[fi]
            if not array_contains(install_order, install_count, pkg)
                install_order[install_count] = pkg
                install_count = install_count + 1
            end if
            fi = fi + 1
        end while
    end if

    if install_count == 0 and pkg_count > 0
        color.print_warning("No packages to install (all already installed or not found)")
        return ec.EXIT_SUCCESS()
    end if

    // Separate new installs from already-installed (for display)
    mut to_install: [string] = new [string](512)
    mut install_idx = 0

    mut dep_idx = 0
    while dep_idx < install_count
        to_install[install_idx] = install_order[dep_idx]
        install_idx = install_idx + 1
        dep_idx = dep_idx + 1
    end while

    // Ask for confirmation (unless -y flag)
    mut empty_upgrade: [string] = new [string](1)
    if not prompt.confirm_install(to_install, install_idx, empty_upgrade, 0, opts)
        color.print_info("Installation cancelled")
        return ec.EXIT_CANCELLED()
    end if

    // Dry-run: show what would be done and exit
    if opts.dry_run
        color.print_info("Dry run — no changes made")
        return ec.EXIT_SUCCESS()
    end if

    // Get root path for installation
    let root = get_root(cfg)

    // Initialize database in the target root
    let root_for_db = config.get_root(cfg)
    if str.length(root_for_db) > 0
        if not database.init_db_rooted(root_for_db)
            color.print_error("Failed to initialize database in " + root_for_db)
            return ec.EXIT_DB_ERROR()
        end if
    else
        if not database.init_db()
            color.print_error("Failed to initialize package database")
            return ec.EXIT_DB_ERROR()
        end if
    end if

    // Install all packages in resolved order (dependencies first)
    i = 0
    while i < install_count
        let pkg_arg = install_order[i]

        // Install this package
        if not install_package(pkg_arg, cfg, root_for_db, opts)
            color.print_error("Failed to install: " + pkg_arg)
            color.print_error("Aborting installation - dependency failed")
            return ec.EXIT_INSTALL_FAILED()
        end if

        i = i + 1
    end while

    return ec.EXIT_SUCCESS()
end execute

// Helper to check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
    mut i = 0
    while i < count
        if str.equals(arr[i], s)
            return true
        end if
        i = i + 1
    end while
    return false
end array_contains

proc print_usage()
    println("Usage: coral install <package...>")
    println("")
    println("Install one or more packages.")
    println("")
    println("Arguments:")
    println("  <package>    Package name or path to .pkg.tar.xz file")
    println("")
    println("Options:")
    println("  -y, --yes    Don't ask for confirmation")
    println("  --force      Force reinstall if already installed")
    println("")
    println("Examples:")
    println("  coral install vim")
    println("  coral install /path/to/package.pkg.tar.xz")
    println("  coral install vim nano htop")
end print_usage

fn install_package(pkg_arg: string, cfg: config.Config, root_path: string, opts: types.GlobalOptions): bool
    // Determine if this is a file path or package name
    let pkg_path = resolve_package_path(pkg_arg, cfg)

    if str.length(pkg_path) == 0
        color.print_error("Package not found: " + pkg_arg)
        return false
    end if

    // Verify signature if required (for local packages not already verified by resolve_package_path)
    let require_signed = config.get_require_signed_packages(cfg)
    if require_signed
        let sig_path = pkg_path + ".sig"
        if file.fileExists(sig_path)
            color.print_info("Verifying package signature...")
            let verify_result = signing.verify_package(pkg_path, sig_path)
            if not verify_result.success or not verify_result.valid
                color.print_error("Signature verification failed: " + verify_result.error)
                return false
            end if
            color.print_success("Signature verified (key: " + verify_result.keyid + ")")
        else
            color.print_error("Package signature required but not found: " + sig_path)
            return false
        end if
    end if

    color.print_action("Installing " + pkg_arg + "...")

    // Create extraction directory
    let extract_dir = create_extract_dir(cfg)
    if str.length(extract_dir) == 0
        color.print_error("Failed to create extraction directory")
        return false
    end if

    // Extract package
    color.print_info("Extracting package...")
    let result = package.extract_package(pkg_path, extract_dir)
    if not result.success
        color.print_error(result.error)
        cleanup_extract_dir(extract_dir)
        return false
    end if

    // Read package info
    let info = package.read_pkginfo(extract_dir)
    if str.length(info.name) == 0
        color.print_error("Failed to read package info")
        cleanup_extract_dir(extract_dir)
        return false
    end if

    color.print_info("Package: " + info.name + " " + info.version)

    // Check for conflicts with installed packages
    if info.conflicts_count > 0
        mut ci = 0
        while ci < info.conflicts_count
            let conflict = info.conflicts[ci]
            if check_installed(conflict, root_path)
                color.print_error("Package " + info.name + " conflicts with installed package: " + conflict)
                if not opts.force
                    color.print_error("Use --force to override conflict check")
                    cleanup_extract_dir(extract_dir)
                    return false
                end if
                color.print_warning("Proceeding despite conflict (--force specified)")
            end if
            ci = ci + 1
        end while
    end if

    // Check if already installed (in target root)
    let already_installed = check_installed(info.name, root_path)
    mut is_upgrade = false
    mut old_version = ""

    if already_installed
        // Get old package info to check version
        let old_pkg = get_old_installed(info.name, root_path)
        old_version = old_pkg.info.version

        if not str.equals(old_version, info.version)
            // Different version — upgrade
            is_upgrade = true
            color.print_info("Upgrading " + info.name + " " + old_version + " -> " + info.version)
        else
            // Same version — skip or reinstall with --force
            if not opts.force
                color.print_warning(info.name + " " + info.version + " is already installed (use --force to reinstall)")
                cleanup_extract_dir(extract_dir)
                return true
            end if
            color.print_info("Reinstalling " + info.name + "...")
        end if
    end if

    let install_root = get_root(cfg)
    // Resolve script execution context; abort early if confinement is required but impossible.
    // Defense-in-depth: main.reef already bars non-root for all non-query commands, so this abort
    // is currently unreachable via the CLI. Kept so confinement fails safely if that global gate is
    // ever relaxed.
    if package.script_wants_chroot(install_root, config.get_chroot_scripts(cfg)) and not priv.is_root()
        color.print_error("--root " + install_root + " runs maintainer scripts confined to the target via chroot, which requires root privileges.")
        color.print_error("Re-run as root, or pass --no-chroot-scripts to run them on the host (unconfined).")
        cleanup_extract_dir(extract_dir)
        return false
    end if
    let script_ctx = package.resolve_script_ctx(install_root, config.get_chroot_scripts(cfg), priv.is_root())

    if is_upgrade
        // Upgrade flow: pre-upgrade → remove old files → install new files → post-upgrade

        // Run pre-upgrade from stored scripts (old package)
        let old_scripts = database.get_scripts_dir(info.name)
        if database.has_stored_scripts(info.name)
            color.print_info("Running pre-upgrade script...")
            if not package.run_stored_pre_upgrade(script_ctx, old_scripts, old_version, info.version)
                color.print_error("Pre-upgrade script failed, aborting")
                cleanup_extract_dir(extract_dir)
                return false
            end if
        end if

        // Remove old files
        color.print_info("Removing old version files...")
        mut old_files: [string] = new [string](4096)
        let old_file_count = get_old_files(info.name, old_files, 4096, root_path)
        if old_file_count > 0
            package.remove_files(old_files, old_file_count, install_root)
        end if

        // Load old manifest for config file checksum protection
        mut old_manifest_entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
        let old_manifest_count = load_old_manifest(info.name, root_path, old_manifest_entries, 8192)

        // Install new files (with upgrade config protection)
        color.print_info("Installing files...")
        if old_manifest_count > 0
            if not package.install_files_upgrade(extract_dir, install_root, old_manifest_entries, old_manifest_count)
                color.print_error("Failed to install files")
                cleanup_extract_dir(extract_dir)
                return false
            end if
        else
            if not package.install_files(extract_dir, install_root)
                color.print_error("Failed to install files")
                cleanup_extract_dir(extract_dir)
                return false
            end if
        end if

        // Run post-upgrade from new package's scripts
        if package.has_scripts(extract_dir)
            color.print_info("Running post-upgrade script...")
            if not package.run_post_upgrade(script_ctx, extract_dir, old_version, info.version)
                color.print_warning("Post-upgrade script failed")
            end if
        end if
    else
        // Fresh install flow

        // Run pre-install script (abort on failure)
        if package.has_scripts(extract_dir)
            color.print_info("Running pre-install script...")
            if not package.run_pre_install(script_ctx, extract_dir, info.version)
                color.print_error("Pre-install script failed")
                cleanup_extract_dir(extract_dir)
                return false
            end if
        end if

        // Install files to target root
        color.print_info("Installing files...")
        if not package.install_files(extract_dir, install_root)
            color.print_error("Failed to install files")
            cleanup_extract_dir(extract_dir)
            return false
        end if

        // Run post-install script (warn on failure, don't abort)
        if package.has_scripts(extract_dir)
            color.print_info("Running post-install script...")
            if not package.run_post_install(script_ctx, extract_dir, info.version)
                color.print_warning("Post-install script failed")
            end if
        end if
    end if

    // Register in database (use rooted version if root is set)
    color.print_info("Registering package...")
    if not register_installed_fast_rooted(info, extract_dir, root_path)
        color.print_error("Failed to register package in database")
        // Files are installed but not registered - warn but don't fail
    end if

    // Store scripts for later use (removal)
    if package.has_scripts(extract_dir)
        if not store_scripts_rooted(info.name, extract_dir, root_path)
            color.print_warning("Failed to store scripts for removal")
        end if
    end if

    // Store config files list for upgrade handling
    if not store_config_files_rooted(info.name, extract_dir, root_path)
        color.print_warning("Failed to store config files list")
    end if

    // Update package database indexes
    if not pkgdb.rebuild_indexes_rooted(root_path)
        color.print_warning("Failed to update package indexes")
    end if

    // Cleanup
    cleanup_extract_dir(extract_dir)

    color.print_success("Installed " + info.name + " " + info.version)
    return true
end install_package

// Check if package is installed, using rooted check if root is set
fn check_installed(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end check_installed

// Register package using rooted version if root is set
fn register_installed_fast_rooted(info: types.PackageInfo, extract_dir: string, root_path: string): bool
    mut files: [string] = new [string](1)
    mut pkg = new_installed_pkg(info, files, 0)

    if str.length(root_path) > 0
        return database.register_from_extract_dir_rooted(pkg, extract_dir, root_path)
    end if
    return database.register_from_extract_dir(pkg, extract_dir)
end register_installed_fast_rooted

// Store scripts using rooted version if root is set
fn store_scripts_rooted(name: string, extract_dir: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.store_scripts_rooted(name, extract_dir, root_path)
    end if
    return database.store_scripts(name, extract_dir)
end store_scripts_rooted

// Store config files using rooted version if root is set
fn store_config_files_rooted(name: string, extract_dir: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.store_config_files_rooted(name, extract_dir, root_path)
    end if
    return database.store_config_files(name, extract_dir)
end store_config_files_rooted

// Find package file - either direct path, repository, or search in packages directory
fn resolve_package_path(pkg_arg: string, cfg: config.Config): string
    // If it's a file path that exists, use it directly
    if file.fileExists(pkg_arg)
        return pkg_arg
    end if

    // Search in local packages cache first
    let packages_dir = config.get_packages_dir(cfg)

    // Find all matching packages and select highest version
    let entries = res.unwrap_or(dir.list_dir(packages_dir), new [string](0))
    let entry_count = entries.length()

    // Collect all matching package files
    mut best_file = ""
    mut best_version = ""
    mut best_release = 0

    mut i = 0
    while i < entry_count
        let entry = entries[i]
        // Check if entry starts with package name and has correct suffix
        if str.starts_with(entry, pkg_arg + "-") and str.ends_with(entry, ".pkg.tar.xz")
            // Extract version from filename
            let entry_version = ver.extract_version_from_filename(entry, pkg_arg)
            let entry_release = ver.extract_release_from_filename(entry)

            // Compare with current best
            if str.length(best_file) == 0
                // First match
                best_file = entry
                best_version = entry_version
                best_release = entry_release
            else
                // Compare versions
                let cmp = ver.compare_versions(entry_version, best_version)
                if cmp > 0
                    // Entry has higher version
                    best_file = entry
                    best_version = entry_version
                    best_release = entry_release
                elif cmp == 0 and entry_release > best_release
                    // Same version but higher release
                    best_file = entry
                    best_version = entry_version
                    best_release = entry_release
                end if
            end if
        end if
        i = i + 1
    end while

    // Return the best matching package
    if str.length(best_file) > 0
        return path.join_path(packages_dir, best_file)
    end if

    // Also try with .pkg.tar.xz appended
    let direct_path = path.join_path(packages_dir, pkg_arg + ".pkg.tar.xz")
    if file.fileExists(direct_path)
        return direct_path
    end if

    // Try to build from source if configured
    if config.get_fallback_to_source(cfg)
        let port_result = port.find(pkg_arg)
        if port_result.success
            color.print_info("No binary package found for " + pkg_arg + ", building from source...")
            let build_cmd = "coral build -y " + pkg_arg
            let build_pid = process.process_spawn_shell(build_cmd)
            if build_pid > 0
                let build_exit = process.process_wait(build_pid)
                if build_exit == 0
                    // Build succeeded, look for the package it produced
                    let p = port_result.port
                    let built_pkg = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
                    let built_path = path.join_path(packages_dir, built_pkg)
                    if file.fileExists(built_path)
                        return built_path
                    end if
                end if
            end if
            color.print_warning("Source build failed for " + pkg_arg + ", trying repositories...")
        end if
    end if

    // Try to find in repositories and download
    let remote_result = repository.find_remote_package(pkg_arg)
    if remote_result.success
        let remote_pkg = remote_result.pkg
        color.print_info("Found " + pkg_arg + " " + remote_pkg.version + " in repository: " + remote_pkg.repo_name)

        // Download the package
        let downloaded_path = repository.download_package(remote_pkg)
        if str.length(downloaded_path) > 0
            // Verify checksum if available
            if str.length(remote_pkg.sha256) > 0
                color.print_info("Verifying checksum...")
                if not checksum.verify_checksum(downloaded_path, remote_pkg.sha256)
                    color.print_error("Checksum verification failed!")
                    return ""
                end if
                color.print_success("Checksum verified")
            end if

            // Verify signature if required or available
            let require_signed = config.get_require_signed_packages(cfg)
            if require_signed or str.length(remote_pkg.signature) > 0
                let sig_path = downloaded_path + ".sig"

                // Download signature file if we don't have it
                if not file.fileExists(sig_path) and str.length(remote_pkg.signature) > 0
                    color.print_info("Downloading signature...")
                    let sig_url = get_sig_url(remote_pkg)
                    if not download_signature(sig_url, sig_path)
                        if require_signed
                            color.print_error("Failed to download package signature")
                            return ""
                        else
                            color.print_warning("Could not download signature, skipping verification")
                        end if
                    end if
                end if

                // Verify signature if we have it
                if file.fileExists(sig_path)
                    color.print_info("Verifying signature...")
                    let verify_result = signing.verify_package(downloaded_path, sig_path)
                    if verify_result.success and verify_result.valid
                        color.print_success("Signature verified (key: " + verify_result.keyid + ")")
                    else
                        if require_signed
                            color.print_error("Signature verification failed: " + verify_result.error)
                            return ""
                        else
                            color.print_warning("Signature verification failed: " + verify_result.error)
                        end if
                    end if
                elif require_signed
                    color.print_error("Package signature required but not available")
                    return ""
                end if
            end if

            return downloaded_path
        end if
    end if

    return ""
end resolve_package_path

// Create a temporary extraction directory
fn create_extract_dir(cfg: config.Config): string
    let work_dir = config.get_work_dir(cfg)
    let pid = process.getpid()
    let extract_dir = path.join_path(work_dir, "install_" + int_to_str(pid))

    if dir.dir_exists(extract_dir)
        // Clean existing
        let cmd = "rm -rf \"" + extract_dir + "\""
        let rm_pid = process.process_spawn_shell(cmd)
        if rm_pid > 0
            process.process_wait(rm_pid)
        end if
    end if

    if not res.is_ok(dir.create_dir_all(extract_dir))
        return ""
    end if

    return extract_dir
end create_extract_dir

// Cleanup extraction directory
fn cleanup_extract_dir(dir_path: string): bool
    if str.length(dir_path) == 0
        return true
    end if

    let cmd = "rm -rf \"" + dir_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if
    process.process_wait(pid)
    return true
end cleanup_extract_dir

// Get installation root from config (can be overridden with --root)
fn get_root(cfg: config.Config): string
    let root = config.get_root(cfg)
    if str.length(root) == 0
        return "/"
    end if
    return root
end get_root

// Check for file conflicts with other installed packages
// TODO: Implement efficient conflict detection using a file database
fn check_conflicts(files: [string], file_count: int, pkg_name: string): bool
    // Skip conflict checking for performance - file overwrites are handled
    // by the manifest-driven installer and dependencies are managed separately
    return true
end check_conflicts

// Helper to create InstalledPackage
fn new_installed_pkg(info: types.PackageInfo, files: [string], file_count: int): types.InstalledPackage
    mut pkg = types.new_installed_package()
    pkg.info = info
    pkg.install_date = get_date_string()
    pkg.install_reason = "explicit"
    pkg.files = files
    pkg.files_count = file_count
    return pkg
end new_installed_pkg

// Get current date as string (simplified)
fn get_date_string(): string
    // Use date command for simplicity
    // TODO: Use proper time functions when available
    return "2025-01-24"
end get_date_string

// Get installed package info (root-aware)
fn get_old_installed(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_old_installed

// Get old file list for a package (root-aware)
fn get_old_files(name: string, files: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.get_files_rooted(name, files, max_count, root_path)
    end if
    return database.get_files(name, files, max_count)
end get_old_files

// Load old manifest from database for upgrade config protection
fn load_old_manifest(name: string, root_path: string, entries: [mtree.ManifestEntry], max_count: int): int
    let manifest_path = database.get_manifest_path(name)
    if not file.fileExists(manifest_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(manifest_path), "")
    if str.length(content) == 0
        return 0
    end if

    return mtree.parse_manifest(content, entries, max_count)
end load_old_manifest

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

// Build signature URL from remote package info
fn get_sig_url(pkg: repository.RemotePackage): string
    mut base_url = pkg.repo_url
    if not str.ends_with(base_url, "/")
        base_url = base_url + "/"
    end if

    // If signature field contains a full URL, use it
    if str.starts_with(pkg.signature, "http")
        return pkg.signature
    end if

    // Otherwise construct from filename
    return base_url + "packages/" + pkg.filename + ".sig"
end get_sig_url

// Download a signature file
fn download_signature(url: string, dest: string): bool
    return uhttp.download(url, dest)
end download_signature

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: key.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Key command - manage signing keys

******************************************************************************/

module commands.key

import sys.args
import sys.process
import io.file
import io.dir
import core.str
import core.signing
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let subcommand = args.get(2)

    if subcommand == "list"
        list_keys()
        return ec.EXIT_SUCCESS()
    elif subcommand == "generate"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key generate <name>")
            return ec.EXIT_USAGE()
        end if
        generate_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "import"
        if argc < 4
            color.print_error("Missing key file")
            println("Usage: coral key import <file> [name]")
            return ec.EXIT_USAGE()
        end if
        let key_file = args.get(3)
        mut name = ""
        if argc >= 5
            name = args.get(4)
        end if
        import_key(key_file, name)
        return ec.EXIT_SUCCESS()
    elif subcommand == "export"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key export <name>")
            return ec.EXIT_USAGE()
        end if
        export_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "delete"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key delete <name>")
            return ec.EXIT_USAGE()
        end if
        delete_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "init"
        init_keyring()
        return ec.EXIT_SUCCESS()
    elif subcommand == "trust"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key trust <name>")
            return ec.EXIT_USAGE()
        end if
        trust_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "revoke"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key revoke <name>")
            return ec.EXIT_USAGE()
        end if
        revoke_key(args.get(3))
        return ec.EXIT_SUCCESS()
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

proc list_keys()
    color.print_action("Signing keys:")
    println("")

    mut keys: [signing.KeyPair] = new [signing.KeyPair](64)
    let count = signing.list_keys(keys, 64)

    if count == 0
        color.print_info("No keys found")
        println("")
        color.print_info("Generate a key with: coral key generate <name>")
        return
    end if

    mut i = 0
    while i < count
        let key = keys[i]
        print("  ")
        print(key.name)
        if str.length(key.private_key) > 0
            print(" [private+public]")
        else
            print(" [public only]")
        end if
        if key.trusted
            print(" [trusted]")
        end if
        println("")
        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(count) + " key(s)")
end list_keys

proc generate_key(name: string)
    color.print_action("Generating Ed25519 keypair: " + name)

    let result = signing.generate_keypair(name)

    if result.success
        color.print_success("Keypair generated successfully")
        println("")
        color.print_info("Private key: " + signing.get_keyring_dir() + "/" + name + ".key")
        color.print_info("Public key:  " + signing.get_keyring_dir() + "/" + name + ".pub")
    else
        color.print_error(result.error)
    end if
end generate_key

proc import_key(key_file: string, name: string)
    if not file.fileExists(key_file)
        color.print_error("Key file not found: " + key_file)
        return
    end if

    // Determine name from filename if not provided
    mut key_name = name
    if str.length(key_name) == 0
        key_name = extract_name(key_file)
    end if

    if str.length(key_name) == 0
        color.print_error("Could not determine key name. Please specify one.")
        return
    end if

    color.print_action("Importing key: " + key_name)

    let key_data = res.unwrap_or(file.readFile(key_file), "")
    let result = signing.import_key(key_data, key_name)

    if result.success
        color.print_success("Key imported successfully")
    else
        color.print_error(result.error)
    end if
end import_key

proc export_key(name: string)
    let keyring = signing.get_keyring_dir()
    let pub_path = keyring + "/" + name + ".pub"

    if not file.fileExists(pub_path)
        color.print_error("Key not found: " + name)
        return
    end if

    color.print_action("Public key for " + name + ":")
    println("")

    let key_data = res.unwrap_or(file.readFile(pub_path), "")
    println(key_data)
end export_key

proc delete_key(name: string)
    let keyring = signing.get_keyring_dir()

    // Check if key exists
    let pub_path = keyring + "/" + name + ".pub"
    let priv_path = keyring + "/" + name + ".key"

    if not file.fileExists(pub_path) and not file.fileExists(priv_path)
        color.print_error("Key not found: " + name)
        return
    end if

    // Ask for confirmation if private key exists
    if file.fileExists(priv_path)
        color.print_warning("This will delete the private key! Are you sure?")
        color.print_info("Use --force to confirm deletion")

        if not args.has_flag("force")
            return
        end if
    end if

    // Delete files
    if file.fileExists(pub_path)
        let cmd1 = "rm -f \"" + pub_path + "\""
        let pid1 = process.process_spawn_shell(cmd1)
        if pid1 > 0
            process.process_wait(pid1)
        end if
    end if

    if file.fileExists(priv_path)
        let cmd2 = "rm -f \"" + priv_path + "\""
        let pid2 = process.process_spawn_shell(cmd2)
        if pid2 > 0
            process.process_wait(pid2)
        end if
    end if

    color.print_success("Deleted key: " + name)
end delete_key

fn extract_name(path: string): string
    // Extract filename without extension
    let len = str.length(path)
    if len == 0
        return ""
    end if

    // Find last slash
    mut start = 0
    mut i = 0
    while i < len
        if path[i] == '/'
            start = i + 1
        end if
        i = i + 1
    end while

    // Find last dot
    mut end_pos = len
    i = len - 1
    while i >= start
        if path[i] == '.'
            end_pos = i
        end if
        i = i - 1
    end while

    if end_pos <= start
        return str.substring(path, start, len - start)
    end if

    return str.substring(path, start, end_pos - start)
end extract_name

// Initialize the keyring directory structure
proc init_keyring()
    color.print_action("Initializing keyring...")

    let keyring = signing.get_keyring_dir()
    let trusted_keys_dir = "/var/lib/coral/trusted-keys"

    // Create keyring directory
    if not dir.dir_exists(keyring)
        if not res.is_ok(dir.create_dir_all(keyring))
            color.print_error("Failed to create keyring directory: " + keyring)
            return
        end if
        color.print_info("Created: " + keyring)
    else
        color.print_info("Keyring already exists: " + keyring)
    end if

    // Create trusted-keys directory
    if not dir.dir_exists(trusted_keys_dir)
        if not res.is_ok(dir.create_dir_all(trusted_keys_dir))
            color.print_error("Failed to create trusted-keys directory")
            return
        end if
        color.print_info("Created: " + trusted_keys_dir)
    else
        color.print_info("Trusted keys directory already exists: " + trusted_keys_dir)
    end if

    // Set permissions (keyring should be root-only for private keys)
    let cmd = "chmod 700 \"" + keyring + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Keyring initialized")
    color.print_info("Generate keys with: coral key generate <name>")
end init_keyring

// Add a key to the trusted keys list
proc trust_key(name: string)
    let keyring = signing.get_keyring_dir()
    let trusted_dir = "/var/lib/coral/trusted-keys"
    let pub_path = keyring + "/" + name + ".pub"

    // Check if key exists
    if not file.fileExists(pub_path)
        color.print_error("Key not found: " + name)
        color.print_info("Import or generate the key first")
        return
    end if

    // Ensure trusted-keys directory exists
    if not dir.dir_exists(trusted_dir)
        if not res.is_ok(dir.create_dir_all(trusted_dir))
            color.print_error("Failed to create trusted-keys directory")
            return
        end if
    end if

    // Check if already trusted
    let trusted_path = trusted_dir + "/" + name + ".pub"
    if file.fileExists(trusted_path)
        color.print_warning("Key already trusted: " + name)
        return
    end if

    // Copy public key to trusted directory
    let cmd = "cp \"" + pub_path + "\" \"" + trusted_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to copy key")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Failed to trust key")
        return
    end if

    color.print_success("Trusted key: " + name)
    color.print_info("Packages signed with this key will now be accepted")
end trust_key

// Remove a key from the trusted keys list
proc revoke_key(name: string)
    let trusted_dir = "/var/lib/coral/trusted-keys"
    let trusted_path = trusted_dir + "/" + name + ".pub"

    // Check if key is trusted
    if not file.fileExists(trusted_path)
        color.print_error("Key is not in trusted list: " + name)
        return
    end if

    // Confirm revocation
    if not args.has_flag("force") and not args.has_flag("yes")
        color.print_warning("This will revoke trust for key: " + name)
        color.print_info("Use --force or -y to confirm")
        return
    end if

    // Remove from trusted keys
    let cmd = "rm -f \"" + trusted_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to revoke key")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Failed to remove key from trusted list")
        return
    end if

    color.print_success("Revoked trust for key: " + name)
    color.print_info("Packages signed with this key will no longer be accepted")
end revoke_key

// List trusted keys
proc list_trusted_keys()
    let trusted_dir = "/var/lib/coral/trusted-keys"

    if not dir.dir_exists(trusted_dir)
        color.print_info("No trusted keys (directory does not exist)")
        return
    end if

    let entries = res.unwrap_or(dir.list_dir(trusted_dir), new [string](0))
    let count = entries.length()

    if count == 0
        color.print_info("No trusted keys")
        return
    end if

    println("")
    color.print_action("Trusted keys:")
    mut i = 0
    while i < count
        let entry = entries[i]
        if str.ends_with(entry, ".pub")
            let name = str.substring(entry, 0, str.length(entry) - 4)
            println("  " + name)
        end if
        i = i + 1
    end while
end list_trusted_keys

proc print_usage()
    println("Usage: coral key <command> [options]")
    println("")
    println("Manage signing keys for package verification.")
    println("")
    println("Commands:")
    println("  list                List all keys in keyring")
    println("  generate <name>     Generate a new Ed25519 keypair")
    println("  import <file> [name] Import a public key")
    println("  export <name>       Export a public key")
    println("  delete <name>       Delete a key (use --force for private keys)")
    println("")
    println("Trust management:")
    println("  init                Initialize keyring directories")
    println("  trust <name>        Add key to trusted list")
    println("  revoke <name>       Remove key from trusted list")
    println("")
    println("Examples:")
    println("  coral key init")
    println("  coral key generate maintainer")
    println("  coral key import repo.pub community")
    println("  coral key trust community")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: list.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: List installed or available packages

******************************************************************************/

module commands.list

import sys.args
import core.str
import core.config
import core.database
import core.port
import core.portindex
import types
import util.color
import exitcodes as ec

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    // Check for --available flag
    if args.has_flag("available") or args.has_flag("a")
        list_available()
        return ec.EXIT_SUCCESS()
    end if

    // Default: list installed packages
    list_installed(root_path)
    return ec.EXIT_SUCCESS()
end execute

proc list_installed(root_path: string)
    mut packages: [string] = new [string](512)
    let pkg_count = list_installed_pkgs(packages, 512, root_path)

    if pkg_count == 0
        color.print_info("No packages installed")
        return
    end if

    color.print_action("Installed packages:")
    println("")

    mut i = 0
    while i < pkg_count
        let pkg_name = packages[i]
        let pkg = get_installed_pkg(pkg_name, root_path)

        // Format: name version
        print("  ")
        print(pkg.info.name)
        print(" ")
        print(pkg.info.version)
        print("-")
        println(int_to_str(pkg.info.release))

        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(pkg_count) + " packages")
end list_installed

// Helper functions for rooted operations
fn list_installed_pkgs(names: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.list_installed_rooted(names, max_count, root_path)
    end if
    return database.list_installed(names, max_count)
end list_installed_pkgs

fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_installed_pkg

proc list_available()
    color.print_action("Available ports:")
    println("")

    mut total = 0

    // Try ports index first (fast path)
    if portindex.port_index_exists()
        mut entries: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](4096)
        let entry_count = portindex.list_all_ports(entries, 4096)

        // Group by category for display
        mut current_cat = ""
        mut i = 0
        while i < entry_count
            let entry = entries[i]
            if not str.equals(entry.category, current_cat)
                if str.length(current_cat) > 0
                    println("")
                end if
                current_cat = entry.category
                color.print_info(current_cat + "/")
            end if

            print("  ")
            print(entry.name)
            print(" ")
            print(entry.version)
            print(" - ")
            println(entry.description)
            total = total + 1

            i = i + 1
        end while
    else
        // Fall back to filesystem scan
        mut cats: [string] = new [string](32)
        let cat_count = port.get_categories(cats, 32)

        mut i = 0
        while i < cat_count
            let category = cats[i]
            mut ports: [string] = new [string](256)
            let port_count = port.list_category(category, ports, 256)

            if port_count > 0
                color.print_info(category + "/")
                mut j = 0
                while j < port_count
                    let port_name = ports[j]
                    let result = port.find(port_name)
                    if result.success
                        let p = result.port
                        print("  ")
                        print(p.info.name)
                        print(" ")
                        print(p.info.version)
                        print(" - ")
                        println(p.info.description)
                    end if
                    j = j + 1
                    total = total + 1
                end while
                println("")
            end if

            i = i + 1
        end while
    end if

    println("")
    color.print_info("Total: " + int_to_str(total) + " ports")
end list_available

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: outdated.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Outdated command - show packages with available updates

******************************************************************************/

module commands.outdated

import sys.args
import core.str
import core.database
import core.port
import types
import util.color
import exitcodes as ec

export
    fn execute(): int
end export

fn execute(): int
    color.print_action("Checking for available updates...")
    println("")

    // Get list of installed packages
    mut installed: [string] = new [string](512)
    let installed_count = database.list_installed(installed, 512)

    if installed_count == 0
        color.print_info("No packages installed")
        return ec.EXIT_SUCCESS()
    end if

    // Check each package for updates
    mut outdated_count = 0
    mut i = 0
    while i < installed_count
        let pkg_name = installed[i]
        let installed_pkg = database.get_installed(pkg_name)

        // Find port
        let port_result = port.find(pkg_name)

        if port_result.success
            let p = port_result.port

            // Compare versions
            let cmp = compare_versions(installed_pkg.info.version, p.info.version)

            if cmp < 0
                // Outdated
                if outdated_count == 0
                    color.print_info("Outdated packages:")
                    println("")
                end if

                print("  ")
                print(pkg_name)
                print(" ")
                print(installed_pkg.info.version)
                print("-")
                print(int_to_str(installed_pkg.info.release))
                print(" -> ")
                print(p.info.version)
                print("-")
                println(int_to_str(p.info.release))

                outdated_count = outdated_count + 1
            end if
        end if

        i = i + 1
    end while

    if outdated_count == 0
        color.print_success("All packages are up to date")
        // Return special code for scripting - no updates available
        if args.has_flag("check")
            return ec.EXIT_NO_UPDATES()
        end if
        return ec.EXIT_SUCCESS()
    else
        println("")
        color.print_info(int_to_str(outdated_count) + " package(s) can be upgraded")
        println("")
        color.print_info("Run 'coral upgrade' to upgrade all packages")
        color.print_info("Run 'coral upgrade <package>' to upgrade specific packages")
        // Return special code for scripting - updates available
        if args.has_flag("check")
            return ec.EXIT_UPDATE_AVAILABLE()
        end if
        return ec.EXIT_SUCCESS()
    end if
end execute

// Compare two version strings
// Returns: -1 if v1 < v2, 0 if equal, 1 if v1 > v2
fn compare_versions(v1: string, v2: string): int
    // Split versions into parts
    mut parts1: [string] = new [string](10)
    mut parts2: [string] = new [string](10)

    let count1 = str.split(v1, '.', parts1, 10)
    let count2 = str.split(v2, '.', parts2, 10)

    // Compare each part
    mut i = 0
    let max_parts = max_int(count1, count2)

    while i < max_parts
        mut n1 = 0
        mut n2 = 0

        if i < count1
            n1 = parse_int(parts1[i])
        end if

        if i < count2
            n2 = parse_int(parts2[i])
        end if

        if n1 < n2
            return 0 - 1
        elif n1 > n2
            return 1
        end if

        i = i + 1
    end while

    return 0
end compare_versions

fn max_int(a: int, b: int): int
    if a > b
        return a
    end if
    return b
end max_int

// Parse integer from string
fn parse_int(s: string): int
    let len = str.length(s)
    if len == 0
        return 0
    end if

    mut result = 0
    mut i = 0

    while i < len
        let c = s[i]
        if c >= '0' and c <= '9'
            result = result * 10 + (c - '0')
        else
            // Stop at non-digit
            return result
        end if
        i = i + 1
    end while

    return result
end parse_int

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: owner.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Owner command - find which package owns a file

******************************************************************************/

module commands.owner

import sys.args
import core.str
import core.config
import core.database
import core.pkgdb
import types
import util.color
import exitcodes as ec

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // File path should be at cmd_index + 1
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    let file_path = args.get(opts.cmd_index + 1)

    // Find owner (use rooted version if root is set)
    let owner = find_owner(file_path, root_path)

    if str.length(owner) == 0
        color.print_error("No package owns: " + file_path)
        return ec.EXIT_PKG_NOT_FOUND()
    end if

    // Get package info (use rooted version if root is set)
    let pkg = get_installed_pkg(owner, root_path)

    color.print_action("File: " + file_path)
    println("")
    println("Owned by: " + owner + " " + pkg.info.version)
    return ec.EXIT_SUCCESS()
end execute

// Helper functions for rooted operations
// Uses pkgdb for fast indexed lookup with fallback to database scan
fn find_owner(file_path: string, root_path: string): string
    return pkgdb.find_file_owner_rooted(file_path, root_path)
end find_owner

fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_installed_pkg

proc print_usage()
    println("Usage: coral owner <file>")
    println("")
    println("Find which package owns a given file.")
    println("")
    println("Arguments:")
    println("  <file>    Path to the file to look up")
    println("")
    println("Examples:")
    println("  coral owner /usr/bin/vim")
    println("  coral owner /usr/bin/hello")
end print_usage

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: ports.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Ports command - port scaffolding and cache management

******************************************************************************/

module commands.ports

import sys.args
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.portindex
import types
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let subcommand = args.get(opts.cmd_index + 1)

    if subcommand == "new"
        return ports_new(opts)
    elif subcommand == "cache"
        return ports_cache(opts)
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

// ============================================================================
// coral ports new <category/name>
// ============================================================================

fn ports_new(opts: types.GlobalOptions): int
    let argc = args.count()

    if argc <= opts.cmd_index + 2
        color.print_error("Missing argument: category/name")
        println("Usage: coral ports new <category/name>")
        return ec.EXIT_USAGE()
    end if

    let arg = args.get(opts.cmd_index + 2)

    // Require slash format
    let slash_idx = str.index_of(arg, "/")
    if slash_idx <= 0
        color.print_error("Invalid format: '" + arg + "'")
        println("Use category/name format, e.g.: coral ports new hammerhead/my-port")
        return ec.EXIT_USAGE()
    end if

    let category = str.substring(arg, 0, slash_idx)
    let name = str.substring(arg, slash_idx + 1, str.length(arg) - slash_idx - 1)

    if str.length(name) == 0
        color.print_error("Port name cannot be empty")
        return ec.EXIT_USAGE()
    end if

    // Get ports directory
    let cfg = config.load()
    let ports_dir = config.get_ports_dir(cfg)

    // Create port directory
    let port_dir = path.join_path(ports_dir, path.join_path(category, name))

    if dir.dir_exists(port_dir)
        color.print_error("Port directory already exists: " + port_dir)
        return ec.EXIT_PKG_ALREADY_INSTALLED()
    end if

    if not res.is_ok(dir.create_dir_all(port_dir))
        color.print_error("Failed to create directory: " + port_dir)
        return ec.EXIT_PERMISSION_DENIED()
    end if

    // Generate package.toml
    let toml_path = path.join_path(port_dir, "package.toml")
    let toml_content = "[package]\nname = \"" + name + "\"\nversion = \"0.1.0\"\nrelease = 1\ndescription = \"\"\nurl = \"\"\nlicense = \"\"\nmaintainer = \"\"\narch = \"x86_64\"\n\n[dependencies]\nruntime = []\nbuild = []\n\n[[source]]\nfile = \"\"\nurls = []\nchecksum = \"SKIP\"\n\n[build]\nparallel = true\njobs = 0\n"

    if not res.is_ok(file.writeFile(toml_path, toml_content))
        color.print_error("Failed to write package.toml")
        return ec.EXIT_PERMISSION_DENIED()
    end if

    // Generate build.sh
    let build_path = path.join_path(port_dir, "build.sh")
    let dollar = "$"
    let build_content = "#!/bin/sh\n# Build script for " + name + "\nset -e\n\n# cd " + name + "-" + dollar + "{VERSION}\n\nMAKE=gmake\nif [ \"" + dollar + "(uname -s)\" != \"SunOS\" ]; then\n    MAKE=make\nfi\n\n# ./configure --prefix=/usr\n# " + dollar + "MAKE " + dollar + "{MAKEFLAGS}\n# " + dollar + "MAKE DESTDIR=\"" + dollar + "{DESTDIR}\" install\n"

    if not res.is_ok(file.writeFile(build_path, build_content))
        color.print_error("Failed to write build.sh")
        return ec.EXIT_PERMISSION_DENIED()
    end if

    color.print_success("Port created: " + category + "/" + name)
    println("")
    println("  Directory: " + port_dir)
    println("  package.toml: " + toml_path)
    println("  build.sh: " + build_path)
    println("")
    color.print_info("Next steps:")
    println("  1. Edit package.toml with package details")
    println("  2. Add source URLs and checksums")
    println("  3. Write the build.sh script")
    println("  4. Test with: coral build " + category + "/" + name)

    return ec.EXIT_SUCCESS()
end ports_new

// ============================================================================
// coral ports cache [status|rebuild]
// ============================================================================

fn ports_cache(opts: types.GlobalOptions): int
    let argc = args.count()

    if argc <= opts.cmd_index + 2
        // Default to status
        return cache_status()
    end if

    let subcmd = args.get(opts.cmd_index + 2)

    if subcmd == "status"
        return cache_status()
    elif subcmd == "rebuild"
        return cache_rebuild()
    else
        color.print_error("Unknown cache subcommand: " + subcmd)
        println("Usage: coral ports cache [status|rebuild]")
        return ec.EXIT_USAGE()
    end if
end ports_cache

fn cache_status(): int
    color.print_action("Ports index status:")
    println("")

    if portindex.port_index_exists()
        let count = portindex.get_port_count()
        println("  Status: built")
        println("  Ports indexed: " + int_to_str(count))
    else
        println("  Status: not built")
        color.print_info("Run 'coral ports cache rebuild' to build the index")
    end if

    return ec.EXIT_SUCCESS()
end cache_status

fn cache_rebuild(): int
    color.print_action("Rebuilding ports index...")
    println("")

    if portindex.rebuild_port_index()
        let count = portindex.get_port_count()
        color.print_success("Ports index rebuilt successfully")
        println("  Ports indexed: " + int_to_str(count))
        return ec.EXIT_SUCCESS()
    else
        color.print_error("Failed to rebuild ports index")
        return ec.EXIT_DB_ERROR()
    end if
end cache_rebuild

// ============================================================================
// Usage
// ============================================================================

proc print_usage()
    println("Usage: coral ports <command> [args]")
    println("")
    println("Port development and cache management.")
    println("")
    println("Commands:")
    println("  new <category/name>   Scaffold a new port")
    println("  cache [status]        Show ports index status")
    println("  cache rebuild         Rebuild ports index")
    println("")
    println("Examples:")
    println("  coral ports new hammerhead/my-port")
    println("  coral ports cache status")
    println("  coral ports cache rebuild")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: remove.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Remove command - uninstall packages

******************************************************************************/

module commands.remove

import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.pkgdb
import core.package
import core.port
import util.prompt
import util.mtree
import util.checksum
import types
import util.color
import fs.stat
import fs.ops
import util.priv
import exitcodes as ec
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Package arguments should be after the command
    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    // Collect packages to remove
    mut packages: [string] = new [string](256)
    mut pkg_count = 0

    mut i = opts.cmd_index + 1
    while i < argc and pkg_count < 256
        let pkg_name = args.get(i)

        // Skip flags and their values
        if pkg_name == "--root" or pkg_name == "--prefix"
            i = i + 2  // Skip flag and its value
            continue
        elif pkg_name == "--no-chroot-scripts"
            i = i + 1  // valueless flag: skip only itself
            continue
        end if
        if str.starts_with(pkg_name, "-")
            i = i + 1
            continue
        end if

        // Check if installed (use rooted version if root is set)
        let installed = check_installed(pkg_name, root_path)
        if installed
            packages[pkg_count] = pkg_name
            pkg_count = pkg_count + 1
        else
            color.print_warning(pkg_name + " is not installed")
        end if

        i = i + 1
    end while

    if pkg_count == 0
        color.print_info("No packages to remove")
        return ec.EXIT_SUCCESS()
    end if

    // Check for reverse dependencies (packages that depend on these)
    mut dependents: [string] = new [string](256)
    mut dependent_count = 0

    i = 0
    while i < pkg_count
        let pkg_name = packages[i]
        let count = get_reverse_dependencies(pkg_name, dependents, dependent_count, 256)
        dependent_count = count
        i = i + 1
    end while

    // Warn if there are dependents
    if dependent_count > 0
        color.print_warning("The following installed packages depend on packages being removed:")
        i = 0
        while i < dependent_count
            println("  - " + dependents[i])
            i = i + 1
        end while

        // Require --force to proceed
        if not opts.force
            color.print_error("Use --force to remove packages with dependents")
            return ec.EXIT_DEPS_CONFLICT()
        end if
        color.print_warning("Proceeding with removal (--force specified)")
    end if

    // Ask for confirmation (unless -y flag)
    if not prompt.confirm_remove(packages, pkg_count, dependents, dependent_count, opts)
        color.print_info("Removal cancelled")
        return ec.EXIT_CANCELLED()
    end if

    // Dry-run: show what would be done and exit
    if opts.dry_run
        color.print_info("Dry run — no changes made")
        return ec.EXIT_SUCCESS()
    end if

    // Remove packages
    mut all_success = true
    i = 0
    while i < pkg_count
        if not remove_package(packages[i], root_path, cfg)
            color.print_error("Failed to remove: " + packages[i])
            all_success = false
        end if
        i = i + 1
    end while

    if all_success
        return ec.EXIT_SUCCESS()
    else
        return ec.EXIT_REMOVE_FAILED()
    end if
end execute

// Check if package is installed, using rooted check if root is set
fn check_installed(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end check_installed

proc print_usage()
    println("Usage: coral remove <package...>")
    println("")
    println("Remove one or more installed packages.")
    println("")
    println("Arguments:")
    println("  <package>    Name of installed package to remove")
    println("")
    println("Options:")
    println("  -y, --yes    Don't ask for confirmation")
    println("  -f, --force  Remove even if other packages depend on it")
    println("")
    println("Examples:")
    println("  coral remove vim")
    println("  coral remove vim nano htop")
    println("  coral remove --force libfoo")
end print_usage

fn remove_package(pkg_name: string, root_path: string, cfg: config.Config): bool
    // Check if package is installed (use rooted version if root is set)
    if not check_installed(pkg_name, root_path)
        color.print_error(pkg_name + " is not installed")
        return false
    end if

    color.print_action("Removing " + pkg_name + "...")

    let install_root = get_actual_root(root_path)
    // Resolve script execution context; abort early if confinement is required but impossible.
    // Defense-in-depth: main.reef already bars non-root for all non-query commands, so this abort
    // is currently unreachable via the CLI. Kept so confinement fails safely if that global gate is
    // ever relaxed.
    if package.script_wants_chroot(install_root, config.get_chroot_scripts(cfg)) and not priv.is_root()
        color.print_error("--root " + install_root + " runs maintainer scripts confined to the target via chroot, which requires root privileges.")
        color.print_error("Re-run as root, or pass --no-chroot-scripts to run them on the host (unconfined).")
        return false
    end if
    let script_ctx = package.resolve_script_ctx(install_root, config.get_chroot_scripts(cfg), priv.is_root())

    // Get package info (use rooted version if root is set)
    let pkg = get_installed_pkg(pkg_name, root_path)
    color.print_info("Package: " + pkg.info.name + " " + pkg.info.version)

    // Get file list from database (use rooted version if root is set)
    mut files: [string] = new [string](4096)
    let file_count = get_files_list(pkg_name, files, 4096, root_path)

    if file_count == 0
        color.print_warning("No files recorded for package")
    else
        color.print_info("Removing " + int_to_str(file_count) + " files...")
    end if

    // Run pre-remove script if present (abort on failure)
    let scripts_dir = database.get_scripts_dir(pkg_name)
    if database.has_stored_scripts(pkg_name)
        color.print_info("Running pre-remove script...")
        if not package.run_stored_pre_remove(script_ctx, scripts_dir, pkg.info.version)
            color.print_error("Pre-remove script failed, aborting removal of " + pkg_name)
            return false
        end if
    end if

    // Load config file list and manifest checksums for config protection
    mut config_files: [string] = new [string](256)
    let config_count = database.get_config_files(pkg_name, config_files, 256)

    mut manifest_entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
    mut manifest_count = 0
    let manifest_path = database.get_manifest_path(pkg_name)
    if file.fileExists(manifest_path)
        let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
        if str.length(manifest_content) > 0
            manifest_count = mtree.parse_manifest(manifest_content, manifest_entries, 8192)
        end if
    end if

    // Remove files (with proper root path, respecting config protection)
    let actual_root = get_actual_root(root_path)
    if not remove_files(files, file_count, actual_root, config_files, config_count, manifest_entries, manifest_count)
        color.print_warning("Some files could not be removed")
        // Continue anyway - unregister from database
    end if

    // Run post-remove script if present (warn on failure, don't abort)
    if database.has_stored_scripts(pkg_name)
        color.print_info("Running post-remove script...")
        if not package.run_stored_post_remove(script_ctx, scripts_dir, pkg.info.version)
            color.print_warning("Post-remove script failed")
        end if
    end if

    // Unregister from database (use rooted version if root is set)
    color.print_info("Unregistering package...")
    if not unregister_pkg(pkg_name, root_path)
        color.print_error("Failed to unregister package from database")
        return false
    end if

    // Update package database indexes
    if not pkgdb.rebuild_indexes_rooted(root_path)
        color.print_warning("Failed to update package indexes")
    end if

    color.print_success("Removed " + pkg_name)
    return true
end remove_package

// Get installed package info, using rooted check if root is set
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_installed_pkg

// Get files list, using rooted check if root is set
fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.get_files_rooted(name, files, max_count, root_path)
    end if
    return database.get_files(name, files, max_count)
end get_files_list

// Unregister package, using rooted version if root is set
fn unregister_pkg(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.unregister_package_rooted(name, root_path)
    end if
    return database.unregister_package(name)
end unregister_pkg

// Get actual root path (returns "/" if empty)
fn get_actual_root(root_path: string): string
    if str.length(root_path) == 0
        return "/"
    end if
    return root_path
end get_actual_root

// Remove files from system, respecting config file protection
fn remove_files(files: [string], file_count: int, root_path: string, config_files: [string], config_count: int, manifest_entries: [mtree.ManifestEntry], manifest_count: int): bool
    mut all_success = true

    // Remove files in reverse order
    mut i = file_count - 1
    while i >= 0
        let rel_path = files[i]
        let full_path = path.join_path(root_path, rel_path)

        if stat.is_symlink(full_path) or stat.exists(full_path)
            // Check if this is a config file that the user has modified
            if config_count > 0 and package.is_config_file(rel_path, config_files, config_count)
                // Look up the package's sha256 from the manifest
                let pkg_sha = find_manifest_sha256(rel_path, manifest_entries, manifest_count)
                if str.length(pkg_sha) > 0
                    let installed_sha = checksum.sha256_file(full_path)
                    if not str.equals(installed_sha, pkg_sha)
                        // User has modified this config — preserve it
                        color.print_info("Preserving modified config: " + rel_path)
                        i = i - 1
                        continue
                    end if
                end if
            end if

            if not res.is_ok(ops.remove_file(full_path))
                color.print_warning("Failed to remove: " + full_path)
                all_success = false
            end if
        end if

        i = i - 1
    end while

    // Try to remove empty parent directories
    i = file_count - 1
    while i >= 0
        let rel_path = files[i]
        let full_path = path.join_path(root_path, rel_path)
        let parent = path.dirname(full_path)

        if str.length(parent) > str.length(root_path) and dir.dir_exists(parent)
            dir.remove_dir(parent)
        end if

        i = i - 1
    end while

    return all_success
end remove_files

// Look up the sha256 for a given relative path in the manifest entries
fn find_manifest_sha256(rel_path: string, entries: [mtree.ManifestEntry], count: int): string
    mut i = 0
    while i < count
        let epath = mtree.entry_path(entries[i])
        // Compare with and without ./ prefix
        mut entry_rel = epath
        if str.starts_with(epath, "./")
            entry_rel = str.substring(epath, 2, str.length(epath) - 2)
        end if
        if str.equals(entry_rel, rel_path)
            return mtree.entry_sha256(entries[i])
        end if
        i = i + 1
    end while
    return ""
end find_manifest_sha256

// Get packages that depend on the given package
// Returns new total count (existing + new dependents)
fn get_reverse_dependencies(pkg_name: string, dependents: [string], current_count: int, max_count: int): int
    mut count = current_count

    // List all installed packages
    mut installed: [string] = new [string](512)
    let installed_count = database.list_installed(installed, 512)

    mut i = 0
    while i < installed_count and count < max_count
        let other_pkg = installed[i]

        // Skip the package being removed and already listed dependents
        if str.equals(other_pkg, pkg_name)
            i = i + 1
            continue
        end if

        // Check if already in dependents list
        if array_contains(dependents, count, other_pkg)
            i = i + 1
            continue
        end if

        // Try to find this package's port to get its dependencies
        let port_result = port.find(other_pkg)
        if port_result.success
            let p = port_result.port

            // Check runtime dependencies
            if depends_on(p.deps.runtime, p.deps.runtime_count, pkg_name)
                dependents[count] = other_pkg
                count = count + 1
            end if
        end if

        i = i + 1
    end while

    return count
end get_reverse_dependencies

// Check if a dependency list contains the given package
fn depends_on(deps: [string], dep_count: int, pkg_name: string): bool
    mut i = 0
    while i < dep_count
        let dep = deps[i]

        // Handle alternative dependencies (format: base:opt1,opt2)
        let colon_pos = str.index_of_char(dep, ':')
        mut base_dep = dep
        if colon_pos > 0
            base_dep = str.substring(dep, 0, colon_pos)
        end if

        if str.equals(base_dep, pkg_name)
            return true
        end if

        i = i + 1
    end while

    return false
end depends_on

// Helper to check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
    mut i = 0
    while i < count
        if str.equals(arr[i], s)
            return true
        end if
        i = i + 1
    end while
    return false
end array_contains

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: repo.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Repo command - manage package repositories

******************************************************************************/

module commands.repo

import sys.args
import sys.process
import io.file
import io.dir
import core.str
import core.repository
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let subcommand = args.get(2)

    if subcommand == "list"
        list_repos()
        return ec.EXIT_SUCCESS()
    elif subcommand == "add"
        if argc < 4
            color.print_error("Missing repository URL")
            println("Usage: coral repo add <url> [name]")
            return ec.EXIT_USAGE()
        end if
        let url = args.get(3)
        mut name = ""
        if argc >= 5
            name = args.get(4)
        end if
        add_repo(url, name)
        return ec.EXIT_SUCCESS()
    elif subcommand == "remove"
        if argc < 4
            color.print_error("Missing repository name")
            println("Usage: coral repo remove <name>")
            return ec.EXIT_USAGE()
        end if
        remove_repo(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "enable"
        if argc < 4
            color.print_error("Missing repository name")
            return ec.EXIT_USAGE()
        end if
        enable_repo(args.get(3), true)
        return ec.EXIT_SUCCESS()
    elif subcommand == "disable"
        if argc < 4
            color.print_error("Missing repository name")
            return ec.EXIT_USAGE()
        end if
        enable_repo(args.get(3), false)
        return ec.EXIT_SUCCESS()
    elif subcommand == "init"
        if argc < 4
            color.print_error("Missing repository path")
            println("Usage: coral repo init <path>")
            return ec.EXIT_USAGE()
        end if
        init_repo(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "rebuild"
        if argc < 4
            color.print_error("Missing repository path")
            println("Usage: coral repo rebuild <path>")
            return ec.EXIT_USAGE()
        end if
        rebuild_repo(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "sign"
        if argc < 4
            color.print_error("Missing repository path")
            println("Usage: coral repo sign <path> [keyname]")
            return ec.EXIT_USAGE()
        end if
        let repo_path = args.get(3)
        mut key_name = "default"
        if argc >= 5
            key_name = args.get(4)
        end if
        sign_repo(repo_path, key_name)
        return ec.EXIT_SUCCESS()
    elif subcommand == "verify"
        if argc < 4
            color.print_error("Missing repository path")
            println("Usage: coral repo verify <path>")
            return ec.EXIT_USAGE()
        end if
        verify_repo(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "mirror"
        if argc < 5
            color.print_error("Missing source or destination")
            println("Usage: coral repo mirror <source> <dest>")
            return ec.EXIT_USAGE()
        end if
        mirror_repo(args.get(3), args.get(4))
        return ec.EXIT_SUCCESS()
    elif subcommand == "export"
        if argc < 5
            color.print_error("Missing repository path or output")
            println("Usage: coral repo export <path> <output>")
            return ec.EXIT_USAGE()
        end if
        export_repo(args.get(3), args.get(4))
        return ec.EXIT_SUCCESS()
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

proc list_repos()
    color.print_action("Configured repositories:")
    println("")

    mut repos: [repository.Repository] = new [repository.Repository](32)
    let count = repository.list_repos(repos, 32)

    if count == 0
        color.print_info("No repositories configured")
        println("")
        color.print_info("Add a repository with: coral repo add <url>")
        return
    end if

    mut i = 0
    while i < count
        let repo = repos[i]
        print("  ")
        print(repo.name)
        print(" - ")
        print(repo.url)
        if not repo.enabled
            print(" [disabled]")
        end if
        if repo.is_signed
            print(" [signed]")
        end if
        println("")
        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(count) + " repository(ies)")
end list_repos

proc add_repo(url: string, name: string)
    color.print_action("Adding repository...")

    // Generate name from URL if not provided
    mut repo_name = name
    if str.length(repo_name) == 0
        repo_name = extract_repo_name(url)
    end if

    if str.length(repo_name) == 0
        color.print_error("Could not determine repository name. Please specify one.")
        return
    end if

    // Create repo file
    let repos_dir = "/etc/coral/repos.d"
    let repo_path = repos_dir + "/" + repo_name + ".repo"

    // Check if it exists
    if file.fileExists(repo_path)
        color.print_error("Repository already exists: " + repo_name)
        return
    end if

    // Ensure directory exists
    if not dir.dir_exists(repos_dir)
        if not res.is_ok(dir.create_dir_all(repos_dir))
            color.print_error("Failed to create repos directory")
            return
        end if
    end if

    // Create repo file content
    mut content = "[repository]\n"
    content = content + "name = \"" + repo_name + "\"\n"
    content = content + "url = \"" + url + "\"\n"
    content = content + "priority = 100\n"
    content = content + "enabled = true\n"
    content = content + "signed = false\n"

    if not res.is_ok(file.writeFile(repo_path, content))
        color.print_error("Failed to write repository file")
        return
    end if

    color.print_success("Added repository: " + repo_name)
end add_repo

proc remove_repo(name: string)
    let repos_dir = "/etc/coral/repos.d"
    let repo_path = repos_dir + "/" + name + ".repo"

    if not file.fileExists(repo_path)
        color.print_error("Repository not found: " + name)
        return
    end if

    // Remove the file
    let cmd = "rm -f \"" + repo_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Removed repository: " + name)
end remove_repo

proc enable_repo(name: string, enable: bool)
    let repos_dir = "/etc/coral/repos.d"
    let repo_path = repos_dir + "/" + name + ".repo"

    if not file.fileExists(repo_path)
        color.print_error("Repository not found: " + name)
        return
    end if

    // Read current content
    let content = res.unwrap_or(file.readFile(repo_path), "")

    // Replace enabled line
    mut new_content = ""
    if enable
        new_content = str.replace(content, "enabled = false", "enabled = true")
    else
        new_content = str.replace(content, "enabled = true", "enabled = false")
    end if

    if not res.is_ok(file.writeFile(repo_path, new_content))
        color.print_error("Failed to update repository file")
        return
    end if

    if enable
        color.print_success("Enabled repository: " + name)
    else
        color.print_success("Disabled repository: " + name)
    end if
end enable_repo

fn extract_repo_name(url: string): string
    // Extract name from URL (e.g., https://repo.example.com/zygaena -> zygaena)
    let len = str.length(url)
    if len == 0
        return ""
    end if

    // Find last slash
    mut last_slash = 0 - 1
    mut i = 0
    while i < len
        if url[i] == '/'
            last_slash = i
        end if
        i = i + 1
    end while

    if last_slash < 0 or last_slash >= len - 1
        return "repo"
    end if

    return str.substring(url, last_slash + 1, len - last_slash - 1)
end extract_repo_name

// Initialize a new repository at the given path
proc init_repo(repo_path: string)
    color.print_action("Initializing repository at " + repo_path)

    // Create the repository directory
    if not dir.dir_exists(repo_path)
        if not res.is_ok(dir.create_dir_all(repo_path))
            color.print_error("Failed to create repository directory")
            return
        end if
    end if

    // Create packages subdirectory
    let packages_dir = repo_path + "/packages"
    if not dir.dir_exists(packages_dir)
        if not res.is_ok(dir.create_dir_all(packages_dir))
            color.print_error("Failed to create packages directory")
            return
        end if
    end if

    // Create repo.toml manifest
    let manifest_path = repo_path + "/repo.toml"
    if file.fileExists(manifest_path)
        color.print_warning("repo.toml already exists, skipping")
    else
        mut content = "# Coral Repository Manifest\n"
        content = content + "# Generated by coral repo init\n\n"
        content = content + "[repository]\n"
        content = content + "name = \"unnamed\"\n"
        content = content + "description = \"A Coral package repository\"\n"
        content = content + "url = \"\"\n"
        content = content + "arch = \"x86_64\"\n"
        content = content + "created = \"2025-01-24\"\n"
        content = content + "signed = false\n\n"
        content = content + "# Packages will be listed below by coral repo rebuild\n"
        content = content + "[packages]\n"

        if not res.is_ok(file.writeFile(manifest_path, content))
            color.print_error("Failed to write repo.toml")
            return
        end if
    end if

    color.print_success("Repository initialized at " + repo_path)
    color.print_info("Place packages in: " + packages_dir)
    color.print_info("Run 'coral repo rebuild " + repo_path + "' to update manifest")
end init_repo

// Rebuild repository manifest by scanning packages
proc rebuild_repo(repo_path: string)
    color.print_action("Rebuilding repository manifest...")

    let packages_dir = repo_path + "/packages"
    if not dir.dir_exists(packages_dir)
        color.print_error("Packages directory not found: " + packages_dir)
        return
    end if

    // Scan for package files
    let entries = res.unwrap_or(dir.list_dir(packages_dir), new [string](0))
    let entry_count = entries.length()

    mut pkg_count = 0
    mut packages_content = ""

    mut i = 0
    while i < entry_count
        let entry = entries[i]
        // Look for .pkg.tar.xz files
        if str.ends_with(entry, ".pkg.tar.xz")
            // Parse package name and version from filename
            // Format: name-version-release.arch.pkg.tar.xz
            let info = parse_package_filename(entry)
            if str.length(info) > 0
                packages_content = packages_content + info + "\n"
                pkg_count = pkg_count + 1
            end if
        end if
        i = i + 1
    end while

    // Generate new repo.toml
    let manifest_path = repo_path + "/repo.toml"
    mut content = "# Coral Repository Manifest\n"
    content = content + "# Rebuilt by coral repo rebuild\n\n"
    content = content + "[repository]\n"
    content = content + "name = \"unnamed\"\n"
    content = content + "description = \"A Coral package repository\"\n"
    content = content + "url = \"\"\n"
    content = content + "arch = \"x86_64\"\n"
    content = content + "created = \"2025-01-24\"\n"
    content = content + "signed = false\n\n"
    content = content + "[packages]\n"
    content = content + packages_content

    if not res.is_ok(file.writeFile(manifest_path, content))
        color.print_error("Failed to write repo.toml")
        return
    end if

    color.print_success("Repository rebuilt: " + int_to_str(pkg_count) + " package(s) found")
end rebuild_repo

// Parse package filename into TOML entry
fn parse_package_filename(filename: string): string
    // Extract name-version-release from filename
    // Example: vim-9.0-1.x86_64.pkg.tar.xz -> vim = { version = "9.0", release = 1 }

    // Remove .pkg.tar.xz suffix
    let base = str.substring(filename, 0, str.length(filename) - 11)

    // Find arch (e.g., .x86_64)
    let arch_pos = str.last_index_of_char(base, '.')
    if arch_pos < 0
        return ""
    end if

    let name_ver_rel = str.substring(base, 0, arch_pos)

    // Find release number (last hyphen)
    let rel_pos = str.last_index_of_char(name_ver_rel, '-')
    if rel_pos < 0
        return ""
    end if
    let release = str.substring(name_ver_rel, rel_pos + 1, str.length(name_ver_rel) - rel_pos - 1)

    // Find version (second to last hyphen)
    let name_ver = str.substring(name_ver_rel, 0, rel_pos)
    let ver_pos = str.last_index_of_char(name_ver, '-')
    if ver_pos < 0
        return ""
    end if

    let name = str.substring(name_ver, 0, ver_pos)
    let version = str.substring(name_ver, ver_pos + 1, str.length(name_ver) - ver_pos - 1)

    return name + " = { version = \"" + version + "\", release = " + release + ", file = \"" + filename + "\" }"
end parse_package_filename

// Sign the repository manifest
proc sign_repo(repo_path: string, key_name: string)
    color.print_action("Signing repository manifest...")

    let manifest_path = repo_path + "/repo.toml"
    if not file.fileExists(manifest_path)
        color.print_error("repo.toml not found in: " + repo_path)
        return
    end if

    // Find the key
    let keyring = "/etc/coral/keys"
    let key_path = keyring + "/" + key_name + ".key"

    if not file.fileExists(key_path)
        color.print_error("Key not found: " + key_name)
        color.print_info("Generate a key with: coral key generate " + key_name)
        return
    end if

    // Sign the manifest using openssl
    let sig_path = repo_path + "/repo.toml.sig"
    let cmd = "openssl pkeyutl -sign -inkey \"" + key_path + "\" -in \"" + manifest_path + "\" -out \"" + sig_path + "\""

    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to start signing process")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Signing failed")
        return
    end if

    // Update repo.toml to indicate it's signed
    let content = res.unwrap_or(file.readFile(manifest_path), "")
    let new_content = str.replace(content, "signed = false", "signed = true")
    file.writeFile(manifest_path, new_content)

    color.print_success("Repository signed with key: " + key_name)
    color.print_info("Signature: " + sig_path)
end sign_repo

// Verify repository signature
proc verify_repo(repo_path: string)
    color.print_action("Verifying repository signature...")

    let manifest_path = repo_path + "/repo.toml"
    let sig_path = repo_path + "/repo.toml.sig"

    if not file.fileExists(manifest_path)
        color.print_error("repo.toml not found")
        return
    end if

    if not file.fileExists(sig_path)
        color.print_error("No signature found (repo.toml.sig)")
        return
    end if

    // Try to find a matching public key
    let keyring = "/etc/coral/keys"
    if not dir.dir_exists(keyring)
        color.print_error("No keys in keyring")
        return
    end if

    // List all public keys and try each
    let entries = res.unwrap_or(dir.list_dir(keyring), new [string](0))
    let count = entries.length()

    mut i = 0
    mut verified = false
    while i < count and not verified
        let entry = entries[i]
        if str.ends_with(entry, ".pub")
            let key_path = keyring + "/" + entry
            let cmd = "openssl pkeyutl -verify -pubin -inkey \"" + key_path + "\" -in \"" + manifest_path + "\" -sigfile \"" + sig_path + "\" 2>/dev/null"

            let pid = process.process_spawn_shell(cmd)
            if pid > 0
                let exit_code = process.process_wait(pid)
                if exit_code == 0
                    let key_name = str.substring(entry, 0, str.length(entry) - 4)
                    color.print_success("Signature verified with key: " + key_name)
                    verified = true
                end if
            end if
        end if
        i = i + 1
    end while

    if not verified
        color.print_error("Signature verification failed - no matching key found")
    end if
end verify_repo

// Mirror repository to remote destination
proc mirror_repo(source: string, dest: string)
    color.print_action("Mirroring repository...")
    color.print_info("Source: " + source)
    color.print_info("Destination: " + dest)

    // Use rsync for mirroring
    let cmd = "rsync -av --delete \"" + source + "/\" \"" + dest + "/\""

    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to start rsync")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Mirror sync failed")
        return
    end if

    color.print_success("Repository mirrored to: " + dest)
end mirror_repo

// Export repository for offline distribution (ISO/USB)
proc export_repo(repo_path: string, output_path: string)
    color.print_action("Exporting repository for offline distribution...")

    if not dir.dir_exists(repo_path)
        color.print_error("Repository not found: " + repo_path)
        return
    end if

    // Determine output format based on extension
    if str.ends_with(output_path, ".tar.xz")
        // Create compressed tarball
        let cmd = "gtar -C \"" + repo_path + "\" -cJf \"" + output_path + "\" ."
        let pid = process.process_spawn_shell(cmd)
        if pid < 0
            color.print_error("Failed to create archive")
            return
        end if
        let exit_code = process.process_wait(pid)
        if exit_code != 0
            color.print_error("Archive creation failed")
            return
        end if
    elif str.ends_with(output_path, ".tar.gz")
        let cmd = "gtar -C \"" + repo_path + "\" -czf \"" + output_path + "\" ."
        let pid = process.process_spawn_shell(cmd)
        if pid < 0
            color.print_error("Failed to create archive")
            return
        end if
        let exit_code = process.process_wait(pid)
        if exit_code != 0
            color.print_error("Archive creation failed")
            return
        end if
    else
        // Copy directory
        let cmd = "cp -r \"" + repo_path + "\" \"" + output_path + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid < 0
            color.print_error("Failed to copy repository")
            return
        end if
        let exit_code = process.process_wait(pid)
        if exit_code != 0
            color.print_error("Copy failed")
            return
        end if
    end if

    color.print_success("Repository exported to: " + output_path)
end export_repo

proc print_usage()
    println("Usage: coral repo <command> [options]")
    println("")
    println("Manage package repositories.")
    println("")
    println("Commands:")
    println("  list              List configured repositories")
    println("  add <url> [name]  Add a new repository")
    println("  remove <name>     Remove a repository")
    println("  enable <name>     Enable a repository")
    println("  disable <name>    Disable a repository")
    println("")
    println("Repository maintenance:")
    println("  init <path>       Create a new repository structure")
    println("  rebuild <path>    Scan packages and rebuild manifest")
    println("  sign <path> [key] Sign repository with Ed25519 key")
    println("  verify <path>     Verify repository signature")
    println("  mirror <src> <dst> Sync repository to mirror (rsync)")
    println("  export <path> <out> Export for offline distribution")
    println("")
    println("Examples:")
    println("  coral repo list")
    println("  coral repo add https://repo.zygaena.org/packages")
    println("  coral repo init /var/www/repo/myrepo")
    println("  coral repo rebuild /var/www/repo/myrepo")
    println("  coral repo sign /var/www/repo/myrepo maintainer")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: search.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Search command - search for packages by name or description

******************************************************************************/

module commands.search

import sys.args
import core.str
import core.port
import core.portindex
import core.database
import types
import util.color
import exitcodes as ec

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let search_term = args.get(2)

    color.print_action("Searching for: " + search_term)
    println("")

    mut total = 0

    // Try ports index first (fast path)
    if portindex.port_index_exists()
        mut results: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](512)
        let result_count = portindex.search_ports(search_term, results, 512)

        mut i = 0
        while i < result_count
            let entry = results[i]
            print_index_match(entry)
            total = total + 1
            i = i + 1
        end while
    else
        // Fall back to filesystem scan
        mut cats: [string] = new [string](32)
        let cat_count = port.get_categories(cats, 32)

        mut i = 0
        while i < cat_count
            let category = cats[i]
            mut ports: [string] = new [string](256)
            let port_count = port.list_category(category, ports, 256)

            mut j = 0
            while j < port_count
                let port_name = ports[j]
                let result = port.find(port_name)
                if result.success
                    let p = result.port

                    // Check if search term matches name or description
                    if matches_search(p, search_term)
                        print_match(p, category)
                        total = total + 1
                    end if
                end if
                j = j + 1
            end while

            i = i + 1
        end while
    end if

    if total == 0
        color.print_info("No packages found matching: " + search_term)
    else
        println("")
        color.print_info("Found " + int_to_str(total) + " package(s)")
    end if
    return ec.EXIT_SUCCESS()
end execute

fn matches_search(p: types.Port, term: string): bool
    let lower_term = str.to_lower(term)
    let lower_name = str.to_lower(p.info.name)
    let lower_desc = str.to_lower(p.info.description)

    // Check name
    if str.contains(lower_name, lower_term)
        return true
    end if

    // Check description
    if str.contains(lower_desc, lower_term)
        return true
    end if

    return false
end matches_search

proc print_index_match(entry: portindex.PortIndexEntry)
    let is_installed = database.is_installed(entry.name)

    print(entry.category)
    print("/")
    print(entry.name)
    print(" ")
    print(entry.version)
    if is_installed
        print(" [installed]")
    end if
    println("")
    print("    ")
    println(entry.description)
end print_index_match

proc print_match(p: types.Port, category: string)
    // Check if installed
    let is_installed = database.is_installed(p.info.name)

    print(category)
    print("/")
    print(p.info.name)
    print(" ")
    print(p.info.version)
    if is_installed
        print(" [installed]")
    end if
    println("")
    print("    ")
    println(p.info.description)
end print_match

proc print_usage()
    println("Usage: coral search <term>")
    println("")
    println("Search for packages by name or description.")
    println("")
    println("Arguments:")
    println("  <term>    Search term to look for")
    println("")
    println("Examples:")
    println("  coral search vim")
    println("  coral search editor")
    println("  coral search hello")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: sync.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Sync command - update ports collection from repository

******************************************************************************/

module commands.sync

import sys.args
import sys.process
import io.dir
import io.path
import io.file
import core.str
import core.config
import core.port
import core.portindex
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(): int
end export

fn execute(): int
    // Load configuration
    let cfg = config.load()
    let ports_dir = config.get_ports_dir(cfg)

    color.print_action("Syncing ports collection...")
    println("")

    // Check if ports directory exists
    if not dir.dir_exists(ports_dir)
        color.print_error("Ports directory does not exist: " + ports_dir)
        color.print_info("You may need to clone the ports repository first:")
        println("  git clone <ports-repo-url> " + ports_dir)
        return ec.EXIT_CONFIG_ERROR()
    end if

    // Check if it's a git repository
    let git_dir = path.join_path(ports_dir, ".git")
    if not dir.dir_exists(git_dir)
        color.print_warning("Ports directory is not a git repository")
        color.print_info("Cannot sync - no version control detected")
        return ec.EXIT_CONFIG_ERROR()
    end if

    // Run git pull
    color.print_info("Updating from remote repository...")

    let cmd = "cd \"" + ports_dir + "\" && git pull"
    let pid = process.process_spawn_shell(cmd)

    if pid < 0
        color.print_error("Failed to start git pull")
        return ec.EXIT_REPO_UNREACHABLE()
    end if

    let exit_code = process.process_wait(pid)

    if exit_code == 0
        color.print_success("Ports collection updated successfully")

        // Rebuild ports index after successful sync
        portindex.rebuild_port_index()

        // Show summary of changes
        show_update_summary(ports_dir)
        return ec.EXIT_SUCCESS()
    else
        color.print_error("Git pull failed with exit code " + int_to_str(exit_code))
        color.print_info("Check your network connection and repository access")
        return ec.EXIT_REPO_UNREACHABLE()
    end if
end execute

proc show_update_summary(ports_dir: string)
    // Count ports in each category (dynamically discovered)
    mut cats: [string] = new [string](32)
    let cat_count = port.get_categories(cats, 32)

    mut total = 0
    mut i = 0
    while i < cat_count
        let cat = cats[i]
        let cat_path = path.join_path(ports_dir, cat)

        if dir.dir_exists(cat_path)
            let entries = res.unwrap_or(dir.list_dir(cat_path), new [string](0))
            let count = entries.length()

            // Count valid ports (directories with package.toml)
            mut port_count = 0
            mut j = 0
            while j < count
                let entry = entries[j]
                if str.length(entry) > 0 and entry[0] != '.'
                    let toml_path = path.join_path(path.join_path(cat_path, entry), "package.toml")
                    if file.fileExists(toml_path)
                        port_count = port_count + 1
                    end if
                end if
                j = j + 1
            end while

            if port_count > 0
                println("  " + cat + ": " + int_to_str(port_count) + " ports")
                total = total + port_count
            end if
        end if

        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(total) + " ports available")
end show_update_summary

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: upgrade.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Upgrade command - upgrade installed packages

******************************************************************************/

module commands.upgrade

import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.port
import core.portindex
import core.package
import types
import util.color
import util.version as ver
import exitcodes as ec
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    // Auto-refresh port index if configured
    if config.get_auto_refresh(cfg)
        portindex.rebuild_port_index()
    end if

    // Show root if set (verbose mode)
    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    // Count non-flag arguments (package names)
    // Skip flag values (--root, --prefix take a value)
    mut pkg_count = 0
    mut i = opts.cmd_index + 1
    while i < argc
        let arg = args.get(i)
        if arg == "--root" or arg == "--prefix"
            i = i + 2  // Skip flag and its value
            continue
        elif arg == "--no-chroot-scripts"
            i = i + 1  // valueless flag: skip only itself
            continue
        end if
        if not str.starts_with(arg, "-")
            pkg_count = pkg_count + 1
        end if
        i = i + 1
    end while

    if pkg_count == 0
        // No packages specified - upgrade all
        return upgrade_all(cfg)
    else
        // Upgrade specified packages
        mut all_success = true
        i = opts.cmd_index + 1
        while i < argc
            let pkg_name = args.get(i)

            // Skip flags and their values
            if pkg_name == "--root" or pkg_name == "--prefix"
                i = i + 2  // Skip flag and its value
                continue
            elif pkg_name == "--no-chroot-scripts"
                i = i + 1  // valueless flag: skip only itself
                continue
            end if
            if str.starts_with(pkg_name, "-")
                i = i + 1
                continue
            end if

            // Upgrade this package
            if not upgrade_package(pkg_name, cfg)
                color.print_error("Failed to upgrade: " + pkg_name)
                all_success = false
            end if

            i = i + 1
        end while

        if all_success
            return ec.EXIT_SUCCESS()
        else
            return ec.EXIT_UPGRADE_FAILED()
        end if
    end if
end execute

fn upgrade_all(cfg: config.Config): int
    color.print_action("Checking for upgrades...")

    // Get root path for rooted operations
    let root_path = config.get_root(cfg)

    // List all installed packages (use rooted version if root is set)
    mut installed: [string] = new [string](512)
    let installed_count = list_installed_pkgs(installed, 512, root_path)

    if installed_count == 0
        color.print_info("No packages installed")
        return ec.EXIT_SUCCESS()
    end if

    // Check each package for updates
    mut upgradable: [string] = new [string](512)
    mut upgradable_count = 0

    mut i = 0
    while i < installed_count
        let pkg_name = installed[i]

        if has_upgrade(pkg_name, root_path)
            upgradable[upgradable_count] = pkg_name
            upgradable_count = upgradable_count + 1
        end if

        i = i + 1
    end while

    if upgradable_count == 0
        color.print_success("All packages are up to date")
        return ec.EXIT_SUCCESS()
    end if

    color.print_info("Packages to upgrade: " + int_to_str(upgradable_count))

    // List packages to upgrade
    i = 0
    while i < upgradable_count
        let pkg_name = upgradable[i]
        let installed_pkg = get_installed_pkg(pkg_name, root_path)
        let port_result = port.find(pkg_name)

        if port_result.success
            let p = port_result.port
            println("  " + pkg_name + " " + installed_pkg.info.version + " -> " + p.info.version)
        end if

        i = i + 1
    end while

    // Ask for confirmation unless -y flag
    if not args.has_flag("y") and not args.has_flag("yes")
        color.print_info("Use -y flag to skip confirmation and proceed with upgrade")
        return ec.EXIT_CANCELLED()
    end if

    // Dry-run: show what would be done and exit
    if args.has_flag("n") or args.has_flag("dry-run")
        color.print_info("Dry run — no changes made")
        return ec.EXIT_SUCCESS()
    end if

    // Perform upgrades
    mut all_success = true
    i = 0
    while i < upgradable_count
        if not upgrade_package(upgradable[i], cfg)
            color.print_error("Failed to upgrade: " + upgradable[i])
            all_success = false
        end if
        i = i + 1
    end while

    if all_success
        return ec.EXIT_SUCCESS()
    else
        return ec.EXIT_UPGRADE_FAILED()
    end if
end upgrade_all

fn has_upgrade(pkg_name: string, root_path: string): bool
    // Get installed version (use rooted version if root is set)
    let installed_pkg = get_installed_pkg(pkg_name, root_path)
    if str.length(installed_pkg.info.name) == 0
        return false
    end if

    // Find port
    let port_result = port.find(pkg_name)
    if not port_result.success
        return false
    end if

    let p = port_result.port

    // Compare versions using semantic versioning
    return ver.compare_versions(installed_pkg.info.version, p.info.version) < 0
end has_upgrade

// Helper functions for rooted operations
fn list_installed_pkgs(names: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.list_installed_rooted(names, max_count, root_path)
    end if
    return database.list_installed(names, max_count)
end list_installed_pkgs

fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
    if str.length(root_path) > 0
        return database.get_installed_rooted(name, root_path)
    end if
    return database.get_installed(name)
end get_installed_pkg

fn is_installed_pkg(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end is_installed_pkg

fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
    if str.length(root_path) > 0
        return database.get_files_rooted(name, files, max_count, root_path)
    end if
    return database.get_files(name, files, max_count)
end get_files_list

fn unregister_pkg(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.unregister_package_rooted(name, root_path)
    end if
    return database.unregister_package(name)
end unregister_pkg

fn register_pkg(pkg: types.InstalledPackage, root_path: string): bool
    if str.length(root_path) > 0
        return database.register_from_extract_dir_rooted(pkg, "", root_path)
    end if
    return database.register_package(pkg)
end register_pkg

fn get_actual_root(root_path: string): string
    if str.length(root_path) == 0
        return "/"
    end if
    return root_path
end get_actual_root

fn upgrade_package(pkg_name: string, cfg: config.Config): bool
    // Get root path for rooted operations
    let root_path = config.get_root(cfg)

    // Check if installed (use rooted version if root is set)
    if not is_installed_pkg(pkg_name, root_path)
        color.print_error(pkg_name + " is not installed")
        return false
    end if

    // Get installed info (use rooted version if root is set)
    let installed_pkg = get_installed_pkg(pkg_name, root_path)

    // Find port
    let port_result = port.find(pkg_name)
    if not port_result.success
        color.print_error("Port not found: " + pkg_name)
        return false
    end if

    let p = port_result.port

    // Check if upgrade is available using semantic versioning
    let cmp = ver.compare_versions(installed_pkg.info.version, p.info.version)
    if cmp >= 0
        color.print_info(pkg_name + " is already at version " + installed_pkg.info.version)
        return true
    end if

    color.print_action("Upgrading " + pkg_name + " from " + installed_pkg.info.version + " to " + p.info.version + "...")

    // Look for pre-built package
    let pkg_path = find_package(pkg_name, p.info.version, p.info.release, cfg)

    if str.length(pkg_path) == 0
        color.print_error("Package not found. Build it first with: coral build")
        return false
    end if

    // Remove old version (keep database entry for now)
    mut files: [string] = new [string](4096)
    let file_count = get_files_list(pkg_name, files, 4096, root_path)

    color.print_info("Removing old files...")
    let actual_root = get_actual_root(root_path)
    remove_files(files, file_count, actual_root)

    // Install new version
    color.print_info("Installing new version...")

    // Create extraction directory
    let extract_dir = create_extract_dir(cfg)
    if str.length(extract_dir) == 0
        color.print_error("Failed to create extraction directory")
        return false
    end if

    // Extract package
    let result = package.extract_package(pkg_path, extract_dir)
    if not result.success
        color.print_error(result.error)
        cleanup_extract_dir(extract_dir)
        return false
    end if

    // Read new file list
    mut new_files: [string] = new [string](4096)
    let new_file_count = package.read_footprint(extract_dir, new_files, 4096)

    // Install files to proper root
    if not package.install_files(extract_dir, actual_root)
        color.print_error("Failed to install files")
        cleanup_extract_dir(extract_dir)
        return false
    end if

    // Update database (remove and re-add) using rooted versions if needed
    unregister_pkg(pkg_name, root_path)

    let new_info = package.read_pkginfo(extract_dir)
    mut new_pkg = types.new_installed_package()
    new_pkg.info = new_info
    new_pkg.install_date = "2025-01-24"
    new_pkg.install_reason = "explicit"
    new_pkg.files = new_files
    new_pkg.files_count = new_file_count

    // Register using rooted version if root is set
    if str.length(root_path) > 0
        if not database.register_from_extract_dir_rooted(new_pkg, extract_dir, root_path)
            color.print_warning("Failed to update database")
        end if
    else
        if not database.register_from_extract_dir(new_pkg, extract_dir)
            color.print_warning("Failed to update database")
        end if
    end if

    // Cleanup
    cleanup_extract_dir(extract_dir)

    color.print_success("Upgraded " + pkg_name + " to " + p.info.version)
    return true
end upgrade_package

// Find a package file by name and version
fn find_package(name: string, version: string, release: int, cfg: config.Config): string
    let packages_dir = config.get_packages_dir(cfg)
    let pkg_name = name + "-" + version + "-" + int_to_str(release) + ".pkg.tar.xz"
    let pkg_path = path.join_path(packages_dir, pkg_name)

    if file.fileExists(pkg_path)
        return pkg_path
    end if

    return ""
end find_package

// Remove files from system
fn remove_files(files: [string], file_count: int, root_path: string): bool
    mut i = file_count - 1
    while i >= 0
        let rel_path = files[i]
        let full_path = path.join_path(root_path, rel_path)

        if file.fileExists(full_path)
            let cmd = "rm -f \"" + full_path + "\""
            let pid = process.process_spawn_shell(cmd)
            if pid > 0
                process.process_wait(pid)
            end if
        end if

        i = i - 1
    end while

    return true
end remove_files

// Create extraction directory
fn create_extract_dir(cfg: config.Config): string
    let work_dir = config.get_work_dir(cfg)
    let pid = process.getpid()
    let extract_dir = path.join_path(work_dir, "upgrade_" + int_to_str(pid))

    if dir.dir_exists(extract_dir)
        let cmd = "rm -rf \"" + extract_dir + "\""
        let rm_pid = process.process_spawn_shell(cmd)
        if rm_pid > 0
            process.process_wait(rm_pid)
        end if
    end if

    if not res.is_ok(dir.create_dir_all(extract_dir))
        return ""
    end if

    return extract_dir
end create_extract_dir

// Cleanup extraction directory
fn cleanup_extract_dir(dir_path: string): bool
    if str.length(dir_path) == 0
        return true
    end if

    let cmd = "rm -rf \"" + dir_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if
    process.process_wait(pid)
    return true
end cleanup_extract_dir

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: verify.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Verify command - check installed package integrity

******************************************************************************/

module commands.verify

import sys.args
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import util.mtree
import util.checksum
import types
import util.color
import exitcodes as ec
import fs.stat
import fs.link
import core.result as res

export
    fn execute(opts: types.GlobalOptions): int
end export

fn execute(opts: types.GlobalOptions): int
    let argc = args.count()

    if argc <= opts.cmd_index + 1
        print_usage()
        return ec.EXIT_USAGE()
    end if

    // Load configuration and apply command-line overrides
    let base_cfg = config.load()
    let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
    let root_path = config.get_root(cfg)

    if opts.verbose and str.length(root_path) > 0
        color.print_info("Using root: " + root_path)
    end if

    let pkg_name = args.get(opts.cmd_index + 1)

    // Check if installed
    if not check_installed(pkg_name, root_path)
        color.print_error(pkg_name + " is not installed")
        return ec.EXIT_PKG_NOT_FOUND()
    end if

    color.print_action("Verifying " + pkg_name + "...")

    // Load manifest from database
    let manifest_path = database.get_manifest_path(pkg_name)
    if not file.fileExists(manifest_path)
        color.print_error("No manifest found for " + pkg_name + " (legacy package without .MANIFEST)")
        return ec.EXIT_PKG_INVALID()
    end if

    let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
    if str.length(manifest_content) == 0
        color.print_error("Empty manifest for " + pkg_name)
        return ec.EXIT_PKG_INVALID()
    end if

    mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
    let entry_count = mtree.parse_manifest(manifest_content, entries, 8192)

    if entry_count == 0
        color.print_error("Failed to parse manifest for " + pkg_name)
        return ec.EXIT_PKG_INVALID()
    end if

    // Determine actual root
    let actual_root = get_actual_root(root_path)

    // Verify each entry
    mut missing_count = 0
    mut checksum_fail_count = 0
    mut mode_fail_count = 0
    mut link_fail_count = 0
    mut ok_count = 0

    mut i = 0
    while i < entry_count
        let entry = entries[i]
        let etype = mtree.entry_type(entry)
        let epath = mtree.entry_path(entry)

        mut rel_path = epath
        if str.starts_with(epath, "./")
            rel_path = str.substring(epath, 2, str.length(epath) - 2)
        end if

        let full_path = path.join_path(actual_root, rel_path)

        if str.equals(etype, "dir")
            if not dir.dir_exists(full_path)
                color.print_warning("MISSING dir:  " + rel_path)
                missing_count = missing_count + 1
            else
                // Check mode
                let expected_mode = mtree.entry_mode(entry)
                let actual_mode = res.unwrap_or(stat.file_mode(full_path), 0)
                // Compare lower 12 bits (permissions + setuid/setgid/sticky)
                if (actual_mode % 4096) != (expected_mode % 4096)
                    if opts.verbose
                        color.print_warning("MODE " + rel_path + " (expected " + int_to_octal(expected_mode) + ", got " + int_to_octal(actual_mode) + ")")
                    else
                        color.print_warning("MODE          " + rel_path)
                    end if
                    mode_fail_count = mode_fail_count + 1
                else
                    ok_count = ok_count + 1
                end if
            end if

        elif str.equals(etype, "file")
            if not stat.exists(full_path)
                color.print_warning("MISSING file: " + rel_path)
                missing_count = missing_count + 1
            else
                mut file_ok = true

                // Check sha256
                let expected_sha = mtree.entry_sha256(entry)
                if str.length(expected_sha) > 0
                    let actual_sha = checksum.sha256_file(full_path)
                    if not str.equals(actual_sha, expected_sha)
                        color.print_warning("CHECKSUM      " + rel_path)
                        checksum_fail_count = checksum_fail_count + 1
                        file_ok = false
                    end if
                end if

                // Check mode
                let expected_mode = mtree.entry_mode(entry)
                let actual_mode = res.unwrap_or(stat.file_mode(full_path), 0)
                if (actual_mode % 4096) != (expected_mode % 4096)
                    if opts.verbose
                        color.print_warning("MODE " + rel_path + " (expected " + int_to_octal(expected_mode) + ", got " + int_to_octal(actual_mode) + ")")
                    else
                        color.print_warning("MODE          " + rel_path)
                    end if
                    mode_fail_count = mode_fail_count + 1
                    file_ok = false
                end if

                // Check ownership
                let expected_uid = mtree.name_to_uid(mtree.entry_uname(entry))
                let expected_gid = mtree.name_to_gid(mtree.entry_gname(entry))
                let actual_uid = res.unwrap_or(stat.file_uid(full_path), 0)
                let actual_gid = res.unwrap_or(stat.file_gid(full_path), 0)
                if actual_uid != expected_uid or actual_gid != expected_gid
                    if opts.verbose
                        color.print_warning("OWNER " + rel_path + " (expected " + mtree.entry_uname(entry) + ":" + mtree.entry_gname(entry) + ")")
                    else
                        color.print_warning("OWNER         " + rel_path)
                    end if
                    mode_fail_count = mode_fail_count + 1
                    file_ok = false
                end if

                if file_ok
                    ok_count = ok_count + 1
                end if
            end if

        elif str.equals(etype, "link")
            if not stat.is_symlink(full_path)
                if not stat.exists(full_path)
                    color.print_warning("MISSING link: " + rel_path)
                    missing_count = missing_count + 1
                else
                    color.print_warning("NOT A LINK    " + rel_path)
                    link_fail_count = link_fail_count + 1
                end if
            else
                let expected_target = mtree.entry_link(entry)
                let actual_target = res.unwrap_or(link.readlink(full_path), "")
                if not str.equals(actual_target, expected_target)
                    if opts.verbose
                        color.print_warning("LINK " + rel_path + " -> " + actual_target + " (expected " + expected_target + ")")
                    else
                        color.print_warning("LINK TARGET   " + rel_path)
                    end if
                    link_fail_count = link_fail_count + 1
                else
                    ok_count = ok_count + 1
                end if
            end if
        end if

        i = i + 1
    end while

    // Summary
    println("")
    let total_issues = missing_count + checksum_fail_count + mode_fail_count + link_fail_count
    if total_issues == 0
        color.print_success(pkg_name + ": " + int_to_str(ok_count) + " entries verified, all OK")
        return ec.EXIT_SUCCESS()
    else
        color.print_error(pkg_name + ": " + int_to_str(total_issues) + " issue(s) found")
        if missing_count > 0
            println("  Missing:    " + int_to_str(missing_count))
        end if
        if checksum_fail_count > 0
            println("  Checksum:   " + int_to_str(checksum_fail_count))
        end if
        if mode_fail_count > 0
            println("  Mode/Owner: " + int_to_str(mode_fail_count))
        end if
        if link_fail_count > 0
            println("  Symlinks:   " + int_to_str(link_fail_count))
        end if
        println("  OK:         " + int_to_str(ok_count))
        return ec.EXIT_PKG_CHECKSUM_MISMATCH()
    end if
end execute

fn check_installed(name: string, root_path: string): bool
    if str.length(root_path) > 0
        return database.is_installed_rooted(name, root_path)
    end if
    return database.is_installed(name)
end check_installed

fn get_actual_root(root_path: string): string
    if str.length(root_path) == 0
        return "/"
    end if
    return root_path
end get_actual_root

proc print_usage()
    println("Usage: coral verify <package>")
    println("")
    println("Verify integrity of an installed package against its manifest.")
    println("")
    println("Checks:")
    println("  - Missing files, directories, and symlinks")
    println("  - File checksum (sha256) mismatches")
    println("  - Permission and ownership changes")
    println("  - Broken or incorrect symlink targets")
    println("")
    println("Arguments:")
    println("  <package>    Name of installed package to verify")
    println("")
    println("Options:")
    println("  -v, --verbose    Show expected vs actual values for failures")
    println("")
    println("Examples:")
    println("  coral verify vim")
    println("  coral verify -v openssl")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

// Helper: convert int to octal string (for mode display)
fn int_to_octal(n: int): string
    if n == 0
        return "0"
    end if

    mut value = n % 4096
    mut result = ""
    while value > 0
        let digit = value % 8
        result = str.concat(str.substring("01234567", digit, 1), result)
        value = value / 8
    end while

    return result
end int_to_octal

end module