onelf 0.2.1

Packer CLI for creating onelf single-binary packages
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
//! Shared library bundling for ONELF packages.
//!
//! Scans ELF binaries in a directory for shared library dependencies,
//! resolves them via ldconfig cache, standard paths, or NixOS store
//! scanning, and copies them into a lib directory for self-contained
//! packaging.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{self, BufRead};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;

mod color {
    use std::io::IsTerminal;
    use std::sync::OnceLock;

    static ENABLED: OnceLock<bool> = OnceLock::new();

    fn enabled() -> bool {
        *ENABLED.get_or_init(|| {
            std::env::var_os("NO_COLOR").is_none() && std::io::stderr().is_terminal()
        })
    }

    pub fn bold(s: &str) -> String {
        if enabled() {
            format!("\x1b[1m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub fn red(s: &str) -> String {
        if enabled() {
            format!("\x1b[31m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub fn cyan(s: &str) -> String {
        if enabled() {
            format!("\x1b[36m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub fn dim(s: &str) -> String {
        if enabled() {
            format!("\x1b[2m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub fn bold_green(s: &str) -> String {
        if enabled() {
            format!("\x1b[1;32m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub fn bold_red(s: &str) -> String {
        if enabled() {
            format!("\x1b[1;31m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
}

pub(crate) fn format_size(bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        format!("{:.1} GB", bytes as f64 / 1_073_741_824.0)
    } else if bytes >= 1_048_576 {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{bytes} B")
    }
}

/// Ensure a file is writable so it can be overwritten on re-runs.
/// No-op if the file doesn't exist yet.
fn ensure_writable(path: &Path) {
    if let Ok(meta) = fs::metadata(path) {
        let mode = meta.permissions().mode();
        if mode & 0o200 == 0 {
            let _ = fs::set_permissions(path, PermissionsExt::from_mode(mode | 0o200));
        }
    }
}

fn verb_str(dry_run: bool) -> String {
    if dry_run {
        color::bold("Would copy")
    } else {
        color::bold_green("Copied")
    }
}

/// Build a search path list from RPATH dirs, standard system paths,
/// NixOS store closures, and user-provided extra paths.
fn build_lib_search_dirs(
    elf_files: &[PathBuf],
    extra_search: &[PathBuf],
    nix_store_paths: &[String],
) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();

    // RPATH dirs from app binaries (highest priority)
    for elf in elf_files {
        for rdir in parse_rpaths(elf) {
            if rdir.is_dir() && !dirs.contains(&rdir) {
                dirs.push(rdir);
            }
        }
    }

    // Standard system lib paths
    for path in STANDARD_LIB_PATHS {
        let p = PathBuf::from(path);
        if p.is_dir() && !dirs.contains(&p) {
            dirs.push(p);
        }
    }

    // NixOS store lib dirs
    for sp in nix_store_paths {
        let lib = PathBuf::from(sp).join("lib");
        if lib.is_dir() && !dirs.contains(&lib) {
            dirs.push(lib);
        }
    }

    // User-provided extra search paths
    for dir in extra_search {
        if dir.is_dir() && !dirs.contains(dir) {
            dirs.push(dir.clone());
        }
    }

    dirs
}

/// Copy libraries matching any of `prefixes` (prefix match on filename) from
/// `search_dirs` into `dest`. Resolves symlinks, deduplicates by filename,
/// and filters by ELF class. Returns (files_copied, total_bytes).
fn copy_prefixed_libs(
    search_dirs: &[PathBuf],
    prefixes: &[&str],
    dest: &Path,
    target_class: Option<u8>,
    dry_run: bool,
    strip: bool,
) -> io::Result<(usize, u64)> {
    let mut copied = 0usize;
    let mut total_bytes = 0u64;
    let mut seen: HashSet<String> = HashSet::new();

    for dir in search_dirs {
        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            if !path.is_file() && !path.is_symlink() {
                continue;
            }
            let name = match path.file_name() {
                Some(n) => n.to_string_lossy().into_owned(),
                None => continue,
            };
            if !prefixes.iter().any(|p| name.starts_with(p)) {
                continue;
            }
            if !seen.insert(name.clone()) {
                continue;
            }
            let resolved = fs::canonicalize(&path).unwrap_or(path.clone());
            if !resolved.is_file() {
                continue;
            }
            if let Some(tc) = target_class {
                if read_elf_class(&resolved) != Some(tc) {
                    continue;
                }
            }
            let size = fs::metadata(&resolved).map(|m| m.len()).unwrap_or(0);
            eprintln!(
                "  {} <- {} ({})",
                color::bold_green(&name),
                resolved.display(),
                color::dim(&format_size(size))
            );
            if !dry_run {
                fs::create_dir_all(dest)?;
                let dest_path = dest.join(&name);
                ensure_writable(&dest_path);
                fs::copy(&resolved, &dest_path)?;
                let _ = fs::set_permissions(&dest_path, PermissionsExt::from_mode(0o755));
                if strip {
                    strip_debug(&dest_path);
                }
            }
            copied += 1;
            total_bytes += size;
        }
    }
    Ok((copied, total_bytes))
}

const DEFAULT_EXCLUDES: &[&str] = &[
    "libnss_",
    "libcuda.so",
    "libnvidia",
    "libamdhip64.so",
    "libze_loader.so",
    "linux-vdso.so",
];

const STANDARD_LIB_PATHS: &[&str] = &[
    "/usr/lib",
    "/usr/lib64",
    "/usr/lib/x86_64-linux-gnu",
    "/lib",
    "/lib64",
    "/lib/x86_64-linux-gnu",
];

pub struct BundleOptions {
    pub directory: PathBuf,
    pub target: Option<PathBuf>,
    pub lib_dir: PathBuf,
    pub exclude: Vec<String>,
    pub include: Vec<String>,
    pub search_path: Vec<PathBuf>,
    pub dry_run: bool,
    pub recursive: bool,
    pub gl: bool,
    pub dri: bool,
    pub vulkan: bool,
    pub wayland: bool,
    pub gtk: bool,
    pub strip: bool,
    pub strict_libc: bool,
    pub scan_dlopen: bool,
    /// Additional sonames added to the dlopen scan allow-list.
    pub dlopen_extra: Vec<String>,
}

/// Strip debug symbols from a shared library (best-effort).
fn strip_debug(path: &Path) {
    match Command::new("strip")
        .arg("--strip-unneeded")
        .arg(path)
        .output()
    {
        Ok(out) if !out.status.success() => {
            eprintln!(
                "  {} strip failed for {}: {}",
                color::bold_red("warning:"),
                path.display(),
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Err(e) => {
            eprintln!(
                "  {} strip failed for {}: {e}",
                color::bold_red("warning:"),
                path.display()
            );
        }
        _ => {}
    }
}

pub fn bundle_libs(opts: &BundleOptions) -> io::Result<()> {
    if !opts.directory.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::NotADirectory,
            format!("{}: not a directory", opts.directory.display()),
        ));
    }

    // Auto-detect frameworks from the input binaries' DT_NEEDED entries.
    // User-provided flags are OR'd with detected flags so explicit opt-ins win
    // but the tool does the right thing when the user passes nothing.
    let detected = detect_frameworks(&opts.directory, opts.target.as_deref());
    let want_gl = opts.gl || detected.gl;
    let want_dri = opts.dri || detected.dri;
    let want_vulkan = opts.vulkan || detected.vulkan;
    let want_wayland = opts.wayland || detected.wayland;
    let want_gtk = opts.gtk || detected.gtk;

    if (detected.gl || detected.dri || detected.vulkan || detected.wayland || detected.gtk)
        && (!opts.gl || !opts.dri || !opts.vulkan || !opts.wayland || !opts.gtk)
    {
        let mut parts = Vec::new();
        if detected.gl && !opts.gl {
            parts.push("gl");
        }
        if detected.dri && !opts.dri {
            parts.push("dri");
        }
        if detected.vulkan && !opts.vulkan {
            parts.push("vulkan");
        }
        if detected.wayland && !opts.wayland {
            parts.push("wayland");
        }
        if detected.gtk && !opts.gtk {
            parts.push("gtk");
        }
        if !parts.is_empty() {
            eprintln!(
                "  {} auto-enabled: {}",
                color::bold("Frameworks:"),
                parts.join(", ")
            );
        }
    }

    // Bundle GPU assets first so DRI driver .so files are present when
    // find_elf_files runs, letting the main loop resolve their transitive deps.
    if want_gl || want_dri || want_vulkan {
        bundle_gpu(
            &opts.directory,
            &opts.lib_dir,
            &opts.search_path,
            opts.dry_run,
            opts.strip,
            want_gl,
            want_dri,
            want_vulkan,
        )?;
    }

    if want_wayland {
        bundle_wayland(
            &opts.directory,
            &opts.lib_dir,
            &opts.search_path,
            opts.dry_run,
            opts.strip,
        )?;
    }

    if want_gtk {
        bundle_gtk_data(&opts.directory, opts.dry_run)?;
    }

    let excludes: Vec<&str> = DEFAULT_EXCLUDES
        .iter()
        .copied()
        .chain(opts.exclude.iter().map(|s| s.as_str()))
        .collect();

    let elf_files = if let Some(ref target) = opts.target {
        let path = if target.is_absolute() {
            target.clone()
        } else {
            opts.directory.join(target)
        };
        if !path.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("{}: not a file", path.display()),
            ));
        }
        vec![path]
    } else {
        find_elf_files(&opts.directory)
    };

    if elf_files.is_empty() {
        eprintln!(
            "{} no ELF files found in {}",
            color::bold_red("warning:"),
            opts.directory.display()
        );
        return Ok(());
    }

    eprintln!(
        "{} {} ELF file(s)...",
        color::bold("Scanning"),
        elf_files.len()
    );

    // Track soname -> first file that requires it (for diagnostics)
    let mut needed_by: HashMap<String, String> = HashMap::new();
    let mut rpath_dirs: Vec<PathBuf> = Vec::new();
    for path in &elf_files {
        let requirer = path
            .strip_prefix(&opts.directory)
            .unwrap_or(path)
            .to_string_lossy()
            .into_owned();
        match parse_needed(path) {
            Ok(libs) => {
                for lib in libs {
                    needed_by.entry(lib).or_insert_with(|| requirer.clone());
                }
            }
            Err(e) => {
                eprintln!("warning: {}: {e}", path.display());
            }
        }
        // Also include the ELF interpreter itself. Distros that ship a
        // stub loader (notably NixOS) have a PT_INTERP path that exists
        // but won't actually run foreign binaries, so the runtime needs
        // a real loader in the bundle to sidestep the stub.
        if let Some(interp) = parse_interp(path) {
            if let Some(name) = Path::new(&interp).file_name().and_then(|n| n.to_str()) {
                needed_by
                    .entry(name.to_string())
                    .or_insert_with(|| format!("{requirer} (PT_INTERP)"));
            }
        }
        // Collect RPATH/RUNPATH directories from input binaries
        for dir in parse_rpaths(path) {
            if !rpath_dirs.contains(&dir) {
                rpath_dirs.push(dir);
            }
        }
    }

    // Add explicitly included libs (e.g. dlopen'd libraries)
    for lib in &opts.include {
        needed_by
            .entry(lib.clone())
            .or_insert_with(|| "--include".into());
    }

    // Opt-in dlopen scan: match string literals against a known allow-list
    // of commonly dlopen'd sonames (GL, Wayland, Vulkan, audio, etc.) and
    // queue the hits as if the user had passed them via --include.
    if opts.scan_dlopen {
        let mut scanned: HashSet<String> = HashSet::new();
        for path in &elf_files {
            if let Ok(hits) = scan_dlopen(path, &opts.dlopen_extra) {
                for soname in hits {
                    if scanned.insert(soname.clone()) {
                        let requirer = path
                            .strip_prefix(&opts.directory)
                            .unwrap_or(path)
                            .to_string_lossy()
                            .into_owned();
                        let label = format!("--scan-dlopen in {requirer}");
                        needed_by.entry(soname).or_insert(label);
                    }
                }
            }
        }
        if !scanned.is_empty() {
            eprintln!(
                "  {} {} dlopen candidate(s): {}",
                color::bold("Scanned:"),
                scanned.len(),
                scanned.iter().cloned().collect::<Vec<_>>().join(", ")
            );
        }
    }

    // Filter excluded
    needed_by.retain(|soname, _| !is_excluded(soname, &excludes));

    // Filter libs already present in the directory tree
    let existing = find_existing_libs(&opts.directory);
    needed_by.retain(|soname, _| !existing.contains(soname));

    if needed_by.is_empty() {
        eprintln!("All dependencies satisfied, nothing to bundle.");
        // PT_INTERP + RUNPATH rewrites still need to run. A prior bundle
        // may have left stale paths (e.g. from an older onelf version)
        // that either don't resolve under the current CWD policy or
        // still rely on LD_LIBRARY_PATH.
        if !opts.dry_run {
            let lib_dest = opts.directory.join(&opts.lib_dir);
            let mut rewritten = 0usize;
            for path in find_elf_files(&opts.directory) {
                let perms = fs::metadata(&path)
                    .map(|m| m.permissions().mode())
                    .unwrap_or(0o755);
                let needs_chmod = perms & 0o200 == 0;
                if needs_chmod {
                    let _ = fs::set_permissions(
                        &path,
                        std::os::unix::fs::PermissionsExt::from_mode(perms | 0o200),
                    );
                }
                if set_origin_runpath(&path).is_ok() {
                    rewritten += 1;
                }
                let _ = scrub_nix_store_paths(&path);
                let _ = strip_absolute_needed(&path);
                if needs_chmod {
                    let _ = fs::set_permissions(
                        &path,
                        std::os::unix::fs::PermissionsExt::from_mode(perms),
                    );
                }
            }
            if rewritten > 0 {
                eprintln!(
                    "{} RUNPATH to $ORIGIN/../lib in {} binaries",
                    color::bold("Rewrote"),
                    rewritten
                );
            }
            match patch_interps_to_bundled(&opts.directory, &lib_dest) {
                Ok(n) if n > 0 => eprintln!(
                    "{} PT_INTERP of {} binaries",
                    color::bold("Patched"),
                    n
                ),
                Ok(_) => {}
                Err(e) => eprintln!(
                    "{} PT_INTERP patching failed: {e}",
                    color::bold_red("warning:"),
                ),
            }
        }
        return Ok(());
    }

    // Determine target ELF class (32-bit vs 64-bit) from the input binaries
    let target_class = elf_files.iter().find_map(|f| read_elf_class(f));

    // Determine target libc family from PT_INTERP. Used to skip spurious
    // cross-libc transitive dependencies (e.g. libgcc_s on a glibc host pulls
    // in libc.so.6 + ld-linux, which can't be used by a musl-linked binary).
    let target_libc = elf_files
        .iter()
        .find_map(|f| parse_interp(f).as_deref().and_then(libc_family_from_interp));

    // Drop sonames from the initial queue that belong to the wrong libc family.
    if let Some(target) = target_libc {
        needed_by.retain(|soname, _| libc_family_of_soname(soname).is_none_or(|fam| fam == target));
    }

    let mut ldconfig_cache = build_lib_cache();
    let mut search_paths: Vec<PathBuf> = opts.search_path.clone();
    search_paths.extend(rpath_dirs);
    let lib_dest = opts.directory.join(&opts.lib_dir);

    let mut copied: Vec<(String, PathBuf, u64, String)> = Vec::new();
    let mut not_found: Vec<(String, String)> = Vec::new();
    let mut already_processed: HashSet<String> = HashSet::new();
    let mut expanded_nix: HashSet<PathBuf> = HashSet::new();
    // BLAKE3(content) -> soname, so aliases with identical bytes symlink instead of copy.
    let mut bundled_by_hash: HashMap<[u8; 32], String> = HashMap::new();
    let mut queue: Vec<String> = needed_by.keys().cloned().collect();
    queue.sort();

    // On NixOS: pre-expand cache for libs already in the dest dir from previous runs,
    // so their transitive nix deps are discoverable.
    if Path::new("/nix/store").is_dir() {
        for lib_name in find_existing_libs(&lib_dest) {
            if let Some(src) = locate_lib(&lib_name, &ldconfig_cache, &search_paths, target_class) {
                let resolved = fs::canonicalize(&src).unwrap_or(src);
                expand_nix_cache(&resolved, &mut ldconfig_cache, &mut expanded_nix);
            }
        }
    }

    while let Some(soname) = queue.pop() {
        if already_processed.contains(&soname) || is_excluded(&soname, &excludes) {
            continue;
        }
        already_processed.insert(soname.clone());

        // Skip if already in directory tree (may have been copied in a previous iteration)
        if lib_dest.join(&soname).exists() {
            continue;
        }

        let requirer = needed_by
            .get(&soname)
            .cloned()
            .unwrap_or_else(|| "?".into());

        match locate_lib(&soname, &ldconfig_cache, &search_paths, target_class) {
            Some(src) => {
                let resolved = fs::canonicalize(&src).unwrap_or(src.clone());
                let size = fs::metadata(&resolved).map(|m| m.len()).unwrap_or(0);
                let dest = lib_dest.join(&soname);

                // Check libc family of this candidate before copying: if it
                // mismatches the target and --strict-libc is set, skip.
                let lib_needed = parse_needed(&resolved).unwrap_or_default();
                let lib_family = lib_needed.iter().find_map(|d| libc_family_of_soname(d));
                let mismatch = matches!(
                    (target_libc, lib_family),
                    (Some(t), Some(f)) if t != f
                );
                if mismatch {
                    let msg = format!(
                        "{} links against {:?} libc but target is {:?}",
                        soname,
                        lib_family.unwrap(),
                        target_libc.unwrap()
                    );
                    if opts.strict_libc {
                        eprintln!(
                            "  {} skipping {} ({})",
                            color::bold_red("skip:"),
                            color::cyan(&soname),
                            msg,
                        );
                        not_found.push((soname.clone(), format!("{requirer} ({msg})")));
                        continue;
                    }
                    eprintln!(
                        "  {} {}; this bundle may not work at runtime",
                        color::bold_red("warning:"),
                        msg,
                    );
                }

                // On NixOS: expand cache with this store path's closure
                // so transitive deps (e.g. libsndfile for libpulsecommon) are found
                expand_nix_cache(&resolved, &mut ldconfig_cache, &mut expanded_nix);

                let content_hash: Option<[u8; 32]> = fs::read(&resolved)
                    .ok()
                    .map(|bytes| blake3::hash(&bytes).into());
                if let Some(hash) = content_hash {
                    if let Some(existing_name) = bundled_by_hash.get(&hash).cloned() {
                        eprintln!(
                            "  {} {} -> {} (alias for {}, {})",
                            color::bold_green("Linked"),
                            soname,
                            existing_name,
                            color::cyan(&requirer),
                            color::dim(&format_size(size))
                        );
                        if !opts.dry_run {
                            fs::create_dir_all(&lib_dest)?;
                            let dest = lib_dest.join(&soname);
                            if dest.exists() || dest.is_symlink() {
                                let _ = fs::remove_file(&dest);
                            }
                            if let Err(e) = std::os::unix::fs::symlink(&existing_name, &dest) {
                                eprintln!(
                                    "  {} failed to symlink {} -> {}: {e}",
                                    color::bold_red("warning:"),
                                    soname,
                                    existing_name
                                );
                            }
                        }
                        continue;
                    }
                }

                eprintln!(
                    "  {} <- {} (needed by {}, {})",
                    color::bold_green(&soname),
                    resolved.display(),
                    color::cyan(&requirer),
                    color::dim(&format_size(size))
                );
                if !opts.dry_run {
                    fs::create_dir_all(&lib_dest)?;
                    ensure_writable(&dest);
                    fs::copy(&resolved, &dest)?;
                    let _ = fs::set_permissions(
                        &dest,
                        std::os::unix::fs::PermissionsExt::from_mode(0o755),
                    );
                    // Strip hardcoded RPATH/RUNPATH so the bundled lib uses
                    // LD_LIBRARY_PATH (set by the runtime) instead of absolute paths
                    if let Err(e) = set_origin_runpath(&dest) {
                        eprintln!(
                            "  {} failed to rewrite RUNPATH of {}: {e}",
                            color::bold_red("warning:"),
                            soname
                        );
                    }
                    // The dynamic loader itself ships with baked-in absolute
                    // paths (ld.so.cache location, preload hook, fallback
                    // library dirs). On the packer's system those resolve to
                    // real files (e.g. /nix/store/.../glibc/etc/ld.so.cache);
                    // on someone else's system they're dead paths at best and
                    // wrong-content paths at worst. Scrub before shipping.
                    if is_dynamic_loader(&soname) {
                        if let Err(e) = scrub_loader_paths(&dest) {
                            eprintln!(
                                "  {} failed to scrub loader paths in {}: {e}",
                                color::bold_red("warning:"),
                                soname
                            );
                        }
                    }
                    if opts.strip {
                        strip_debug(&dest);
                    }
                }

                if let Some(hash) = content_hash {
                    bundled_by_hash.insert(hash, soname.clone());
                }
                copied.push((soname.clone(), resolved.clone(), size, requirer));

                // Collect RPATHs from resolved lib for transitive dep resolution
                for dir in parse_rpaths(&resolved) {
                    if !search_paths.contains(&dir) {
                        search_paths.push(dir);
                    }
                }

                // Resolve transitive dependencies
                if opts.recursive {
                    for dep in lib_needed {
                        if already_processed.contains(&dep)
                            || is_excluded(&dep, &excludes)
                            || existing.contains(&dep)
                        {
                            continue;
                        }
                        // Target's libc is already queued via its direct NEEDED;
                        // any libc-family transitive is either wrong-family or a redundant alias.
                        if libc_family_of_soname(&dep).is_some() {
                            continue;
                        }
                        needed_by
                            .entry(dep.clone())
                            .or_insert_with(|| soname.clone());
                        queue.push(dep);
                    }
                }
            }
            None => {
                not_found.push((soname, requirer));
            }
        }
    }

    // Summary
    copied.sort_by(|a, b| a.0.cmp(&b.0));
    not_found.sort();

    let total_size: u64 = copied.iter().map(|(_, _, s, _)| s).sum();

    if opts.dry_run {
        eprintln!(
            "\n{} would copy {} libraries ({})",
            color::bold("Dry run:"),
            color::bold_green(&copied.len().to_string()),
            color::bold(&format_size(total_size))
        );
    } else if !copied.is_empty() {
        eprintln!(
            "\n{} {} libraries ({}) to {}",
            color::bold_green("Copied"),
            copied.len(),
            color::bold(&format_size(total_size)),
            lib_dest.display()
        );
    }

    if !not_found.is_empty() {
        eprintln!("\n{} ({})", color::bold_red("Not found"), not_found.len());
        for (lib, requirer) in &not_found {
            eprintln!(
                "  {} {}",
                color::red(lib),
                color::dim(&format!("(needed by {})", color::cyan(requirer)))
            );
        }
    }

    // Ensure each ELF's PT_INTERP basename exists in lib_dest as a file or
    // symlink. On musl the loader is referenced as ld-musl-*.so.1 but bundled
    // as libc.musl-*.so.1 (both are names for the same file on disk); without
    // the alias the kernel can't find the interpreter at runtime.
    if !opts.dry_run {
        let mut interp_names: Vec<String> = elf_files
            .iter()
            .filter_map(|p| {
                parse_interp(p).and_then(|i| {
                    Path::new(&i)
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                })
            })
            .collect();
        interp_names.sort();
        interp_names.dedup();

        for interp_name in interp_names {
            let target = lib_dest.join(&interp_name);
            if target.exists() || target.is_symlink() {
                continue;
            }
            let Some(libc_name) = libc_alias_for(&interp_name) else {
                continue;
            };
            let libc_path = lib_dest.join(&libc_name);
            if !libc_path.exists() {
                continue;
            }
            if let Err(e) = std::os::unix::fs::symlink(&libc_name, &target) {
                eprintln!(
                    "  {} failed to create {} -> {}: {e}",
                    color::bold_red("warning:"),
                    interp_name,
                    libc_name
                );
            } else {
                eprintln!(
                    "  {} {} -> {}",
                    color::bold_green("Linked"),
                    interp_name,
                    libc_name
                );
            }
        }
    }

    // Strip RPATHs from all ELF files in the directory for portability.
    // Hardcoded absolute paths (e.g. /nix/store/...) won't exist on the
    // target system; LD_LIBRARY_PATH (set by the runtime) is used instead.
    if !opts.dry_run {
        let mut rewritten = 0usize;
        let mut scrubbed = 0usize;
        for path in find_elf_files(&opts.directory) {
            let perms = fs::metadata(&path)
                .map(|m| m.permissions().mode())
                .unwrap_or(0o755);
            let needs_chmod = perms & 0o200 == 0;
            if needs_chmod {
                let _ = fs::set_permissions(
                    &path,
                    std::os::unix::fs::PermissionsExt::from_mode(perms | 0o200),
                );
            }
            if set_origin_runpath(&path).is_ok() {
                rewritten += 1;
            }
            let before = fs::metadata(&path).and_then(|m| m.modified()).ok();
            let _ = scrub_nix_store_paths(&path);
            let _ = strip_absolute_needed(&path);
            let after = fs::metadata(&path).and_then(|m| m.modified()).ok();
            if before.is_some() && before != after {
                scrubbed += 1;
            }
            if needs_chmod {
                let _ =
                    fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(perms));
            }
        }
        if rewritten > 0 {
            eprintln!(
                "{} RUNPATH to $ORIGIN/../lib in {} binaries",
                color::bold("Rewrote"),
                rewritten
            );
        }
        if scrubbed > 0 {
            eprintln!(
                "{} /nix/store paths in {} binaries",
                color::bold("Scrubbed"),
                scrubbed
            );
        }
    }

    // Patch PT_INTERP of every ELF with a bundled loader. This is what
    // makes /proc/self/exe point at the real target after kernel exec
    // (Python's stdlib detection, Electron's ASAR locator, Qt's plugin
    // loader all read /proc/self/exe). The runtime and `onelf run` chdir
    // into the AppDir before exec so the relative path resolves.
    if !opts.dry_run {
        match patch_interps_to_bundled(&opts.directory, &lib_dest) {
            Ok(n) if n > 0 => eprintln!(
                "{} PT_INTERP of {} binaries",
                color::bold("Patched"),
                n
            ),
            Ok(_) => {}
            Err(e) => eprintln!(
                "{} PT_INTERP patching failed: {e}",
                color::bold_red("warning:"),
            ),
        }
    }

    Ok(())
}

fn find_elf_files(dir: &Path) -> Vec<PathBuf> {
    let mut result = Vec::new();
    for entry in jwalk::WalkDir::new(dir).skip_hidden(false) {
        let Ok(entry) = entry else { continue };
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        if is_elf(&path) {
            result.push(path);
        }
    }
    result
}

fn is_elf(path: &Path) -> bool {
    fs::File::open(path)
        .and_then(|mut f| {
            let mut magic = [0u8; 4];
            io::Read::read_exact(&mut f, &mut magic)?;
            Ok(magic == *b"\x7fELF")
        })
        .unwrap_or(false)
}

/// Read the ELF class (1 = 32-bit, 2 = 64-bit) from a file.
fn read_elf_class(path: &Path) -> Option<u8> {
    let mut f = fs::File::open(path).ok()?;
    let mut header = [0u8; 5];
    io::Read::read_exact(&mut f, &mut header).ok()?;
    if header[0..4] == *b"\x7fELF" {
        Some(header[4])
    } else {
        None
    }
}

/// Read the ELF e_machine field (bytes 18-19, little-endian).
fn read_elf_machine(path: &Path) -> Option<u16> {
    let mut f = fs::File::open(path).ok()?;
    let mut header = [0u8; 20];
    io::Read::read_exact(&mut f, &mut header).ok()?;
    if header[0..4] != *b"\x7fELF" {
        return None;
    }
    Some(u16::from_le_bytes([header[18], header[19]]))
}

const EM_X86_64: u16 = 62;
const EM_386: u16 = 3;
const EM_AARCH64: u16 = 183;
const EM_ARM: u16 = 40;

/// Vulkan driver filenames relevant to x86/x86_64 desktop GPUs.
const VULKAN_DRIVERS_X86: &[&str] = &[
    "libvulkan_intel.so",
    "libvulkan_radeon.so",
    "libvulkan_nouveau.so",
    "libvulkan_lvp.so",
    "libvulkan_virtio.so",
];

/// Vulkan driver filenames relevant to ARM/AArch64 GPUs.
const VULKAN_DRIVERS_ARM: &[&str] = &[
    "libvulkan_panfrost.so",
    "libvulkan_asahi.so",
    "libvulkan_freedreno.so",
    "libvulkan_broadcom.so",
    "libvulkan_powervr_mesa.so",
    "libvulkan_lvp.so",
    "libvulkan_virtio.so",
];

/// DRI driver filenames relevant to x86/x86_64.
const DRI_DRIVERS_X86: &[&str] = &[
    "iris_dri.so",
    "i915_dri.so",
    "i965_dri.so",
    "radeonsi_dri.so",
    "r600_dri.so",
    "r300_dri.so",
    "nouveau_dri.so",
    "swrast_dri.so",
    "kms_swrast_dri.so",
    "vmwgfx_dri.so",
    "virtio_gpu_dri.so",
    "zink_dri.so",
];

/// DRI driver filenames relevant to ARM/AArch64.
const DRI_DRIVERS_ARM: &[&str] = &[
    "panfrost_dri.so",
    "asahi_dri.so",
    "freedreno_dri.so",
    "v3d_dri.so",
    "vc4_dri.so",
    "etnaviv_dri.so",
    "lima_dri.so",
    "tegra_dri.so",
    "swrast_dri.so",
    "kms_swrast_dri.so",
    "virtio_gpu_dri.so",
    "zink_dri.so",
];

/// Get the architecture-specific driver filter list.
/// Returns None for unknown architectures (no filtering).
fn driver_filter(
    machine: Option<u16>,
    x86_list: &'static [&'static str],
    arm_list: &'static [&'static str],
) -> Option<&'static [&'static str]> {
    match machine {
        Some(EM_X86_64) | Some(EM_386) => Some(x86_list),
        Some(EM_AARCH64) | Some(EM_ARM) => Some(arm_list),
        _ => None,
    }
}

#[derive(Default, Debug, Clone, Copy)]
struct FrameworkFlags {
    gl: bool,
    dri: bool,
    vulkan: bool,
    wayland: bool,
    gtk: bool,
}

/// Inspect DT_NEEDED across the input binaries (or the --target if set) and
/// infer which framework bundlers should run. Heuristics track common sonames:
/// the user can still explicitly pass the flags to force any of them on.
fn detect_frameworks(directory: &Path, target: Option<&Path>) -> FrameworkFlags {
    let files = match target {
        Some(t) => {
            let p = if t.is_absolute() {
                t.to_path_buf()
            } else {
                directory.join(t)
            };
            if p.is_file() {
                vec![p]
            } else {
                return FrameworkFlags::default();
            }
        }
        None => find_elf_files(directory),
    };
    let mut flags = FrameworkFlags::default();
    for path in &files {
        if let Ok(needed) = parse_needed(path) {
            for soname in needed {
                inspect_soname_for_frameworks(&soname, &mut flags);
            }
        }

        // Also scan for literal soname strings in the binary. Apps like
        // Blender don't DT_NEED libwayland-cursor or libdecor; they
        // dlopen them at runtime after detecting the session type.
        // Without a string scan, detect_frameworks would miss wayland
        // on such apps and the user would have to pass --wayland.
        if let Ok(bytes) = fs::read(path) {
            scan_framework_strings(&bytes, &mut flags);
        }
    }
    flags
}

/// Inspect a single soname (from DT_NEEDED or a dlopen string scan)
/// and turn on whichever framework flags it implies.
fn inspect_soname_for_frameworks(soname: &str, flags: &mut FrameworkFlags) {
    if soname.starts_with("libGL.so")
        || soname.starts_with("libEGL.so")
        || soname.starts_with("libGLESv")
        || soname.starts_with("libOpenGL.so")
    {
        flags.gl = true;
        flags.dri = true;
    }
    if soname.starts_with("libgbm.so") {
        flags.dri = true;
    }
    if soname.starts_with("libvulkan.so") {
        flags.vulkan = true;
    }
    if soname.starts_with("libwayland-client.so")
        || soname.starts_with("libwayland-egl.so")
        || soname.starts_with("libwayland-cursor.so")
        || soname.starts_with("libwayland-server.so")
        || soname.starts_with("libdecor-0.so")
    {
        flags.wayland = true;
    }
    if soname.starts_with("libgtk-3.so")
        || soname.starts_with("libgtk-4.so")
        || soname.starts_with("libgtk-")
    {
        flags.gtk = true;
    }
}

/// Walk the byte buffer looking for null-terminated library names that
/// would make us enable a framework bundler. Only matches on well-known
/// soname prefixes to avoid false positives from arbitrary strings in
/// the binary.
fn scan_framework_strings(bytes: &[u8], flags: &mut FrameworkFlags) {
    const PREFIXES: &[&[u8]] = &[
        b"libGL.so",
        b"libEGL.so",
        b"libGLESv",
        b"libOpenGL.so",
        b"libgbm.so",
        b"libvulkan.so",
        b"libwayland-client.so",
        b"libwayland-egl.so",
        b"libwayland-cursor.so",
        b"libwayland-server.so",
        b"libdecor-0.so",
        b"libgtk-3.so",
        b"libgtk-4.so",
    ];
    let needles: Vec<&[u8]> = PREFIXES.iter().copied().collect();
    let max_len = needles.iter().map(|n| n.len()).max().unwrap_or(0);
    let mut i = 0;
    while i + max_len <= bytes.len() {
        // Cheap gate: must start with 'l' to be any of our sonames.
        if bytes[i] != b'l' {
            i += 1;
            continue;
        }
        for needle in &needles {
            if i + needle.len() <= bytes.len() && &bytes[i..i + needle.len()] == *needle {
                // The printable path normally ends at a NUL; bail out
                // if the byte after the match is a printable path char
                // (digit, dot): we still match the prefix when iteration
                // continues past this point, or stop on NUL.
                if let Ok(soname) = std::str::from_utf8(&bytes[i..i + needle.len()]) {
                    inspect_soname_for_frameworks(soname, flags);
                }
                break;
            }
        }
        i += 1;
    }
}

/// Sonames that applications commonly dlopen at runtime. Absence from DT_NEEDED
/// doesn't mean absence from the runtime graph; these are known offenders.
const DLOPEN_CANDIDATES: &[&str] = &[
    // OpenGL / GLVND
    "libGL.so.1",
    "libEGL.so.1",
    "libGLX.so.0",
    "libGLdispatch.so.0",
    "libOpenGL.so.0",
    "libGLESv1_CM.so.1",
    "libGLESv2.so.2",
    "libgbm.so.1",
    // Vulkan
    "libvulkan.so.1",
    // Wayland
    "libwayland-client.so.0",
    "libwayland-cursor.so.0",
    "libwayland-egl.so.1",
    "libdecor-0.so.0",
    // X11
    "libX11.so.6",
    "libxcb.so.1",
    "libxkbcommon.so.0",
    "libxkbcommon-x11.so.0",
    // Video acceleration
    "libva.so.2",
    "libva-drm.so.2",
    "libva-x11.so.2",
    "libva-wayland.so.2",
    // Audio
    "libpulse.so.0",
    "libasound.so.2",
    "libjack.so.0",
    // IPC / desktop
    "libdbus-1.so.3",
    // NVIDIA proprietary stack
    "libcuda.so.1",
    "libnvidia-ml.so.1",
    "libnvidia-encode.so.1",
    "libnvidia-fbc.so.1",
    // Fonts / text
    "libfontconfig.so.1",
    "libfreetype.so.6",
    "libharfbuzz.so.0",
];

/// Scan a binary's string table for soname-shaped values that match the
/// dlopen allow-list (built-in plus any user-supplied additions). Matches
/// are candidates for bundling even though they don't appear in DT_NEEDED.
fn scan_dlopen(path: &Path, extra: &[String]) -> io::Result<Vec<String>> {
    let data = fs::read(path)?;
    let mut found: Vec<String> = Vec::new();

    let mut start = None;
    for (i, &b) in data.iter().enumerate() {
        let printable = (0x20..=0x7e).contains(&b);
        if printable {
            if start.is_none() {
                start = Some(i);
            }
        } else if let Some(s) = start.take() {
            if i - s >= 5 {
                if let Ok(text) = std::str::from_utf8(&data[s..i]) {
                    let match_builtin = DLOPEN_CANDIDATES.iter().any(|c| *c == text);
                    let match_extra = extra.iter().any(|c| c == text);
                    if (match_builtin || match_extra) && !found.iter().any(|x| x == text) {
                        found.push(text.to_string());
                    }
                }
            }
        }
    }
    Ok(found)
}

fn parse_needed(path: &Path) -> io::Result<Vec<String>> {
    let data = fs::read(path)?;
    let elf = goblin::elf::Elf::parse(&data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
    // nixpkgs occasionally emits DT_NEEDED entries as absolute
    // `/nix/store/<hash>/lib/libfoo.so` paths rather than plain
    // sonames. Reduce those to their basename so our resolver can
    // find the lib on the host / search paths. `strip_absolute_needed`
    // rewrites the ELF's own DT_NEEDED string after bundling so the
    // runtime loader also picks up the bundled copy via RUNPATH.
    Ok(elf
        .libraries
        .iter()
        .map(|s| {
            if s.starts_with('/') {
                Path::new(s)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(s)
                    .to_string()
            } else {
                s.to_string()
            }
        })
        .collect())
}

/// Parse PT_INTERP from an ELF binary, returning the interpreter path.
///
/// goblin returns `p_filesz - 1` bytes verbatim, so a slot padded with
/// trailing NULs (common after our in-place PT_INTERP rewrite if the
/// phdr wasn't shrunk) would leak into callers as embedded NULs in
/// the returned string. Trim them so queue lookups and `file_name()`
/// behave correctly.
fn parse_interp(path: &Path) -> Option<String> {
    let data = fs::read(path).ok()?;
    let elf = goblin::elf::Elf::parse(&data).ok()?;
    elf.interpreter
        .map(|s| s.trim_end_matches('\0').to_string())
}

/// Map an ELF interpreter basename to the libc filename that serves it.
/// On musl, `ld-musl-<arch>.so.1` and `libc.musl-<arch>.so.1` are both
/// names for the same file. Returns None if no mapping is known.
fn libc_alias_for(interp_name: &str) -> Option<String> {
    interp_name
        .strip_prefix("ld-musl-")
        .map(|rest| format!("libc.musl-{rest}"))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LibcFamily {
    Musl,
    Glibc,
}

/// Detect a binary's libc family from its PT_INTERP basename.
fn libc_family_from_interp(interp: &str) -> Option<LibcFamily> {
    let name = Path::new(interp).file_name()?.to_str()?;
    if name.starts_with("ld-musl-") {
        Some(LibcFamily::Musl)
    } else if name.starts_with("ld-linux") {
        Some(LibcFamily::Glibc)
    } else {
        None
    }
}

/// Map a soname to the libc family it belongs to, when known.
fn libc_family_of_soname(soname: &str) -> Option<LibcFamily> {
    if soname == "libc.so.6" || soname.starts_with("ld-linux") {
        Some(LibcFamily::Glibc)
    } else if soname.starts_with("libc.musl-")
        || soname.starts_with("ld-musl-")
        || soname == "libc.so"
    {
        // libc.so is musl's canonical libc filename; libc.musl-*/ld-musl-* are aliases.
        Some(LibcFamily::Musl)
    } else {
        None
    }
}

/// Parse RPATH and RUNPATH entries from an ELF binary.
fn parse_rpaths(path: &Path) -> Vec<PathBuf> {
    let Ok(data) = fs::read(path) else {
        return Vec::new();
    };
    let Ok(elf) = goblin::elf::Elf::parse(&data) else {
        return Vec::new();
    };
    elf.runpaths
        .iter()
        .chain(elf.rpaths.iter())
        .map(|s| PathBuf::from(s))
        .filter(|p| p.is_absolute() && p.is_dir())
        .collect()
}

/// Rewrite RPATH/RUNPATH to `$ORIGIN/../lib` so the bundled ELF finds its
/// transitive libraries via its own on-disk location, never via
/// `LD_LIBRARY_PATH`. That matters because `LD_LIBRARY_PATH` is a
/// per-process env variable that gets inherited into host binaries the
/// app may spawn (for example, `postgres` uses `popen(3)` which execs
/// `/bin/sh` - a host binary linked against the host's glibc). If we
/// left our bundle dir on `LD_LIBRARY_PATH`, the host shell would load
/// our newer `libc.so.6` against its own older `ld-linux.so.2` and
/// crash with a null deref in the loader. Using `$ORIGIN/../lib` keeps
/// the bundle's library search scoped to the bundled ELF itself.
///
/// Only works when the ELF already has a DT_RPATH or DT_RUNPATH entry
/// we can reuse. Upstream Linux distros (including nixpkgs, Debian,
/// Fedora) compile most system binaries with one set, pointing at the
/// distro's own lib dir, so we almost always find a slot. Binaries
/// without any RPATH entry stay unmodified, which is fine because the
/// caller still sets `LD_LIBRARY_PATH` in the direct-ELF exec path as
/// a fallback.
fn set_origin_runpath(path: &Path) -> io::Result<()> {
    // Cover binaries at depth 1 (e.g. bin/foo), 2 (libexec/podman/x),
    // and 3 (share/pkg/helpers/y). Nonexistent entries are silently
    // ignored by the dynamic loader, so this is safe to apply
    // uniformly without knowing where each ELF sits.
    const NEW: &[u8] = b"$ORIGIN/../lib:$ORIGIN/../../lib:$ORIGIN/../../../lib";
    let data = fs::read(path)?;
    let elf = goblin::elf::Elf::parse(&data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

    // Find .dynstr section file offset
    let dynstr_offset = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
        .map(|sh| sh.sh_offset as usize);

    let Some(dynstr_offset) = dynstr_offset else {
        return Ok(());
    };

    let Some(dynamic) = &elf.dynamic else {
        return Ok(());
    };

    let mut modified = data;
    let mut changed = false;

    for dyn_entry in &dynamic.dyns {
        if dyn_entry.d_tag == goblin::elf::dynamic::DT_RPATH
            || dyn_entry.d_tag == goblin::elf::dynamic::DT_RUNPATH
        {
            let file_pos = dynstr_offset + dyn_entry.d_val as usize;
            if file_pos >= modified.len() {
                continue;
            }
            // Measure the writable slot size: the current string plus
            // any trailing NUL padding that follows it, up to the next
            // non-NUL byte. That covers three cases:
            //   (a) fresh ELF: the slot is exactly string + NUL.
            //   (b) an older onelf pass already zeroed the string: no
            //       leading content, just a run of NULs.
            //   (c) an older onelf pass wrote a *shorter* replacement
            //       (e.g. `$ORIGIN/../lib`): leading string, then a
            //       NUL run up to where the next .dynstr entry starts.
            //   We need (c) to grow the slot back beyond our earlier
            //   shorter write so a longer replacement still fits.
            let mut end = file_pos;
            while end < modified.len() && modified[end] != 0 {
                end += 1;
            }
            while end < modified.len() && modified[end] == 0 {
                end += 1;
            }
            let slot_size = end - file_pos;
            if NEW.len() + 1 > slot_size {
                // Not enough room to fit NEW plus a NUL terminator. The
                // caller will still fall back to LD_LIBRARY_PATH for ELF
                // entrypoints in the direct-exec path, so this isn't
                // fatal - just less robust.
                continue;
            }
            modified[file_pos..file_pos + NEW.len()].copy_from_slice(NEW);
            for i in NEW.len()..slot_size {
                modified[file_pos + i] = 0;
            }
            changed = true;
        }
    }

    if changed {
        fs::write(path, &modified)?;
    }
    Ok(())
}

/// Rewrite any absolute-path DT_NEEDED entry to just its basename. The
/// pack host's nixpkgs stack sometimes emits a full
/// `/nix/store/<hash>-name/lib/libfoo.so` as the DT_NEEDED string. The
/// dynamic loader treats those literally and ignores `RUNPATH` /
/// `LD_LIBRARY_PATH`, so a binary built with them will try to `open`
/// that exact path on the user's machine and fail. Stripping to the
/// basename puts the lookup back on the standard search path and
/// picks up our bundled copy via `$ORIGIN/../lib`.
///
/// Operates in place: writes the new basename over the old string and
/// NUL-pads the rest of the slot. The old slot is always longer than
/// the new basename, so this never needs to grow the string table.
fn strip_absolute_needed(path: &Path) -> io::Result<()> {
    let data = fs::read(path)?;
    let elf = goblin::elf::Elf::parse(&data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

    let dynstr_offset = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
        .map(|sh| sh.sh_offset as usize);
    let Some(dynstr_offset) = dynstr_offset else {
        return Ok(());
    };
    let Some(dynamic) = &elf.dynamic else {
        return Ok(());
    };

    let mut modified = data;
    let mut changed = false;

    for dyn_entry in &dynamic.dyns {
        if dyn_entry.d_tag != goblin::elf::dynamic::DT_NEEDED {
            continue;
        }
        let file_pos = dynstr_offset + dyn_entry.d_val as usize;
        if file_pos >= modified.len() || modified[file_pos] != b'/' {
            continue;
        }
        // Read the current (absolute) path from the string table.
        let mut end = file_pos;
        while end < modified.len() && modified[end] != 0 {
            end += 1;
        }
        let original = &modified[file_pos..end];
        let slot_size = end - file_pos;

        let basename_start = match original.iter().rposition(|&b| b == b'/') {
            Some(p) => p + 1,
            None => 0,
        };
        let basename_len = original.len() - basename_start;
        if basename_len == 0 || basename_len >= slot_size {
            continue;
        }

        let basename: Vec<u8> = original[basename_start..].to_vec();
        modified[file_pos..file_pos + basename_len].copy_from_slice(&basename);
        for i in basename_len..slot_size {
            modified[file_pos + i] = 0;
        }
        changed = true;
    }

    if changed {
        fs::write(path, &modified)?;
    }
    Ok(())
}

fn is_excluded(soname: &str, excludes: &[&str]) -> bool {
    excludes.iter().any(|pat| soname.starts_with(pat))
}

/// True for sonames that denote the dynamic linker itself.
fn is_dynamic_loader(soname: &str) -> bool {
    soname.starts_with("ld-linux") || soname.starts_with("ld-musl-") || soname == "ld.so"
}

/// Rewrite absolute-path byte sequences baked into the dynamic loader.
///
/// glibc's `ld-linux` hardcodes its build-time `/etc/ld.so.cache`,
/// `/etc/ld-nix.so.preload`, `/nix/store/<hash>-glibc-X/lib/`, and a
/// few other absolute paths. Those exist on the packer's machine but
/// not on the user's; worse, if any do exist, they'll point at a
/// libc that disagrees with the one we bundled. The fix is to replace
/// each prefix with a path that is guaranteed not to resolve (starts
/// with `/XXX`), keeping byte length identical so ELF offsets stay
/// valid.
///
/// This is the same idea as sharun's `sed` pass, done in pure Rust
/// with a more targeted prefix list.
fn scrub_loader_paths(path: &Path) -> io::Result<()> {
    let mut data = fs::read(path)?;
    let mut changed = false;
    // Each pattern and replacement are equal length to avoid any ELF
    // structure shifts. Replacements are paths that simply don't exist
    // on any sane system.
    let replacements: &[(&[u8], &[u8])] = &[
        (b"/etc/", b"/XXX/"),
        (b"/usr/", b"/XXX/"),
        (b"/nix/", b"/XXX/"),
        // /lib/ and /lib64/ appear as glibc's hardcoded fallback
        // library search paths. Our bundled libs live in `lib/` (no
        // leading slash), so scrubbing absolute /lib doesn't hurt.
        (b"/lib/", b"/XXX/"),
        (b"/lib64/", b"/XXX///"),
    ];

    for (needle, replace) in replacements {
        debug_assert_eq!(needle.len(), replace.len());
        let len = needle.len();
        let mut i = 0;
        while i + len <= data.len() {
            if &data[i..i + len] == *needle {
                data[i..i + len].copy_from_slice(replace);
                changed = true;
                i += len;
            } else {
                i += 1;
            }
        }
    }

    if changed {
        fs::write(path, &data)?;
    }
    Ok(())
}

/// Rewrite specific `/nix/store/<hash>-<name>-<version>/...` strings
/// baked into a bundled ELF with sensible host equivalents. Called for
/// every bundled non-loader ELF, not just the loader.
///
/// nixpkgs typically compiles postgres with `--with-system-tzdata=<store>`
/// and embeds the full path to the `locale` binary it will shell out
/// to. Both paths exist only on the packer's machine. On the user's
/// machine postgres prints a parade of warnings about the missing
/// directory, then falls back to internal UTC-only behavior and
/// still-functional locale defaults. The bundle still works, but the
/// noise is confusing.
///
/// Replacements are equal-length to avoid any ELF structure shifts,
/// with the replacement null-padded to the original slot size. We
/// target the suffix (e.g. `/share/zoneinfo`, `/bin/locale`) and walk
/// back to the nearest NUL to find the start of the whole path
/// string.
fn scrub_nix_store_paths(path: &Path) -> io::Result<()> {
    let mut data = fs::read(path)?;
    let mut changed = false;

    // (suffix to find, replacement path, friendly name)
    let rewrites: &[(&[u8], &[u8])] = &[
        (b"/share/zoneinfo", b"/usr/share/zoneinfo"),
        (b"/bin/locale", b"/usr/bin/locale"),
    ];

    for (suffix, replacement) in rewrites {
        let mut i = 0;
        while i + suffix.len() <= data.len() {
            if &data[i..i + suffix.len()] != *suffix {
                i += 1;
                continue;
            }
            // Walk back to find the start of this C string.
            let mut start = i;
            while start > 0 && data[start - 1] != 0 {
                start -= 1;
            }
            // Only touch strings rooted in /nix/store/.
            if start + 11 > data.len() || &data[start..start + 11] != b"/nix/store/" {
                i = i + suffix.len();
                continue;
            }
            // Find end of string: walk forward to the NUL.
            let mut end = i + suffix.len();
            while end < data.len() && data[end] != 0 {
                end += 1;
            }
            let slot = end - start;
            if replacement.len() + 1 > slot {
                // Shouldn't happen for these specific replacements,
                // but guard just in case.
                i = end;
                continue;
            }
            data[start..start + replacement.len()].copy_from_slice(replacement);
            for b in &mut data[start + replacement.len()..end] {
                *b = 0;
            }
            changed = true;
            i = end;
        }
    }

    if changed {
        fs::write(path, &data)?;
    }
    Ok(())
}

/// Rewrite PT_INTERP of an ELF in place.
///
/// Fast path: if the new string fits in the existing slot
/// (`p_offset..p_offset+p_filesz`), overwrite and null-pad.
/// Slow path: append the new string to the end of the file and
/// rewrite the PT_INTERP program header's `p_offset`, `p_filesz`,
/// and `p_memsz` to point at it. Kernel reads PT_INTERP directly
/// from the file (no PT_LOAD coverage required) so appending bytes
/// past the last segment is safe.
///
/// Returns `Ok(true)` if we rewrote, `Ok(false)` if the file has no
/// PT_INTERP or the new value already matches.
fn patch_interp(path: &Path, new_interp: &str) -> io::Result<bool> {
    let data = fs::read(path)?;
    let elf = goblin::elf::Elf::parse(&data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

    let phdr_idx = elf
        .program_headers
        .iter()
        .position(|p| p.p_type == goblin::elf::program_header::PT_INTERP);
    let Some(phdr_idx) = phdr_idx else {
        return Ok(false);
    };
    let ph = &elf.program_headers[phdr_idx];

    let offset = ph.p_offset as usize;
    let slot = ph.p_filesz as usize;
    if offset + slot > data.len() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "PT_INTERP offset out of file bounds",
        ));
    }

    let new_bytes = new_interp.as_bytes();

    // Short-circuit if the slot already holds the desired string.
    let existing = &data[offset..offset + slot];
    let existing_str = match existing.iter().position(|&b| b == 0) {
        Some(n) => &existing[..n],
        None => existing,
    };
    if existing_str == new_bytes {
        return Ok(false);
    }

    let header = elf.header;
    drop(elf);

    if new_bytes.len() + 1 <= slot {
        // Fast path: overwrite in place and shrink p_filesz / p_memsz to
        // match the actual string. If we don't, tools that read
        // p_filesz bytes (including goblin and readelf) will see the
        // trailing NULs as part of the string.
        let mut modified = data;
        modified[offset..offset + new_bytes.len()].copy_from_slice(new_bytes);
        for b in &mut modified[offset + new_bytes.len()..offset + slot] {
            *b = 0;
        }
        rewrite_interp_phdr(
            &mut modified,
            &header,
            phdr_idx,
            offset as u64,
            (new_bytes.len() + 1) as u64,
        )?;
        fs::write(path, &modified)?;
        return Ok(true);
    }

    // Slow path: append the new interp to the end of the file and
    // rewrite the PT_INTERP phdr to point at it.
    patch_interp_expand(path, data, &header, phdr_idx, new_bytes)?;
    Ok(true)
}

/// Write `p_offset` and matching `p_filesz`/`p_memsz` back into the
/// PT_INTERP program header entry. The caller is responsible for
/// ensuring the string bytes (and terminating NUL) are already in the
/// file at the given offset.
fn rewrite_interp_phdr(
    data: &mut [u8],
    header: &goblin::elf::Header,
    phdr_idx: usize,
    new_offset: u64,
    new_size: u64,
) -> io::Result<()> {
    use goblin::elf::header;

    let is_64 = header.e_ident[header::EI_CLASS] == header::ELFCLASS64;
    if header.e_ident[header::EI_DATA] != header::ELFDATA2LSB {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "big-endian ELF PT_INTERP rewrite not implemented",
        ));
    }

    let e_phoff = header.e_phoff as usize;
    let e_phentsize = header.e_phentsize as usize;
    let phdr_off = e_phoff + phdr_idx * e_phentsize;
    if phdr_off + e_phentsize > data.len() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "program header table out of bounds",
        ));
    }

    if is_64 {
        let off_p_offset = phdr_off + 8;
        let off_p_filesz = phdr_off + 32;
        let off_p_memsz = phdr_off + 40;
        data[off_p_offset..off_p_offset + 8].copy_from_slice(&new_offset.to_le_bytes());
        data[off_p_filesz..off_p_filesz + 8].copy_from_slice(&new_size.to_le_bytes());
        data[off_p_memsz..off_p_memsz + 8].copy_from_slice(&new_size.to_le_bytes());
    } else {
        let off_p_offset = phdr_off + 4;
        let off_p_filesz = phdr_off + 16;
        let off_p_memsz = phdr_off + 20;
        let new_offset_u32: u32 = new_offset
            .try_into()
            .map_err(|_| io::Error::other("PT_INTERP offset does not fit in 32 bits"))?;
        let new_size_u32: u32 = new_size
            .try_into()
            .map_err(|_| io::Error::other("PT_INTERP size does not fit in 32 bits"))?;
        data[off_p_offset..off_p_offset + 4].copy_from_slice(&new_offset_u32.to_le_bytes());
        data[off_p_filesz..off_p_filesz + 4].copy_from_slice(&new_size_u32.to_le_bytes());
        data[off_p_memsz..off_p_memsz + 4].copy_from_slice(&new_size_u32.to_le_bytes());
    }
    Ok(())
}

/// Append `new_bytes` + NUL to the file and rewrite PT_INTERP's phdr
/// entry so `p_offset` points at the new location and `p_filesz` /
/// `p_memsz` cover the new length. Kernel reads PT_INTERP by file
/// offset, so the string does not need to live inside any PT_LOAD.
fn patch_interp_expand(
    path: &Path,
    data: Vec<u8>,
    header: &goblin::elf::Header,
    phdr_idx: usize,
    new_bytes: &[u8],
) -> io::Result<()> {
    let mut modified = data;
    let new_offset = modified.len() as u64;
    modified.extend_from_slice(new_bytes);
    modified.push(0);

    rewrite_interp_phdr(
        &mut modified,
        header,
        phdr_idx,
        new_offset,
        (new_bytes.len() + 1) as u64,
    )?;
    fs::write(path, &modified)?;
    Ok(())
}

/// Walk every ELF under `app_dir` and rewrite PT_INTERP to a path
/// relative to `app_dir` that resolves to the bundled loader copy.
///
/// Requires the caller (runtime / `onelf run`) to chdir into `app_dir`
/// before execing the target so the kernel resolves the relative
/// PT_INTERP correctly. Returns the count of patched files.
fn patch_interps_to_bundled(app_dir: &Path, lib_dest: &Path) -> io::Result<usize> {
    let rel_lib = lib_dest
        .strip_prefix(app_dir)
        .unwrap_or(lib_dest)
        .to_path_buf();

    let mut patched = 0usize;
    for path in find_elf_files(app_dir) {
        let Some(interp) = parse_interp(&path) else {
            continue;
        };
        let Some(basename) = Path::new(&interp).file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        // Only patch when we actually have a bundled replacement.
        let bundled = lib_dest.join(basename);
        if !bundled.exists() {
            continue;
        }

        // The runtime and `onelf run` always chdir to the AppDir root
        // before exec (so a single relative PT_INTERP works for every
        // binary regardless of subdirectory). Build the path as it
        // resolves from that CWD: `lib/<basename>`.
        if path.strip_prefix(app_dir).is_err() {
            continue;
        }
        let new_interp = rel_lib
            .join(basename)
            .to_string_lossy()
            .into_owned();

        // ELF files may be read-only (e.g. copied with `fs::copy` from
        // a read-only source). Make writable before patching, restore after.
        let perms = fs::metadata(&path)
            .map(|m| m.permissions().mode())
            .unwrap_or(0o755);
        let needs_chmod = perms & 0o200 == 0;
        if needs_chmod {
            let _ = fs::set_permissions(
                &path,
                std::os::unix::fs::PermissionsExt::from_mode(perms | 0o200),
            );
        }
        match patch_interp(&path, &new_interp) {
            Ok(true) => patched += 1,
            Ok(false) => {}
            Err(e) => {
                eprintln!(
                    "  {} could not patch PT_INTERP of {}: {e}",
                    color::bold_red("warning:"),
                    path.display()
                );
            }
        }
        if needs_chmod {
            let _ =
                fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(perms));
        }
    }
    Ok(patched)
}

fn find_existing_libs(dir: &Path) -> HashSet<String> {
    let mut libs = HashSet::new();
    for entry in jwalk::WalkDir::new(dir).skip_hidden(false) {
        let Ok(entry) = entry else { continue };
        let path = entry.path();
        let Some(name) = path.file_name() else {
            continue;
        };
        let name = name.to_string_lossy();
        if !name.contains(".so") {
            continue;
        }
        // A previous run may have copied NixOS's stub loader into the
        // bundle. Treat it as absent so it gets replaced with a real
        // loader on this pass; otherwise the stale stub would persist
        // forever.
        if is_nix_stub_ld(&path) {
            let _ = fs::remove_file(&path);
            continue;
        }
        libs.insert(name.into_owned());
    }
    libs
}

fn build_lib_cache() -> HashMap<String, Vec<PathBuf>> {
    let cache = parse_ldconfig_cache();
    if !cache.is_empty() {
        return cache;
    }

    // Fallback: on NixOS, ldconfig has no cache. Scan the system closure instead.
    if Path::new("/nix/store").is_dir() {
        return scan_nix_store_libs();
    }

    cache
}

fn parse_ldconfig_cache() -> HashMap<String, Vec<PathBuf>> {
    let mut cache: HashMap<String, Vec<PathBuf>> = HashMap::new();
    let Ok(output) = Command::new("ldconfig").arg("-p").output() else {
        return cache;
    };
    // Lines like: "	libX11.so.6 (libc6,x86-64) => /usr/lib/libX11.so.6"
    for line in output.stdout.lines().map_while(Result::ok) {
        let line = line.trim();
        if let Some((left, right)) = line.split_once(" => ") {
            let soname = left.split_whitespace().next().unwrap_or("");
            if !soname.is_empty() {
                cache
                    .entry(soname.to_string())
                    .or_default()
                    .push(PathBuf::from(right.trim()));
            }
        }
    }
    cache
}

/// Scan lib/ directories from NixOS closures to build a soname map.
/// Scans the system closure, user profile, and home-manager profile.
fn scan_nix_store_libs() -> HashMap<String, Vec<PathBuf>> {
    let mut cache: HashMap<String, Vec<PathBuf>> = HashMap::new();
    let mut store_paths: HashSet<String> = HashSet::new();

    // Collect store paths from multiple roots
    let roots: Vec<&str> = vec![
        "/run/current-system",
        "~/.nix-profile",
        "/etc/profiles/per-user",
    ];

    for root in &roots {
        let expanded = if root.starts_with('~') {
            if let Ok(home) = std::env::var("HOME") {
                root.replacen('~', &home, 1)
            } else {
                continue;
            }
        } else {
            root.to_string()
        };

        if !Path::new(&expanded).exists() {
            continue;
        }

        let Ok(output) = Command::new("nix-store").args(["-qR", &expanded]).output() else {
            continue;
        };

        if output.status.success() {
            for line in output.stdout.lines().map_while(Result::ok) {
                store_paths.insert(line.trim().to_string());
            }
        }
    }

    if store_paths.is_empty() {
        return cache;
    }

    let lib_dirs: Vec<PathBuf> = store_paths
        .iter()
        .map(|p| PathBuf::from(p).join("lib"))
        .filter(|p| p.is_dir())
        .collect();

    eprintln!(
        "{} scanning {} store paths...",
        color::dim("NixOS detected,"),
        lib_dirs.len()
    );

    for lib_dir in &lib_dirs {
        for entry in jwalk::WalkDir::new(lib_dir).max_depth(3).skip_hidden(false) {
            let Ok(entry) = entry else { continue };
            if !entry.file_type().is_file() {
                continue;
            }
            if let Some(name) = entry.path().file_name() {
                let name = name.to_string_lossy();
                if name.contains(".so") {
                    cache
                        .entry(name.into_owned())
                        .or_default()
                        .push(entry.path());
                }
            }
        }
    }

    cache
}

/// Extract the nix store path from a full path.
/// e.g. /nix/store/HASH-name/lib/foo.so -> /nix/store/HASH-name
fn nix_store_path(path: &Path) -> Option<PathBuf> {
    let s = path.to_string_lossy();
    let rest = s.strip_prefix("/nix/store/")?;
    let end = rest.find('/').unwrap_or(rest.len());
    Some(PathBuf::from(format!("/nix/store/{}", &rest[..end])))
}

/// When a lib is resolved from the nix store, scan its store path's closure
/// to discover transitive dependencies that may not be in the initial scan set.
/// Tracks already-expanded store paths to avoid redundant work.
fn expand_nix_cache(
    resolved: &Path,
    cache: &mut HashMap<String, Vec<PathBuf>>,
    expanded: &mut HashSet<PathBuf>,
) {
    let store_path = match nix_store_path(resolved) {
        Some(p) => p,
        None => return,
    };

    if !expanded.insert(store_path.clone()) {
        return; // already expanded this store path
    }

    let Ok(output) = Command::new("nix-store")
        .args(["-qR"])
        .arg(&store_path)
        .output()
    else {
        return;
    };

    if !output.status.success() {
        return;
    }

    for line in output.stdout.lines().map_while(Result::ok) {
        let lib_dir = PathBuf::from(line.trim()).join("lib");
        if !lib_dir.is_dir() {
            continue;
        }
        for entry in jwalk::WalkDir::new(&lib_dir)
            .max_depth(3)
            .skip_hidden(false)
        {
            let Ok(entry) = entry else { continue };
            if !entry.file_type().is_file() {
                continue;
            }
            if let Some(name) = entry.path().file_name() {
                let name = name.to_string_lossy();
                if name.contains(".so") {
                    let paths = cache.entry(name.into_owned()).or_default();
                    let path = entry.path();
                    if !paths.contains(&path) {
                        paths.push(path);
                    }
                }
            }
        }
    }
}

fn locate_lib(
    soname: &str,
    ldconfig_cache: &HashMap<String, Vec<PathBuf>>,
    search_paths: &[PathBuf],
    target_class: Option<u8>,
) -> Option<PathBuf> {
    let class_matches = |path: &Path| -> bool {
        match target_class {
            Some(tc) => read_elf_class(path) == Some(tc),
            None => true,
        }
    };
    // Reject NixOS's stub loader anywhere it surfaces. It exists on disk
    // but refuses to actually load foreign binaries, so bundling it would
    // produce a package that runs nowhere.
    let acceptable = |path: &Path| class_matches(path) && !is_nix_stub_ld(path);

    // 1. --search-path directories (user-provided: highest priority)
    for dir in search_paths {
        let candidate = dir.join(soname);
        if candidate.exists() && acceptable(&candidate) {
            return Some(candidate);
        }
    }

    // 2. ldconfig cache
    if let Some(paths) = ldconfig_cache.get(soname) {
        for path in paths {
            if path.exists() && acceptable(path) {
                return Some(path.clone());
            }
        }
    }

    // 3. Standard paths
    for dir in STANDARD_LIB_PATHS {
        let candidate = Path::new(dir).join(soname);
        if candidate.exists() && acceptable(&candidate) {
            return Some(candidate);
        }
    }

    // 4. LD_LIBRARY_PATH and NIX_LD_LIBRARY_PATH
    for var in ["LD_LIBRARY_PATH", "NIX_LD_LIBRARY_PATH"] {
        if let Ok(val) = std::env::var(var) {
            for dir in val.split(':') {
                if dir.is_empty() {
                    continue;
                }
                let candidate = Path::new(dir).join(soname);
                if candidate.exists() && acceptable(&candidate) {
                    return Some(candidate);
                }
            }
        }
    }

    // 5. NixOS fallback: scan /nix/store/*/lib/ directly
    if Path::new("/nix/store").is_dir() {
        if let Ok(entries) = fs::read_dir("/nix/store") {
            for entry in entries.filter_map(Result::ok) {
                let lib_dir = entry.path().join("lib");
                // Check lib/<soname> directly
                let candidate = lib_dir.join(soname);
                if candidate.exists() && acceptable(&candidate) {
                    return Some(candidate);
                }
                // Also check one level of subdirs (e.g. lib/pulseaudio/)
                if let Ok(subdirs) = fs::read_dir(&lib_dir) {
                    for subdir in subdirs.filter_map(Result::ok) {
                        if subdir.file_type().map_or(false, |t| t.is_dir()) {
                            let candidate = subdir.path().join(soname);
                            if candidate.exists() && acceptable(&candidate) {
                                return Some(candidate);
                            }
                        }
                    }
                }
            }
        }
    }

    None
}

/// Detect NixOS's stub-ld, a tiny loader that prints a message and exits.
/// The stub lives at `/lib*/ld-*` on NixOS when nix-ld isn't enabled.
/// We check two signals:
///
/// 1. The canonical path contains `stub-ld` (covers the fresh symlink case).
/// 2. The file content contains NixOS's signature error string (covers the
///    case where a previous bundle copied the stub into the AppDir itself,
///    so canonicalize no longer points at the nix store).
fn is_nix_stub_ld(path: &Path) -> bool {
    if let Ok(real) = fs::canonicalize(path) {
        if real.to_string_lossy().contains("stub-ld") {
            return true;
        }
    }
    // Real glibc ld-linux is >100 KB; the stub is ~35 KB. Cheap filter
    // before hashing through the file content.
    let Ok(meta) = fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() || meta.len() > 128 * 1024 {
        return false;
    }
    let Ok(bytes) = fs::read(path) else {
        return false;
    };
    bytes
        .windows(b"NixOS cannot run".len())
        .any(|w| w == b"NixOS cannot run")
}

// ---------------------------------------------------------------------------
// GPU asset bundling
// ---------------------------------------------------------------------------

const DRI_SEARCH_PATHS: &[&str] = &[
    "/usr/lib/dri",
    "/usr/lib64/dri",
    "/usr/lib/x86_64-linux-gnu/dri",
];

const GBM_SEARCH_PATHS: &[&str] = &[
    "/usr/lib/gbm",
    "/usr/lib64/gbm",
    "/usr/lib/x86_64-linux-gnu/gbm",
];

const EGL_SEARCH_PATHS: &[&str] = &["/usr/share/glvnd/egl_vendor.d"];

const VK_SEARCH_PATHS: &[&str] = &["/usr/share/vulkan/icd.d", "/etc/vulkan/icd.d"];

/// Bundle GPU drivers and vendor configs so OpenGL/Vulkan/EGL apps work portably.
fn bundle_gpu(
    directory: &Path,
    lib_dir: &Path,
    extra_search: &[PathBuf],
    dry_run: bool,
    strip: bool,
    include_gl: bool,
    include_dri: bool,
    include_vulkan: bool,
) -> io::Result<()> {
    eprintln!("{} GPU drivers...", color::bold("Bundling"));

    let elf_files = find_elf_files(directory);

    // Determine target ELF class and machine type from existing binaries
    let target_class = elf_files.iter().find_map(|f| read_elf_class(f));
    let target_machine = elf_files.iter().find_map(|f| read_elf_machine(f));

    // Collect RPATH dirs from the app binaries. These point to the exact
    // library versions the app was built against. On NixOS this ensures we
    // pick DRI drivers from the same Mesa as the bundled libGL.so.
    let mut rpath_dri: Vec<PathBuf> = Vec::new();
    let mut rpath_gbm: Vec<PathBuf> = Vec::new();
    let mut rpath_egl: Vec<PathBuf> = Vec::new();
    let mut rpath_vk: Vec<PathBuf> = Vec::new();
    for elf in &elf_files {
        for rdir in parse_rpaths(elf) {
            let dri = rdir.join("dri");
            if dri.is_dir() && !rpath_dri.contains(&dri) {
                rpath_dri.push(dri);
            }
            let gbm = rdir.join("gbm");
            if gbm.is_dir() && !rpath_gbm.contains(&gbm) {
                rpath_gbm.push(gbm);
            }
            // EGL/Vulkan configs are in share/, which is a sibling of lib/
            if let Some(parent) = rdir.parent() {
                let egl = parent.join("share/glvnd/egl_vendor.d");
                if egl.is_dir() && !rpath_egl.contains(&egl) {
                    rpath_egl.push(egl);
                }
                let vk = parent.join("share/vulkan/icd.d");
                if vk.is_dir() && !rpath_vk.contains(&vk) {
                    rpath_vk.push(vk);
                }
            }
        }
    }

    // RPATH-derived dirs go first so they win over system/store-wide scan.
    // This ensures DRI drivers match the Mesa version the app links against.
    let mut dri_dirs = rpath_dri;
    let mut gbm_dirs = rpath_gbm;
    let mut egl_dirs = rpath_egl;
    let mut vk_dirs = rpath_vk;

    // Then standard system paths
    dri_dirs.extend(DRI_SEARCH_PATHS.iter().map(PathBuf::from));
    gbm_dirs.extend(GBM_SEARCH_PATHS.iter().map(PathBuf::from));
    egl_dirs.extend(EGL_SEARCH_PATHS.iter().map(PathBuf::from));
    vk_dirs.extend(VK_SEARCH_PATHS.iter().map(PathBuf::from));

    // Add extra search paths with dri/ and gbm/ subdirs
    for dir in extra_search {
        let dri = dir.join("dri");
        if dri.is_dir() && !dri_dirs.contains(&dri) {
            dri_dirs.push(dri);
        }
        let gbm = dir.join("gbm");
        if gbm.is_dir() && !gbm_dirs.contains(&gbm) {
            gbm_dirs.push(gbm);
        }
    }

    // NixOS: scan store closures for GPU asset directories (lowest priority)
    let store_paths = if Path::new("/nix/store").is_dir() {
        collect_nix_store_paths()
    } else {
        Vec::new()
    };
    if !store_paths.is_empty() {
        for sp in &store_paths {
            let sp = PathBuf::from(sp);
            let dri = sp.join("lib/dri");
            if dri.is_dir() && !dri_dirs.contains(&dri) {
                dri_dirs.push(dri);
            }
            let gbm = sp.join("lib/gbm");
            if gbm.is_dir() && !gbm_dirs.contains(&gbm) {
                gbm_dirs.push(gbm);
            }
            let egl = sp.join("share/glvnd/egl_vendor.d");
            if egl.is_dir() && !egl_dirs.contains(&egl) {
                egl_dirs.push(egl);
            }
            let vk = sp.join("share/vulkan/icd.d");
            if vk.is_dir() && !vk_dirs.contains(&vk) {
                vk_dirs.push(vk);
            }
        }
    }

    let lib_dest = directory.join(lib_dir);

    // Collect lib directories that contain DRI drivers - these are the Mesa
    // installation directories. We pull implementation libraries from them.
    let mesa_lib_dirs: Vec<PathBuf> = dri_dirs
        .iter()
        .filter_map(|dri_path| {
            // dri_path is e.g. /nix/store/HASH-mesa/lib/dri -> parent is lib/
            let parent = dri_path.parent()?;
            if parent.is_dir() {
                Some(parent.to_path_buf())
            } else {
                None
            }
        })
        .collect();

    // Search dirs for Mesa impl + glvnd dispatch libs.
    // mesa_lib_dirs first (version-matched), then RPATHs, system paths,
    // NixOS store, and extra dirs so glvnd from a separate package is found.
    let mut gl_search_dirs = mesa_lib_dirs.clone();
    for dir in build_lib_search_dirs(&elf_files, extra_search, &store_paths) {
        if !gl_search_dirs.contains(&dir) {
            gl_search_dirs.push(dir);
        }
    }

    let mut gpu_total_bytes = 0u64;

    // 0. Remove conflicting GL libraries shipped by the application (e.g.
    //    old monolithic Mesa libGL.so in a subdirectory) so they don't shadow
    //    the glvnd versions we're about to copy.
    if include_gl {
        remove_conflicting_gl_libs(directory, &lib_dest, dry_run);
    }

    // 1. Mesa implementation + glvnd dispatch libraries
    let mut mesa_count = 0;
    if include_gl {
        let all_gl: Vec<&str> = MESA_IMPL_PREFIXES
            .iter()
            .chain(GLVND_PREFIXES.iter())
            .copied()
            .collect();
        let (count, bytes) = copy_prefixed_libs(
            &gl_search_dirs,
            &all_gl,
            &lib_dest,
            target_class,
            dry_run,
            strip,
        )?;
        mesa_count = count;
        gpu_total_bytes += bytes;
        if count > 0 {
            eprintln!(
                "  {} {} Mesa/glvnd lib(s) ({})",
                verb_str(dry_run),
                count,
                format_size(bytes)
            );
        }
    }

    // 2. DRI drivers (only with --dri)
    let mut dri_count = 0;
    if include_dri {
        let dri_filter = driver_filter(target_machine, DRI_DRIVERS_X86, DRI_DRIVERS_ARM);
        let dri_dest = lib_dest.join("dri");
        let (count, bytes) = copy_so_dir(
            &dri_dirs,
            &dri_dest,
            target_class,
            dri_filter,
            dry_run,
            strip,
        )?;
        dri_count = count;
        gpu_total_bytes += bytes;
        if count > 0 {
            eprintln!(
                "  {} {} DRI driver(s) ({})",
                verb_str(dry_run),
                count,
                format_size(bytes)
            );
        }
    }

    // 3. GBM backends (with --gl)
    let mut gbm_count = 0;
    if include_gl {
        let gbm_dest = lib_dest.join("gbm");
        let (count, bytes) = copy_so_dir(&gbm_dirs, &gbm_dest, target_class, None, dry_run, strip)?;
        gbm_count = count;
        gpu_total_bytes += bytes;
        if count > 0 {
            eprintln!(
                "  {} {} GBM backend(s) ({})",
                verb_str(dry_run),
                count,
                format_size(bytes)
            );
        }
    }

    // 4. EGL vendor configs (with --gl)
    let mut egl_count = 0;
    if include_gl {
        let egl_dest = directory.join("share/glvnd/egl_vendor.d");
        let (count, bytes) =
            copy_vendor_json(&egl_dirs, &egl_dest, &lib_dest, target_class, None, dry_run)?;
        egl_count = count;
        gpu_total_bytes += bytes;
        if count > 0 {
            eprintln!(
                "  {} {} EGL vendor config(s) ({})",
                verb_str(dry_run),
                count,
                format_size(bytes)
            );
        }
    }

    // 5. Vulkan ICD configs (only with --vulkan)
    let mut vk_count = 0;
    if include_vulkan {
        let vk_filter = driver_filter(target_machine, VULKAN_DRIVERS_X86, VULKAN_DRIVERS_ARM);
        let vk_dest = directory.join("share/vulkan/icd.d");
        let (count, bytes) = copy_vendor_json(
            &vk_dirs,
            &vk_dest,
            &lib_dest,
            target_class,
            vk_filter,
            dry_run,
        )?;
        vk_count = count;
        gpu_total_bytes += bytes;
        if count > 0 {
            eprintln!(
                "  {} {} Vulkan ICD config(s) ({})",
                verb_str(dry_run),
                count,
                format_size(bytes)
            );
        }
    }

    // 6. Mesa data files (drirc.d configs and libdrm GPU tables)
    let mut data_count = 0u64;
    if include_gl || include_dri {
        // Find Mesa share directories from the same paths we found DRI drivers
        let share_dirs: Vec<PathBuf> = mesa_lib_dirs
            .iter()
            .filter_map(|lib_dir| {
                // lib_dir is e.g. /nix/store/HASH-mesa/lib -> parent has share/
                lib_dir.parent().map(|p| p.join("share"))
            })
            .filter(|p| p.is_dir())
            .collect();

        // Also check standard system paths
        let mut all_share = share_dirs;
        for path in &["/usr/share", "/usr/local/share"] {
            let p = PathBuf::from(path);
            if p.is_dir() && !all_share.contains(&p) {
                all_share.push(p);
            }
        }

        // Copy drirc.d/
        for share in &all_share {
            let drirc = share.join("drirc.d");
            if drirc.is_dir() {
                let dest = directory.join("share/drirc.d");
                let count = copy_data_dir(&drirc, &dest, dry_run)?;
                data_count += count;
                if count > 0 {
                    break;
                }
            }
        }

        // Copy libdrm/
        for share in &all_share {
            let libdrm = share.join("libdrm");
            if libdrm.is_dir() {
                let dest = directory.join("share/libdrm");
                let count = copy_data_dir(&libdrm, &dest, dry_run)?;
                data_count += count;
                if count > 0 {
                    break;
                }
            }
        }

        if data_count > 0 {
            eprintln!("  {} {} Mesa data file(s)", verb_str(dry_run), data_count);
        }
    }

    let total_count =
        mesa_count + dri_count + gbm_count + egl_count + vk_count + data_count as usize;
    if total_count == 0 {
        eprintln!(
            "  {} no GPU assets found on this system",
            color::bold_red("warning:")
        );
    } else if gpu_total_bytes > 0 {
        eprintln!(
            "  {} {}",
            color::bold("GPU total:"),
            format_size(gpu_total_bytes)
        );
    }

    Ok(())
}

/// Copy `.so` files from source directories into `dest`, filtering by ELF class
/// and optionally by an architecture-specific name allowlist.
/// Returns (files_copied, total_bytes).
fn copy_so_dir(
    src_dirs: &[PathBuf],
    dest: &Path,
    target_class: Option<u8>,
    name_filter: Option<&[&str]>,
    dry_run: bool,
    strip: bool,
) -> io::Result<(usize, u64)> {
    let mut copied = 0usize;
    let mut total_bytes = 0u64;
    let mut seen: HashSet<String> = HashSet::new();

    for dir in src_dirs {
        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            let name = match path.file_name() {
                Some(n) => n.to_string_lossy().into_owned(),
                None => continue,
            };
            if !name.contains(".so") {
                continue;
            }
            // Architecture-specific driver filter
            if let Some(allowed) = name_filter {
                if !allowed.iter().any(|a| name.starts_with(a)) {
                    continue;
                }
            }
            // Skip if we already have this filename from an earlier directory
            if !seen.insert(name.clone()) {
                continue;
            }
            // ELF class filter
            if let Some(tc) = target_class {
                if read_elf_class(&path) != Some(tc) {
                    continue;
                }
            }
            let resolved = fs::canonicalize(&path).unwrap_or(path.clone());
            let size = fs::metadata(&resolved).map(|m| m.len()).unwrap_or(0);
            eprintln!(
                "  {} <- {} ({})",
                color::bold_green(&name),
                resolved.display(),
                color::dim(&format_size(size))
            );
            if !dry_run {
                fs::create_dir_all(dest)?;
                let dest_path = dest.join(&name);
                ensure_writable(&dest_path);
                fs::copy(&resolved, &dest_path)?;
                let _ = fs::set_permissions(&dest_path, PermissionsExt::from_mode(0o755));
                if strip {
                    strip_debug(&dest_path);
                }
            }
            copied += 1;
            total_bytes += size;
        }
    }
    Ok((copied, total_bytes))
}

/// Mesa implementation libs loaded via dlopen by libglvnd (not in DT_NEEDED).
const MESA_IMPL_PREFIXES: &[&str] = &[
    "libGLX_mesa.so",
    "libEGL_mesa.so",
    "libglapi.so",
    "libgbm.so",
    "libxatracker.so",
];

/// glvnd dispatch libs. Bundled alongside Mesa to ensure version consistency
/// and to replace any incompatible versions shipped by the app.
const GLVND_PREFIXES: &[&str] = &[
    "libGL.so",
    "libGLX.so",
    "libEGL.so",
    "libGLESv2.so",
    "libOpenGL.so",
    "libGLdispatch.so",
];

/// All GL-related prefixes that should be removed from app subdirectories
/// when --gl replaces them with the system's glvnd/Mesa stack.
const ALL_GL_PREFIXES: &[&str] = &[
    // glvnd dispatch
    "libGL.so",
    "libGLX.so",
    "libEGL.so",
    "libGLESv2.so",
    "libOpenGL.so",
    "libGLdispatch.so",
    // Mesa impl
    "libGLX_mesa.so",
    "libEGL_mesa.so",
    "libglapi.so",
    "libgbm.so",
    "libxatracker.so",
    // utility
    "libGLU.so",
];

/// Remove GL libraries from subdirectories of `directory` that would conflict
/// with the glvnd/Mesa libs we copy into `lib_dest`. Files in `lib_dest`
/// itself are skipped (they get overwritten by copy_prefixed_libs).
fn remove_conflicting_gl_libs(directory: &Path, lib_dest: &Path, dry_run: bool) {
    let lib_dest_canon = fs::canonicalize(lib_dest).unwrap_or_else(|_| {
        // lib_dest may not exist yet; build an absolute path manually
        fs::canonicalize(directory)
            .unwrap_or_else(|_| directory.to_path_buf())
            .join(&lib_dest.strip_prefix(directory).unwrap_or(lib_dest))
    });

    let mut to_remove: Vec<PathBuf> = Vec::new();
    collect_gl_conflicts(directory, &lib_dest_canon, &mut to_remove);

    for path in &to_remove {
        let rel = path.strip_prefix(directory).unwrap_or(path);
        let label = if path.is_symlink() && !path.exists() {
            "dangling symlink"
        } else {
            "conflicts with bundled glvnd"
        };
        eprintln!(
            "  {} {} ({})",
            color::bold_red("Removing"),
            rel.display(),
            label,
        );
        if !dry_run {
            let _ = fs::remove_file(path);
        }
    }
}

/// Recursively find GL-related files and symlinks to remove, skipping
/// files directly in lib_dest (those get overwritten by copy_prefixed_libs).
fn collect_gl_conflicts(dir: &Path, lib_dest_canon: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.filter_map(Result::ok) {
        let path = entry.path();
        let is_symlink = path.is_symlink();

        if path.is_dir() && !is_symlink {
            // Always recurse — even into lib_dest so we catch its subdirectories
            collect_gl_conflicts(&path, lib_dest_canon, out);
            continue;
        }

        if !is_symlink && !path.is_file() {
            continue;
        }

        let name = match path.file_name() {
            Some(n) => n.to_string_lossy(),
            None => continue,
        };
        if !ALL_GL_PREFIXES.iter().any(|p| name.starts_with(p)) {
            continue;
        }

        // Skip files directly in lib_dest (those get overwritten by copy_prefixed_libs)
        if let Some(parent) = path.parent() {
            let parent_canon = fs::canonicalize(parent).unwrap_or(parent.to_path_buf());
            if parent_canon == *lib_dest_canon {
                continue;
            }
        }

        out.push(path);
    }
}

/// Wayland client libraries that may be dlopen'd or version-mismatched.
const WAYLAND_LIB_PREFIXES: &[&str] = &[
    "libwayland-client.so",
    "libwayland-server.so",
    "libwayland-cursor.so",
    "libwayland-egl.so",
    "libdecor-0.so",
    "libxkbcommon.so",
];

/// Bundle Wayland client libraries and libdecor plugins.
fn bundle_wayland(
    directory: &Path,
    lib_dir: &Path,
    extra_search: &[PathBuf],
    dry_run: bool,
    strip: bool,
) -> io::Result<()> {
    eprintln!("{} Wayland libraries...", color::bold("Bundling"));

    let elf_files = find_elf_files(directory);
    let target_class = elf_files.iter().find_map(|f| read_elf_class(f));

    let nix_paths = if Path::new("/nix/store").is_dir() {
        collect_nix_store_paths()
    } else {
        Vec::new()
    };
    let search_dirs = build_lib_search_dirs(&elf_files, extra_search, &nix_paths);
    let lib_dest = directory.join(lib_dir);

    // Copy Wayland libraries
    let (copied, total_bytes) = copy_prefixed_libs(
        &search_dirs,
        WAYLAND_LIB_PREFIXES,
        &lib_dest,
        target_class,
        dry_run,
        strip,
    )?;
    if copied > 0 {
        eprintln!(
            "  {} {} Wayland lib(s) ({})",
            verb_str(dry_run),
            copied,
            format_size(total_bytes)
        );
    }

    // Copy libdecor plugins from libdecor/plugins-1/ subdirs
    let plugin_dirs: Vec<PathBuf> = search_dirs
        .iter()
        .map(|d| d.join("libdecor/plugins-1"))
        .filter(|d| d.is_dir())
        .collect();

    let plugin_dest = directory.join("share/libdecor/plugins-1");
    let (plugin_count, _) = copy_so_dir(
        &plugin_dirs,
        &plugin_dest,
        target_class,
        None,
        dry_run,
        strip,
    )?;
    if plugin_count > 0 {
        eprintln!(
            "  {} {} libdecor plugin(s)",
            verb_str(dry_run),
            plugin_count
        );
    }

    if copied == 0 && plugin_count == 0 {
        eprintln!(
            "  {} no Wayland libraries found on this system",
            color::bold_red("warning:")
        );
    }

    Ok(())
}

/// Bundle GSettings compiled schemas so GTK/GLib apps don't crash with
/// "No GSettings schemas are installed on the system".
///
/// Collects `.gschema.xml` files from all discoverable schema directories
/// (system, NixOS store, XDG_DATA_DIRS) and compiles them into a single
/// `gschemas.compiled` using `glib-compile-schemas`.
fn bundle_gtk_data(directory: &Path, dry_run: bool) -> io::Result<()> {
    eprintln!("{} GTK data...", color::bold("Bundling"));

    let dest = directory.join("share/glib-2.0/schemas");
    if dest.join("gschemas.compiled").exists() {
        eprintln!("  {} already present", color::dim("gschemas.compiled"));
        return Ok(());
    }

    // Collect all schema source directories
    let mut schema_dirs: Vec<PathBuf> = Vec::new();

    // Standard paths (non-NixOS distros)
    for path in &[
        "/usr/share/glib-2.0/schemas",
        "/usr/local/share/glib-2.0/schemas",
    ] {
        let p = PathBuf::from(path);
        if p.is_dir() && !schema_dirs.contains(&p) {
            schema_dirs.push(p);
        }
    }

    // NixOS: scan store closures for schema dirs
    if Path::new("/nix/store").is_dir() {
        for sp in &collect_nix_store_paths() {
            let p = PathBuf::from(sp);
            // Standard layout
            let standard = p.join("share/glib-2.0/schemas");
            if standard.is_dir() && !schema_dirs.contains(&standard) {
                schema_dirs.push(standard);
            }
            // NixOS layout: share/gsettings-schemas/<pkg>/glib-2.0/schemas/
            let gs_dir = p.join("share/gsettings-schemas");
            if gs_dir.is_dir() {
                if let Ok(entries) = fs::read_dir(&gs_dir) {
                    for entry in entries.filter_map(Result::ok) {
                        let schemas = entry.path().join("glib-2.0/schemas");
                        if schemas.is_dir() && !schema_dirs.contains(&schemas) {
                            schema_dirs.push(schemas);
                        }
                    }
                }
            }
        }
    }

    // XDG_DATA_DIRS (including NixOS gsettings-schemas subdirs)
    if let Ok(xdg) = std::env::var("XDG_DATA_DIRS") {
        for dir in xdg.split(':').filter(|d| !d.is_empty()) {
            let schemas = PathBuf::from(dir).join("glib-2.0/schemas");
            if schemas.is_dir() && !schema_dirs.contains(&schemas) {
                schema_dirs.push(schemas);
            }
            let gs_dir = PathBuf::from(dir).join("gsettings-schemas");
            if gs_dir.is_dir() {
                if let Ok(entries) = fs::read_dir(&gs_dir) {
                    for entry in entries.filter_map(Result::ok) {
                        let schemas = entry.path().join("glib-2.0/schemas");
                        if schemas.is_dir() && !schema_dirs.contains(&schemas) {
                            schema_dirs.push(schemas);
                        }
                    }
                }
            }
        }
    }

    if schema_dirs.is_empty() {
        eprintln!(
            "  {} no GSettings schema directories found",
            color::bold_red("warning:")
        );
        return Ok(());
    }

    // Collect all .gschema.xml files into a temp dir, then compile
    let tmp = directory.join(".onelf-schemas-tmp");
    if !dry_run {
        let _ = fs::remove_dir_all(&tmp);
        fs::create_dir_all(&tmp)?;
    }

    let mut xml_count = 0usize;
    let mut seen: HashSet<String> = HashSet::new();
    for schema_dir in &schema_dirs {
        let Ok(entries) = fs::read_dir(schema_dir) else {
            continue;
        };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            let name = match path.file_name() {
                Some(n) => n.to_string_lossy().into_owned(),
                None => continue,
            };
            if !name.ends_with(".gschema.xml") && !name.ends_with(".enums.xml") {
                continue;
            }
            if !seen.insert(name.clone()) {
                continue;
            }
            if !dry_run {
                fs::copy(&path, tmp.join(&name))?;
            }
            xml_count += 1;
        }
    }

    if xml_count == 0 {
        eprintln!(
            "  {} no .gschema.xml files found",
            color::bold_red("warning:")
        );
        let _ = fs::remove_dir_all(&tmp);
        return Ok(());
    }

    eprintln!(
        "  Collected {} schema XML files from {} source(s)",
        xml_count,
        schema_dirs.len()
    );

    if dry_run {
        eprintln!(
            "  {} compile {} schema files",
            color::bold("Would"),
            xml_count
        );
        let _ = fs::remove_dir_all(&tmp);
        return Ok(());
    }

    // Compile schemas (find glib-compile-schemas, may not be in PATH on NixOS)
    let compiler = find_glib_compile_schemas();
    fs::create_dir_all(&dest)?;
    let output = Command::new(&compiler)
        .arg("--targetdir")
        .arg(&dest)
        .arg(&tmp)
        .output();

    let _ = fs::remove_dir_all(&tmp);

    match output {
        Ok(out) if out.status.success() => {
            let size = fs::metadata(dest.join("gschemas.compiled"))
                .map(|m| m.len())
                .unwrap_or(0);
            eprintln!(
                "  {} GSettings schemas ({}, {} sources)",
                color::bold_green("Compiled"),
                format_size(size),
                xml_count
            );
        }
        Ok(out) => {
            eprintln!(
                "  {} glib-compile-schemas failed: {}",
                color::bold_red("error:"),
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Err(e) => {
            eprintln!(
                "  {} glib-compile-schemas not found: {e}",
                color::bold_red("error:")
            );
            eprintln!("  hint: install glib development tools");
        }
    }

    Ok(())
}

/// Find `glib-compile-schemas` binary. On NixOS it's in glib-dev which may
/// not be in PATH, so we search the nix store.
fn find_glib_compile_schemas() -> PathBuf {
    // Try PATH first
    if let Ok(output) = Command::new("which").arg("glib-compile-schemas").output() {
        if output.status.success() {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !path.is_empty() {
                return PathBuf::from(path);
            }
        }
    }

    // NixOS: search store for glib-*-dev/bin/glib-compile-schemas
    if Path::new("/nix/store").is_dir() {
        if let Ok(entries) = fs::read_dir("/nix/store") {
            for entry in entries.filter_map(Result::ok) {
                let name = entry.file_name();
                let name = name.to_string_lossy();
                if name.contains("glib-") && name.ends_with("-dev") {
                    let candidate = entry.path().join("bin/glib-compile-schemas");
                    if candidate.is_file() {
                        return candidate;
                    }
                }
            }
        }
    }

    // Fallback — let Command::new fail with a clear error
    PathBuf::from("glib-compile-schemas")
}

/// Copy vendor JSON configs (EGL or Vulkan ICD), rewriting `library_path` to
/// filename-only and copying the referenced `.so` into `lib_dest`.
/// When `driver_filter` is Some, only copies configs whose library matches
/// the architecture-specific allowlist.
fn copy_vendor_json(
    src_dirs: &[PathBuf],
    json_dest: &Path,
    lib_dest: &Path,
    target_class: Option<u8>,
    driver_filter: Option<&[&str]>,
    dry_run: bool,
) -> io::Result<(usize, u64)> {
    let mut copied = 0usize;
    let mut total_bytes = 0u64;
    let mut seen: HashSet<String> = HashSet::new();

    for dir in src_dirs {
        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            let name = match path.file_name() {
                Some(n) => n.to_string_lossy().into_owned(),
                None => continue,
            };
            if !name.ends_with(".json") {
                continue;
            }
            if !seen.insert(name.clone()) {
                continue;
            }

            let content = match fs::read_to_string(&path) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let (rewritten, so_path) = rewrite_library_path(&content, &path);

            // If we found a library_path, validate ELF class and copy the .so
            if let Some(ref so_src) = so_path {
                let resolved = fs::canonicalize(so_src).unwrap_or(so_src.clone());
                // Architecture-specific driver filter
                if let Some(allowed) = driver_filter {
                    let so_fname = resolved.file_name().unwrap_or_default().to_string_lossy();
                    if !allowed.iter().any(|a| so_fname.starts_with(a)) {
                        continue;
                    }
                }
                if let Some(tc) = target_class {
                    if read_elf_class(&resolved) != Some(tc) {
                        continue;
                    }
                }
                let so_name = resolved
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .into_owned();
                let so_size = fs::metadata(&resolved).map(|m| m.len()).unwrap_or(0);
                eprintln!(
                    "  {} <- {} ({})",
                    color::bold_green(&so_name),
                    resolved.display(),
                    color::dim(&format_size(so_size))
                );
                if !dry_run {
                    fs::create_dir_all(lib_dest)?;
                    let dest_so = lib_dest.join(&so_name);
                    if !dest_so.exists() {
                        fs::copy(&resolved, &dest_so)?;
                        let _ = fs::set_permissions(&dest_so, PermissionsExt::from_mode(0o755));
                    }
                }
                total_bytes += so_size;
            }

            eprintln!("  {} <- {}", color::bold_green(&name), path.display());
            if !dry_run {
                fs::create_dir_all(json_dest)?;
                let dest_json = json_dest.join(&name);
                ensure_writable(&dest_json);
                fs::write(&dest_json, &rewritten)?;
            }
            copied += 1;
        }
    }
    Ok((copied, total_bytes))
}

/// Find `"library_path"` in a JSON string and rewrite absolute paths to filename-only.
/// Returns (rewritten_content, Option<resolved_so_path>).
fn rewrite_library_path(content: &str, json_path: &Path) -> (String, Option<PathBuf>) {
    // Match: "library_path" : "some/path"
    // Simple approach: find the key, extract the value, rewrite if absolute
    let key = "\"library_path\"";
    let Some(key_pos) = content.find(key) else {
        return (content.to_string(), None);
    };
    let after_key = &content[key_pos + key.len()..];

    // Skip whitespace and colon
    let after_colon = match after_key.find(':') {
        Some(i) => &after_key[i + 1..],
        None => return (content.to_string(), None),
    };

    // Find opening quote
    let Some(open_quote) = after_colon.find('"') else {
        return (content.to_string(), None);
    };
    let value_start = after_colon[open_quote + 1..].as_ptr() as usize - content.as_ptr() as usize;

    // Find closing quote
    let value_slice = &content[value_start..];
    let Some(close_quote) = value_slice.find('"') else {
        return (content.to_string(), None);
    };

    let lib_path_str = &content[value_start..value_start + close_quote];
    let lib_path = Path::new(lib_path_str);

    // Resolve relative paths against the JSON file's directory
    let resolved = if lib_path.is_absolute() {
        PathBuf::from(lib_path_str)
    } else {
        let dir = json_path.parent().unwrap_or(Path::new("."));
        dir.join(lib_path_str)
    };

    let filename = resolved
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .into_owned();

    // Rewrite the content: replace the path with just the filename
    let mut rewritten = String::with_capacity(content.len());
    rewritten.push_str(&content[..value_start]);
    rewritten.push_str(&filename);
    rewritten.push_str(&content[value_start + close_quote..]);

    (rewritten, Some(resolved))
}

/// Copy all files from a data directory into `dest`. Returns number of files copied.
fn copy_data_dir(src: &Path, dest: &Path, dry_run: bool) -> io::Result<u64> {
    let mut count = 0u64;
    let entries = fs::read_dir(src)?;
    for entry in entries.filter_map(Result::ok) {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let name = path.file_name().unwrap();
        eprintln!(
            "  {} <- {}",
            color::bold_green(&name.to_string_lossy()),
            path.display()
        );
        if !dry_run {
            fs::create_dir_all(dest)?;
            let dest_path = dest.join(name);
            ensure_writable(&dest_path);
            fs::copy(&path, &dest_path)?;
            let _ = fs::set_permissions(&dest_path, PermissionsExt::from_mode(0o644));
        }
        count += 1;
    }
    Ok(count)
}

/// Collect nix store paths from system and user closures.
fn collect_nix_store_paths() -> Vec<String> {
    let mut store_paths: HashSet<String> = HashSet::new();

    let roots: &[&str] = &["/run/current-system", "/etc/profiles/per-user"];

    // Also try ~/.nix-profile
    let home_profile = std::env::var("HOME")
        .ok()
        .map(|h| format!("{h}/.nix-profile"));

    for root in roots.iter().copied().chain(home_profile.as_deref()) {
        if !Path::new(root).exists() {
            continue;
        }
        let Ok(output) = Command::new("nix-store").args(["-qR", root]).output() else {
            continue;
        };
        if output.status.success() {
            for line in output.stdout.lines().map_while(Result::ok) {
                store_paths.insert(line.trim().to_string());
            }
        }
    }

    store_paths.into_iter().collect()
}