aboutsummarylogtreecommitdiffstats
path: root/minecraft-bedrock
blob: 36c5b9474442221e896cd3d8b26fa0bfca95d7be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
#!/usr/bin/env bash
set -euo pipefail

APP_ID="${MINECRAFT_BEDROCK_STEAM_APP_ID:-0}"
APP_HOME="${MINECRAFT_BEDROCK_HOME:-${XDG_DATA_HOME:-${HOME}/.local/share}/minecraft-bedrock}"
CACHE_DIR="${MINECRAFT_BEDROCK_CACHE_DIR:-${XDG_CACHE_HOME:-${HOME}/.cache}/minecraft-bedrock}"
STATE_DIR="${MINECRAFT_BEDROCK_STATE_DIR:-${XDG_STATE_HOME:-${HOME}/.local/state}/minecraft-bedrock}"
COMPAT_DATA_PATH="${MINECRAFT_BEDROCK_COMPAT_DATA_PATH:-${APP_HOME}/compatdata/${APP_ID}}"
PREFIX_PATH="${COMPAT_DATA_PATH}/pfx"
LEGACY_INSTALLER_URL="${MINECRAFT_BEDROCK_LEGACY_INSTALLER_URL:-https://aka.ms/minecraftClientWindows}"
GAMECORE_INSTALLER_URL="${MINECRAFT_BEDROCK_GAMECORE_INSTALLER_URL:-${MINECRAFT_BEDROCK_GDK_INSTALLER_URL:-https://aka.ms/minecraftClientGameCoreWindows}}"
INSTALLER_URL="${MINECRAFT_BEDROCK_INSTALLER_URL:-${GAMECORE_INSTALLER_URL}}"
INSTALLER_PATH="${MINECRAFT_BEDROCK_INSTALLER:-${CACHE_DIR}/MinecraftInstaller.exe}"
LEGACY_INSTALLER_PATH="${CACHE_DIR}/MinecraftInstaller.msi"
INSTALLER_RUNTIME_DIR="${CACHE_DIR}/installer-runtime"
GAMES_DIR="${APP_HOME}/games"
CONTENT_PATH="${APP_HOME}/content"
GAME_ARCHIVE_URL="${MINECRAFT_BEDROCK_GAME_ARCHIVE_URL:-}"
GAME_ARCHIVE_REPO="${MINECRAFT_BEDROCK_GAME_ARCHIVE_REPO:-}"
GAME_ARCHIVE_VERSION="${MINECRAFT_BEDROCK_GAME_VERSION:-}"
GAME_ARCHIVE_SHA256="${MINECRAFT_BEDROCK_GAME_ARCHIVE_SHA256:-}"
GAME_ARCHIVE_INCLUDE_PRERELEASE="${MINECRAFT_BEDROCK_INCLUDE_PRERELEASE:-0}"
BUBBLES_GAME_ARCHIVE_REPO="bubbles-wow/mcbe-gdk-unpack-archive"
GDK_PROTON_REPO="${MINECRAFT_BEDROCK_GDK_PROTON_REPO:-Weather-OS/GDK-Proton}"
DEFAULT_WINRT_CONTRACTS_VERSION="10.0.17763.1000"
DEFAULT_WINRT_CONTRACTS_SHA256="78b0b15a13ec3ae90f8e1e0fd609fd10f6d20ef984c5a56b48b55ceffbf88a94"
WINRT_CONTRACTS_VERSION="${MINECRAFT_BEDROCK_WINRT_CONTRACTS_VERSION:-${DEFAULT_WINRT_CONTRACTS_VERSION}}"
WINRT_CONTRACTS_URL="${MINECRAFT_BEDROCK_WINRT_CONTRACTS_URL:-https://www.nuget.org/api/v2/package/Microsoft.Windows.SDK.Contracts/${WINRT_CONTRACTS_VERSION}}"
WINRT_CONTRACTS_ARCHIVE="${CACHE_DIR}/Microsoft.Windows.SDK.Contracts.${WINRT_CONTRACTS_VERSION}.nupkg"
WINRT_CONTRACTS_DIR="${MINECRAFT_BEDROCK_WINRT_CONTRACTS_DIR:-${CACHE_DIR}/winrt-contracts-${WINRT_CONTRACTS_VERSION}}"
if [[ -n "${MINECRAFT_BEDROCK_WINRT_CONTRACTS_SHA256:-}" ]]; then
  WINRT_CONTRACTS_SHA256="${MINECRAFT_BEDROCK_WINRT_CONTRACTS_SHA256}"
elif [[ "${WINRT_CONTRACTS_VERSION}" == "${DEFAULT_WINRT_CONTRACTS_VERSION}" && -z "${MINECRAFT_BEDROCK_WINRT_CONTRACTS_URL:-}" ]]; then
  WINRT_CONTRACTS_SHA256="${DEFAULT_WINRT_CONTRACTS_SHA256}"
else
  WINRT_CONTRACTS_SHA256=""
fi
MSYS2_CURL_URL="${MINECRAFT_BEDROCK_MSYS2_CURL_URL:-https://mirror.msys2.org/mingw/mingw64/mingw-w64-x86_64-curl-8.17.0-1-any.pkg.tar.zst}"
CA_BUNDLE_URL="${MINECRAFT_BEDROCK_CA_BUNDLE_URL:-https://curl.se/ca/cacert.pem}"
GDK_DEPS_URL="${MINECRAFT_BEDROCK_GDK_DEPS_URL:-https://github.com/minecraft-linux/mcpelauncher-gdk-dependencies/releases/download/v0.0.0}"
STEAM_SHORTCUT_NAME="${MINECRAFT_BEDROCK_STEAM_NAME:-Minecraft Bedrock (Proton)}"
INSTALLED_SHORTCUT_HELPER="/usr/lib/minecraft-bedrock/steam-shortcut.py"
WINRT_CONTRACT_FILES=(
  Windows.Foundation.FoundationContract.winmd
  Windows.Foundation.UniversalApiContract.winmd
)
GDK_DEPS_DLLS=(
  libHttpClient.GDK.dll
)
DEFAULT_LAUNCHER_ARGS=(
  --disable-gpu
  --disable-gpu-compositing
  --disable-gpu-rasterization
  --disable-accelerated-2d-canvas
  --disable-accelerated-video-decode
)
DEFAULT_CEF_OPTIONS=(
  disable-gpu
  disable-gpu-compositing
  disable-gpu-rasterization
  disable-accelerated-2d-canvas
  disable-accelerated-video-decode
)

info() {
  printf '==> %s\n' "$*" >&2
}

warn() {
  printf 'warning: %s\n' "$*" >&2
}

die() {
  printf 'error: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
Usage: minecraft-bedrock [command]

Commands:
  setup [--gamecore|--legacy|--game-archive|--installed-game]
                        Install Proton, create the prefix, run installer, add Steam shortcut
  stop                  Stop Wine/Proton processes owned by this helper
  purge                 Remove prefix/cache/state, managed GDK-Proton, and Steam shortcut
  install-proton        Install latest Weather-OS GDK-Proton into Steam compatibilitytools.d
  download-installer    Download the current GameCore Minecraft installer
  install-winrt-contracts
                        Download WinRT contract metadata needed by the GameCore installer
  patch-installer [installer]
                        Patch a GameCore installer for Proton Mono compatibility
  init-prefix           Create/update the Proton compatdata prefix
  install-prereqs [--gamecore|--legacy]
                        Install prefix prerequisites with winetricks
  patch-proton-runtime Patch selected GDK-Proton runtime DLLs for Bedrock GDK
  install-gameinput [game-dir]
                        Install Microsoft GameInput redist from the GDK game files
  install-launcher [installer]
                        Run the downloaded Minecraft installer inside Proton
  list-game-versions   List configured GDK game archive releases
  download-game [tag]  Download and install a configured GDK game archive
  install-game <path>  Install an extracted GDK game directory or archive
  configure-launcher    Write launcher settings for Wine/Proton rendering
  patch-online          Patch Minecraft.Windows.exe directory with GDK online support files
  add-steam-shortcut    Add/update the Steam non-Steam shortcut
  launch [launcher|game|installer]
                        Launch the launcher, game, installer, or first available target
  paths                 Print resolved paths
  help                  Show this help

Environment:
  MINECRAFT_BEDROCK_PROTON_PATH       Proton directory or proton script to use
  MINECRAFT_BEDROCK_PREFER_GDK_PROTON Set to 1 to prefer GDK-Proton over Steam Proton
  MINECRAFT_BEDROCK_PREFER_STEAM_PROTON
                                      Set to 1 to prefer regular Steam Proton for game launch
  MINECRAFT_BEDROCK_NO_PROTON_PATCH   Set to 1 to skip GDK-Proton runtime patches
  MINECRAFT_BEDROCK_COMPAT_DATA_PATH  Proton compatdata directory
  MINECRAFT_BEDROCK_INSTALLER         Pre-downloaded installer path
  MINECRAFT_BEDROCK_GAME_ARCHIVE_URL  Zip/AppX/MSIX archive containing Minecraft.Windows.exe
  MINECRAFT_BEDROCK_GAME_ARCHIVE_REPO GitHub owner/repo for opt-in game archives
  MINECRAFT_BEDROCK_GAME_VERSION      Release tag to use with GAME_ARCHIVE_REPO
  MINECRAFT_BEDROCK_GAME_ARCHIVE_SHA256
                                      Expected sha256 for GAME_ARCHIVE_URL or repo asset
  MINECRAFT_BEDROCK_INCLUDE_PRERELEASE
                                      Set to 1 to allow prerelease game archives by default
  MINECRAFT_BEDROCK_WINRT_CONTRACTS_DIR
                                      Directory containing installer WinRT .winmd files
  MINECRAFT_BEDROCK_NO_IMPORT_GUI_ENV Set to 1 to disable importing GUI env from systemd
  MINECRAFT_BEDROCK_NO_INSTALLER_PATCH
                                      Set to 1 to skip patching the GameCore installer
  MINECRAFT_BEDROCK_DISABLE_GPU       Set to 0 to avoid writing disableGPU=true
  MINECRAFT_BEDROCK_CEF_OPTIONS       Space-separated CEF switches without leading --
  MINECRAFT_BEDROCK_LAUNCHER_ARGS     Override launcher Chromium/CEF flags
  MINECRAFT_BEDROCK_NO_LAUNCHER_ARGS  Set to 1 to pass no extra launcher flags
  MINECRAFT_BEDROCK_STEAM_USER_ID     Steam userdata id for shortcut writes
  MINECRAFT_BEDROCK_SKIP_WINETRICKS   Set to 1 to skip winetricks prereqs
  MINECRAFT_BEDROCK_USE_NATIVE_DOTNET Set to 1 to try native .NET for GameCore diagnostics
  MINECRAFT_BEDROCK_DIAGNOSTICS       Set to 1 to enable verbose game launch logs

Purge options:
  -y, --yes             Do not prompt before deleting files
      --keep-cache      Keep downloaded installers and patch assets
      --keep-proton     Keep helper-managed GDK-Proton installs
      --keep-shortcut   Keep the Steam non-Steam shortcut

Installer options:
      --gamecore        Download the current Windows 10/11 GameCore EXE (default)
      --legacy          Download the legacy MSI launcher installer
      --game-archive    Use configured game archive source instead of the launcher installer
      --installed-game  Use an already installed/imported Minecraft.Windows.exe
      --bubbles         Shorthand for --game-archive --repo bubbles-wow/mcbe-gdk-unpack-archive
      --repo owner/repo Use a GitHub release repo as the game archive source
      --url URL         Use a direct game archive URL
      --version tag     Use a specific game archive release tag
      --sha256 digest   Verify the selected game archive with this sha256
      --include-prerelease
                        Allow prerelease GitHub releases when auto-selecting a game archive
      --reset           Purge before setup; accepts --keep-cache/--keep-proton/--keep-shortcut
      --launch          Launch the game after setup succeeds
EOF
}

require_command() {
  command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"
}

try_find_steam_root() {
  local candidate
  local candidates=()

  [[ -n "${STEAM_COMPAT_CLIENT_INSTALL_PATH:-}" ]] && candidates+=("${STEAM_COMPAT_CLIENT_INSTALL_PATH}")
  [[ -n "${STEAM_ROOT:-}" ]] && candidates+=("${STEAM_ROOT}")
  candidates+=(
    "${HOME}/.steam/root"
    "${HOME}/.local/share/Steam"
    "${HOME}/.var/app/com.valvesoftware.Steam/.local/share/Steam"
  )

  for candidate in "${candidates[@]}"; do
    [[ -n "${candidate}" ]] || continue
    if [[ -d "${candidate}/steamapps" || -d "${candidate}/userdata" || -d "${candidate}/compatibilitytools.d" ]]; then
      (cd "${candidate}" && pwd -P)
      return 0
    fi
  done

  return 1
}

find_steam_root() {
  try_find_steam_root || die "Steam root not found. Start Steam once or set STEAM_ROOT."
}

resolve_proton_path() {
  local path="$1"
  [[ -n "${path}" ]] || return 1

  if [[ -x "${path}/proton" ]]; then
    (cd "${path}" && pwd -P)
    return 0
  fi

  if [[ -x "${path}" && "$(basename "${path}")" == "proton" ]]; then
    (cd "$(dirname "${path}")" && pwd -P)
    return 0
  fi

  return 1
}

find_installed_proton() {
  local resolved steam_root
  local gdk_candidates=()
  local steam_candidates=()
  local system_candidates=()
  local dir

  if [[ -n "${MINECRAFT_BEDROCK_PROTON_PATH:-}" ]]; then
    resolved="$(resolve_proton_path "${MINECRAFT_BEDROCK_PROTON_PATH}")" || \
      die "MINECRAFT_BEDROCK_PROTON_PATH does not contain an executable proton script"
    printf '%s\n' "${resolved}"
    return 0
  fi

  steam_root="$(try_find_steam_root || true)"
  if [[ -n "${steam_root}" ]]; then
    if [[ -d "${steam_root}/compatibilitytools.d" ]]; then
      while IFS= read -r -d '' dir; do
        gdk_candidates+=("${dir}")
      done < <(find "${steam_root}/compatibilitytools.d" -maxdepth 1 -type d -name 'GDK-Proton*' -print0 | sort -zV)
    fi

    if [[ -d "${steam_root}/steamapps/common" ]]; then
      while IFS= read -r -d '' dir; do
        steam_candidates+=("${dir}")
      done < <(find "${steam_root}/steamapps/common" -maxdepth 1 -type d \( -name 'Proton*' -o -name 'GE-Proton*' \) -print0 | sort -zV)
    fi
  fi

  if [[ -d "/usr/share/steam/compatibilitytools.d" ]]; then
    while IFS= read -r -d '' dir; do
      system_candidates+=("${dir}")
    done < <(find "/usr/share/steam/compatibilitytools.d" -maxdepth 1 -type d \( -name 'Proton*' -o -name 'GE-Proton*' -o -name 'proton-ge*' \) -print0 | sort -zV)
  fi

  if [[ "${MINECRAFT_BEDROCK_PREFER_GDK_PROTON:-0}" == "1" ]]; then
    for ((idx=${#gdk_candidates[@]} - 1; idx >= 0; idx--)); do
      resolved="$(resolve_proton_path "${gdk_candidates[$idx]}" || true)"
      if [[ -n "${resolved}" ]]; then
        printf '%s\n' "${resolved}"
        return 0
      fi
    done

    if [[ "${MINECRAFT_BEDROCK_REQUIRE_GDK_PROTON:-0}" == "1" ]]; then
      return 1
    fi
  fi

  for ((idx=${#steam_candidates[@]} - 1; idx >= 0; idx--)); do
    resolved="$(resolve_proton_path "${steam_candidates[$idx]}" || true)"
    if [[ -n "${resolved}" ]]; then
      printf '%s\n' "${resolved}"
      return 0
    fi
  done

  for ((idx=${#system_candidates[@]} - 1; idx >= 0; idx--)); do
    resolved="$(resolve_proton_path "${system_candidates[$idx]}" || true)"
    if [[ -n "${resolved}" ]]; then
      printf '%s\n' "${resolved}"
      return 0
    fi
  done

  for ((idx=${#gdk_candidates[@]} - 1; idx >= 0; idx--)); do
    resolved="$(resolve_proton_path "${gdk_candidates[$idx]}" || true)"
    if [[ -n "${resolved}" ]]; then
      printf '%s\n' "${resolved}"
      return 0
    fi
  done

  return 1
}

require_proton() {
  find_installed_proton || die "No Proton install found. Run \`minecraft-bedrock install-proton\` or set MINECRAFT_BEDROCK_PROTON_PATH."
}

maybe_import_graphical_env() {
  local line key value imported=0

  if [[ -n "${DISPLAY:-}" || -n "${WAYLAND_DISPLAY:-}" || "${MINECRAFT_BEDROCK_NO_IMPORT_GUI_ENV:-0}" == "1" ]]; then
    return 0
  fi

  if ! command -v systemctl >/dev/null 2>&1; then
    return 0
  fi

  while IFS= read -r line; do
    key="${line%%=*}"
    value="${line#*=}"
    [[ "${line}" == *=* && -n "${value}" ]] || continue

    case "${key}" in
      DISPLAY|WAYLAND_DISPLAY|XAUTHORITY|XDG_RUNTIME_DIR|DBUS_SESSION_BUS_ADDRESS|XDG_CURRENT_DESKTOP|XDG_SESSION_TYPE)
        if [[ -z "${!key:-}" ]]; then
          export "${key}=${value}"
          imported=1
        fi
        ;;
    esac
  done < <(systemctl --user show-environment 2>/dev/null || true)

  if [[ "${imported}" == "1" ]]; then
    info "Imported graphical session environment from systemd user manager."
  fi
}

require_graphical_env() {
  maybe_import_graphical_env

  if [[ -z "${DISPLAY:-}" && -z "${WAYLAND_DISPLAY:-}" ]]; then
    die "no graphical session detected. Run from a graphical terminal, set DISPLAY/WAYLAND_DISPLAY, or run \`systemctl --user import-environment DISPLAY WAYLAND_DISPLAY XAUTHORITY XDG_RUNTIME_DIR DBUS_SESSION_BUS_ADDRESS XDG_CURRENT_DESKTOP XDG_SESSION_TYPE\` from your desktop session."
  fi
}

record_managed_proton() {
  local proton_path="$1"

  mkdir -p "${STATE_DIR}"
  printf '%s\n' "${proton_path}" > "${STATE_DIR}/gdk-proton-path"
}

download_file() {
  local url="$1"
  local dest="$2"
  local tmp="${dest}.part"

  require_command curl
  mkdir -p "$(dirname "${dest}")"
  info "Downloading ${url}"
  curl --fail --location --retry 3 --retry-delay 2 \
    --user-agent 'minecraft-bedrock-aur/0.1' \
    --output "${tmp}" \
    "${url}"
  mv -f "${tmp}" "${dest}"
}

verify_sha256() {
  local file="$1"
  local expected="$2"

  [[ -n "${expected}" ]] || return 0
  expected="${expected#sha256:}"
  printf '%s  %s\n' "${expected}" "${file}" | sha256sum -c - >&2
}

download_installer_to() {
  local url="$1"
  local dest="$2"
  local format="${3:-exe}"
  local magic

  if [[ -f "${dest}" ]]; then
    info "Using existing installer: ${dest}"
  else
    download_file "${url}" "${dest}"
  fi

  case "${format}" in
    exe)
      magic="$(LC_ALL=C dd if="${dest}" bs=2 count=1 2>/dev/null || true)"
      [[ "${magic}" == "MZ" ]] || die "${dest} does not look like a Windows executable"
      ;;
    msi)
      magic="$(od -An -tx1 -N8 "${dest}" | tr -d ' \n')"
      [[ "${magic}" == "d0cf11e0a1b11ae1" ]] || die "${dest} does not look like a Windows Installer MSI"
      ;;
    *)
      die "unknown installer format: ${format}"
      ;;
  esac
}

latest_gdk_release() {
  require_command python
  python - "${GDK_PROTON_REPO}" <<'PY'
import json
import sys
import urllib.request

repo = sys.argv[1]
request = urllib.request.Request(
    f"https://api.github.com/repos/{repo}/releases/latest",
    headers={
        "Accept": "application/vnd.github+json",
        "User-Agent": "minecraft-bedrock-aur/0.1",
    },
)
with urllib.request.urlopen(request) as response:
    release = json.load(response)

assets = [
    asset for asset in release.get("assets", [])
    if asset.get("name", "").endswith(".tar.gz")
]
if not assets:
    raise SystemExit("no .tar.gz release asset found")

asset = assets[0]
digest = asset.get("digest") or ""
sha256 = digest.split(":", 1)[1] if digest.startswith("sha256:") else ""
print(
    release.get("name") or release.get("tag_name") or "GDK-Proton",
    asset["name"],
    asset["browser_download_url"],
    sha256,
    sep="\t",
)
PY
}

cmd_install_proton() {
  local steam_root tools_dir release_name asset_name asset_url asset_sha archive target tmp extracted existing

  if [[ -n "${MINECRAFT_BEDROCK_PROTON_PATH:-}" ]]; then
    info "MINECRAFT_BEDROCK_PROTON_PATH is set; skipping GDK-Proton install"
    return 0
  fi

  existing="$(find_installed_proton || true)"
  if [[ -n "${existing}" && "$(basename "${existing}")" == GDK-Proton* ]]; then
    info "Using existing GDK-Proton: ${existing}"
    return 0
  fi

  steam_root="$(find_steam_root)"
  tools_dir="${steam_root}/compatibilitytools.d"
  mkdir -p "${tools_dir}" "${CACHE_DIR}"

  IFS=$'\t' read -r release_name asset_name asset_url asset_sha < <(latest_gdk_release)
  archive="${CACHE_DIR}/${asset_name}"
  target="${tools_dir}/${asset_name%.tar.gz}"

  if [[ -x "${target}/proton" ]]; then
    if [[ -f "${target}/.minecraft-bedrock-managed" ]]; then
      record_managed_proton "${target}"
    fi
    info "Using existing ${release_name}: ${target}"
    return 0
  fi

  if [[ ! -f "${archive}" ]]; then
    download_file "${asset_url}" "${archive}"
  else
    info "Using cached GDK-Proton archive: ${archive}"
  fi

  if [[ -n "${asset_sha}" ]]; then
    printf '%s  %s\n' "${asset_sha}" "${archive}" | sha256sum -c - >&2
  else
    warn "No sha256 digest published for ${asset_name}; skipping checksum verification"
  fi

  tmp="$(mktemp -d "${tools_dir}/.gdk-proton.XXXXXX")"
  tar -xzf "${archive}" -C "${tmp}"
  extracted="$(find "${tmp}" -mindepth 1 -maxdepth 1 -type d -print -quit)"
  [[ -n "${extracted}" && -x "${extracted}/proton" ]] || die "GDK-Proton archive did not contain a proton script"

  rm -rf "${target}"
  mv "${extracted}" "${target}"
  printf 'Managed by minecraft-bedrock. Safe to remove with `minecraft-bedrock purge`.\n' \
    > "${target}/.minecraft-bedrock-managed"
  record_managed_proton "${target}"
  rmdir "${tmp}"
  info "Installed ${release_name}: ${target}"
  warn "Restart Steam so it notices newly installed compatibility tools."
}

cmd_ensure_proton() {
  local proton

  proton="$(find_installed_proton || true)"
  if [[ -n "${proton}" ]]; then
    info "Using Proton: ${proton}"
    return 0
  fi

  warn "No Steam Proton install found; installing GDK-Proton as a fallback."
  cmd_install_proton
}

prefer_gdk_proton_for_game() {
  if [[ "${MINECRAFT_BEDROCK_PREFER_STEAM_PROTON:-0}" == "1" || -n "${MINECRAFT_BEDROCK_PROTON_PATH:-}" ]]; then
    return 0
  fi

  export MINECRAFT_BEDROCK_PREFER_GDK_PROTON=1
  export MINECRAFT_BEDROCK_REQUIRE_GDK_PROTON=1
}

patch_gdk_proton_runtime() {
  local proton_dir wine_dir base

  if [[ "${MINECRAFT_BEDROCK_NO_PROTON_PATCH:-0}" == "1" ]]; then
    warn "Skipping GDK-Proton runtime patches"
    return 0
  fi

  proton_dir="$(require_proton)"
  base="$(basename "${proton_dir}")"
  case "${base}" in
    GDK-Proton*|GDK_Proton*|gdk-proton*)
      ;;
    *)
      if [[ "${MINECRAFT_BEDROCK_ALLOW_PROTON_PATCH:-0}" != "1" ]]; then
        warn "Not patching non-GDK Proton runtime: ${proton_dir}"
        warn "Set MINECRAFT_BEDROCK_ALLOW_PROTON_PATCH=1 to patch this runtime anyway."
        return 0
      fi
      ;;
  esac

  wine_dir="${proton_dir}/files/lib/wine/x86_64-windows"
  [[ -f "${wine_dir}/combase.dll" && -f "${wine_dir}/ntdll.dll" ]] || die "GDK-Proton Wine DLLs not found in ${wine_dir}"

  require_command python
  python - "${wine_dir}/combase.dll" "${wine_dir}/ntdll.dll" <<'PY'
import shutil
import struct
import sys
from pathlib import Path

combase = Path(sys.argv[1])
ntdll = Path(sys.argv[2])


class PE:
    def __init__(self, path):
        self.path = path
        self.data = path.read_bytes()
        data = self.data
        if data[:2] != b"MZ":
            raise ValueError(f"{path} is not a PE file")
        e_lfanew = struct.unpack_from("<I", data, 0x3C)[0]
        if data[e_lfanew:e_lfanew + 4] != b"PE\0\0":
            raise ValueError(f"{path} has no PE signature")
        coff = e_lfanew + 4
        section_count = struct.unpack_from("<H", data, coff + 2)[0]
        optional = coff + 20
        if struct.unpack_from("<H", data, optional)[0] != 0x20B:
            raise ValueError(f"{path} is not PE32+")
        optional_size = struct.unpack_from("<H", data, coff + 16)[0]
        self.export_rva = struct.unpack_from("<I", data, optional + 112)[0]
        section_table = optional + optional_size
        self.sections = []
        for index in range(section_count):
            base = section_table + index * 40
            virtual_size, virtual_address, raw_size, raw_pointer = struct.unpack_from("<IIII", data, base + 8)
            self.sections.append((virtual_address, virtual_size, raw_pointer, raw_size))

    def rva_to_offset(self, rva):
        for virtual_address, virtual_size, raw_pointer, raw_size in self.sections:
            span = max(virtual_size, raw_size)
            if virtual_address <= rva < virtual_address + span:
                return raw_pointer + (rva - virtual_address)
        return None

    def offset_to_rva(self, offset):
        for virtual_address, _virtual_size, raw_pointer, raw_size in self.sections:
            if raw_pointer <= offset < raw_pointer + raw_size:
                return virtual_address + (offset - raw_pointer)
        return None

    def export_offset(self, name):
        data = self.data
        export_offset = self.rva_to_offset(self.export_rva)
        if export_offset is None:
            return None
        name_count = struct.unpack_from("<I", data, export_offset + 24)[0]
        function_table = self.rva_to_offset(struct.unpack_from("<I", data, export_offset + 28)[0])
        name_table = self.rva_to_offset(struct.unpack_from("<I", data, export_offset + 32)[0])
        ordinal_table = self.rva_to_offset(struct.unpack_from("<I", data, export_offset + 36)[0])
        wanted = name.encode("ascii")
        for index in range(name_count):
            name_rva = struct.unpack_from("<I", data, name_table + 4 * index)[0]
            name_offset = self.rva_to_offset(name_rva)
            end = data.index(b"\0", name_offset)
            if data[name_offset:end] != wanted:
                continue
            ordinal = struct.unpack_from("<H", data, ordinal_table + 2 * index)[0]
            function_rva = struct.unpack_from("<I", data, function_table + 4 * ordinal)[0]
            return self.rva_to_offset(function_rva)
        return None

    def export_rva_by_name(self, name):
        offset = self.export_offset(name)
        return self.offset_to_rva(offset) if offset is not None else None


def backup_once(path):
    backup = path.with_suffix(path.suffix + ".minecraft-bedrock.bak")
    if not backup.exists():
        shutil.copy2(path, backup)


def patch_combase(path):
    pe = PE(path)
    offset = pe.export_offset("RoOriginateErrorW")
    if offset is None:
        raise SystemExit("RoOriginateErrorW not found in combase.dll")
    raw = bytearray(pe.data)
    replacement = bytes.fromhex("31c0c3") + b"\x90" * 21
    if bytes(raw[offset:offset + len(replacement)]) == replacement:
        print("combase.RoOriginateErrorW already patched", file=sys.stderr)
        return
    backup_once(path)
    raw[offset:offset + len(replacement)] = replacement
    path.write_bytes(raw)
    print("patched combase.RoOriginateErrorW", file=sys.stderr)


def patch_ntdll(path):
    pe = PE(path)
    rre = pe.export_rva_by_name("RtlRaiseException")
    if rre is None:
        raise SystemExit("RtlRaiseException not resolved in ntdll.dll")
    data = pe.data
    sig = bytes.fromhex("55534881ecc8000000488dac24c0000000")
    replacement = bytes.fromhex("b8020000c0c3") + b"\x90\x90"
    funnels = []
    index = data.find(sig)
    while index >= 0:
        call = data.find(bytes.fromhex("4889d9e8"), index, index + 0x90)
        if call >= 0:
            call_function = call + 3
            rel = struct.unpack_from("<i", data, call_function + 1)[0]
            target = pe.offset_to_rva(call_function) + 5 + rel
            if target == rre and data[call_function + 5:call_function + 7] == b"\xeb\xf6":
                funnels.append(index)
        index = data.find(sig, index + 1)

    if funnels:
        raw = bytearray(data)
        for offset in funnels:
            raw[offset:offset + len(replacement)] = replacement
        backup_once(path)
        path.write_bytes(raw)
        print(f"patched ntdll unimplemented stub funnel(s): {len(funnels)}", file=sys.stderr)
        return

    if replacement in data:
        print("ntdll unimplemented stub funnel already patched", file=sys.stderr)
        return

    raise SystemExit("ntdll unimplemented stub funnel not found")


patch_combase(combase)
patch_ntdll(ntdll)
PY
}

run_proton_wait() {
  local proton_dir steam_root
  proton_dir="$(require_proton)"
  steam_root="$(find_steam_root)"
  maybe_import_graphical_env

  mkdir -p "${COMPAT_DATA_PATH}" "${STATE_DIR}"
  env \
    STEAM_COMPAT_CLIENT_INSTALL_PATH="${steam_root}" \
    STEAM_COMPAT_DATA_PATH="${COMPAT_DATA_PATH}" \
    STEAM_COMPAT_APP_ID="${APP_ID}" \
    WINEDEBUG="${WINEDEBUG:--all}" \
    "${proton_dir}/proton" waitforexitandrun "$@"
}

launcher_args() {
  local arg
  local override_args=()

  if [[ "${MINECRAFT_BEDROCK_NO_LAUNCHER_ARGS:-0}" == "1" ]]; then
    return 0
  fi

  if [[ -n "${MINECRAFT_BEDROCK_LAUNCHER_ARGS:-}" ]]; then
    read -r -a override_args <<< "${MINECRAFT_BEDROCK_LAUNCHER_ARGS}"
    for arg in "${override_args[@]}"; do
      printf '%s\0' "${arg}"
    done
    return 0
  fi

  for arg in "${DEFAULT_LAUNCHER_ARGS[@]}"; do
    printf '%s\0' "${arg}"
  done
}

cmd_download_installer() {
  local url="${INSTALLER_URL}"
  local dest="${INSTALLER_PATH}"
  local format="exe"

  case "${1:---gamecore}" in
    --gamecore|--windows-gdk|--gdk|--win10|--win11)
      ;;
    --legacy)
      url="${LEGACY_INSTALLER_URL}"
      dest="${MINECRAFT_BEDROCK_INSTALLER:-${LEGACY_INSTALLER_PATH}}"
      format="msi"
      ;;
    *)
      die "unknown installer option: $1"
      ;;
  esac

  if [[ -n "${MINECRAFT_BEDROCK_INSTALLER:-}" && -f "${MINECRAFT_BEDROCK_INSTALLER}" ]]; then
    info "Using MINECRAFT_BEDROCK_INSTALLER=${MINECRAFT_BEDROCK_INSTALLER}"
    return 0
  fi

  download_installer_to "${url}" "${dest}" "${format}"
}

require_game_archive_repo() {
  [[ -n "${GAME_ARCHIVE_REPO}" ]] || die "no game archive source configured. Set MINECRAFT_BEDROCK_GAME_ARCHIVE_URL to a zip/appx/msix archive you are allowed to use, or set MINECRAFT_BEDROCK_GAME_ARCHIVE_REPO=owner/repo for an explicit GitHub release source."
}

github_game_archive_info() {
  local tag="${1:-}"

  require_game_archive_repo
  require_command python
  python - "${GAME_ARCHIVE_REPO}" "${tag}" "${GAME_ARCHIVE_INCLUDE_PRERELEASE}" <<'PY'
import json
import sys
import urllib.parse
import urllib.request

repo, tag, include_prerelease = sys.argv[1], sys.argv[2], sys.argv[3] == "1"
headers = {
    "Accept": "application/vnd.github+json",
    "User-Agent": "minecraft-bedrock-aur/0.1",
}

def fetch(url):
    request = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(request) as response:
        return json.load(response)

if tag:
    releases = [fetch(f"https://api.github.com/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}")]
else:
    releases = fetch(f"https://api.github.com/repos/{repo}/releases?per_page=30")

for release in releases:
    if not tag and release.get("prerelease") and not include_prerelease:
        continue
    assets = release.get("assets", [])
    for asset in assets:
        name = asset.get("name", "")
        lower = name.lower()
        if lower.endswith((".zip", ".appx", ".appxbundle", ".msix", ".msixbundle")) and "minecraft" in lower:
            print(
                release.get("tag_name", ""),
                name,
                asset.get("browser_download_url", ""),
                asset.get("size", 0),
                asset.get("digest") or "",
                sep="\t",
            )
            raise SystemExit(0)

raise SystemExit("no Minecraft archive asset found in configured release source")
PY
}

cmd_list_game_versions() {
  require_game_archive_repo
  require_command python
  python - "${GAME_ARCHIVE_REPO}" <<'PY'
import json
import sys
import urllib.request

repo = sys.argv[1]
request = urllib.request.Request(
    f"https://api.github.com/repos/{repo}/releases?per_page=60",
    headers={
        "Accept": "application/vnd.github+json",
        "User-Agent": "minecraft-bedrock-aur/0.1",
    },
)
with urllib.request.urlopen(request) as response:
    releases = json.load(response)

for release in releases:
    assets = release.get("assets", [])
    archive = next(
        (
            asset
            for asset in assets
            if asset.get("name", "").lower().endswith(
                (".zip", ".appx", ".appxbundle", ".msix", ".msixbundle")
            )
            and "minecraft" in asset.get("name", "").lower()
        ),
        None,
    )
    if not archive:
        continue
    print(
        release.get("tag_name", ""),
        "prerelease" if release.get("prerelease") else "stable",
        archive.get("name", ""),
        archive.get("size", 0),
        sep="\t",
    )
PY
}

find_game_root_in() {
  local base="$1"
  local exe dir

  [[ -d "${base}" ]] || return 1
  while IFS= read -r -d '' exe; do
    dir="$(dirname "${exe}")"
    if [[ -f "${dir}/AppxManifest.xml" || -f "${dir}/appxmanifest.xml" ]]; then
      printf '%s\n' "${dir}"
      return 0
    fi
  done < <(find "${base}" -type f -iname 'Minecraft.Windows.exe' -print0 2>/dev/null || true)

  return 1
}

game_version_from_dir() {
  local game_dir="$1"

  require_command python
  python - "${game_dir}" <<'PY'
import re
import sys
from pathlib import Path

game_dir = Path(sys.argv[1])
for name in ("AppxManifest.xml", "appxmanifest.xml"):
    manifest = game_dir / name
    if not manifest.exists():
        continue
    match = re.search(
        r'Identity[^>]*Version="(\d+)\.(\d+)\.(\d+)\.\d+"',
        manifest.read_text(encoding="utf-8", errors="ignore"),
    )
    if not match:
        continue
    patch = match.group(3)
    if len(patch) >= 3:
        print(f"{match.group(1)}.{match.group(2)}.{int(patch[:2])}.{int(patch[2:])}")
    else:
        print(f"{match.group(1)}.{match.group(2)}.{int(patch)}")
    raise SystemExit(0)
raise SystemExit(1)
PY
}

safe_game_label() {
  local label="$1"

  label="${label//\//_}"
  label="${label//\\/_}"
  label="${label#"${label%%[![:space:]]*}"}"
  label="${label%"${label##*[![:space:]]}"}"
  if [[ -z "${label}" || "${label}" == "." || "${label}" == ".." ]]; then
    label="minecraft"
  fi
  printf '%s\n' "${label}"
}

cmd_install_game() {
  local source="${1:-}"
  local label="${2:-}"
  local tmp="" root version dest root_real dest_real

  [[ -n "${source}" ]] || die "install-game requires an extracted game directory or archive path"
  require_command bsdtar
  mkdir -p "${CACHE_DIR}"

  if [[ -d "${source}" ]]; then
    root="$(find_game_root_in "${source}")" || die "Minecraft.Windows.exe with AppxManifest.xml was not found under ${source}"
  elif [[ -f "${source}" ]]; then
    tmp="$(mktemp -d "${CACHE_DIR}/game-extract.XXXXXX")"
    info "Extracting Minecraft game archive: ${source}"
    bsdtar -xf "${source}" -C "${tmp}"
    root="$(find_game_root_in "${tmp}")" || {
      rm -rf "${tmp}"
      die "Minecraft.Windows.exe with AppxManifest.xml was not found in ${source}"
    }
  else
    die "game source not found: ${source}"
  fi

  version="$(game_version_from_dir "${root}" || true)"
  if [[ -z "${label}" ]]; then
    label="${GAME_ARCHIVE_VERSION:-${version:-$(basename "${source}")}}"
  fi
  label="$(safe_game_label "${label}")"
  dest="${GAMES_DIR}/${label}"
  root_real="$(realpath -m -- "${root}")"
  dest_real="$(realpath -m -- "${dest}")"

  mkdir -p "${GAMES_DIR}"
  if [[ "${root_real}" != "${dest_real}" ]]; then
    rm -rf -- "${dest}"
    mkdir -p "${dest}"
    cp -a "${root}/." "${dest}/"
  fi
  rm -rf -- "${CONTENT_PATH}"
  ln -s "${dest}" "${CONTENT_PATH}"
  rm -rf "${tmp}"

  info "Installed Minecraft game content: ${dest}"
  cmd_patch_online
}

cmd_download_game() {
  local tag="${1:-${GAME_ARCHIVE_VERSION}}"
  local archive name url size digest

  if [[ -n "${GAME_ARCHIVE_URL}" ]]; then
    name="${GAME_ARCHIVE_URL%%\?*}"
    name="${name##*/}"
    [[ -n "${name}" ]] || name="MinecraftGame.zip"
    archive="${CACHE_DIR}/${name}"
    if [[ -f "${archive}" ]]; then
      info "Using cached game archive: ${archive}"
    else
      download_file "${GAME_ARCHIVE_URL}" "${archive}"
    fi
    verify_sha256 "${archive}" "${GAME_ARCHIVE_SHA256}"
    cmd_install_game "${archive}" "${tag:-${name}}"
    return 0
  fi

  IFS=$'\t' read -r tag name url size digest < <(github_game_archive_info "${tag}")
  [[ -n "${url}" && -n "${name}" ]] || die "configured game archive release did not include a downloadable asset"
  archive="${CACHE_DIR}/${name}"
  if [[ -f "${archive}" ]]; then
    info "Using cached game archive: ${archive}"
  else
    info "Downloading Minecraft game archive ${tag} (${size} bytes)"
    download_file "${url}" "${archive}"
  fi
  if [[ -n "${GAME_ARCHIVE_SHA256}" ]]; then
    verify_sha256 "${archive}" "${GAME_ARCHIVE_SHA256}"
  elif [[ -n "${digest}" ]]; then
    verify_sha256 "${archive}" "${digest}"
  else
    warn "No sha256 digest published for ${name}; skipping archive checksum verification"
  fi
  cmd_install_game "${archive}" "${tag}"
}

cmd_install_winrt_contracts() {
  local tmp contract src dest missing=0

  for contract in "${WINRT_CONTRACT_FILES[@]}"; do
    [[ -f "${WINRT_CONTRACTS_DIR}/${contract}" ]] || missing=1
  done

  if [[ "${missing}" == "0" ]]; then
    info "Using existing WinRT installer contracts: ${WINRT_CONTRACTS_DIR}"
    return 0
  fi

  require_command curl
  require_command bsdtar

  mkdir -p "${CACHE_DIR}" "${WINRT_CONTRACTS_DIR}"
  if [[ -f "${WINRT_CONTRACTS_ARCHIVE}" ]]; then
    info "Using cached Microsoft.Windows.SDK.Contracts archive: ${WINRT_CONTRACTS_ARCHIVE}"
  else
    download_file "${WINRT_CONTRACTS_URL}" "${WINRT_CONTRACTS_ARCHIVE}"
  fi
  if [[ -n "${WINRT_CONTRACTS_SHA256}" ]]; then
    printf '%s  %s\n' "${WINRT_CONTRACTS_SHA256}" "${WINRT_CONTRACTS_ARCHIVE}" | sha256sum -c - >&2
  else
    warn "No sha256 configured for Microsoft.Windows.SDK.Contracts; skipping checksum verification"
  fi

  tmp="$(mktemp -d "${CACHE_DIR}/winrt-contracts.XXXXXX")"
  bsdtar -xf "${WINRT_CONTRACTS_ARCHIVE}" -C "${tmp}"
  for contract in "${WINRT_CONTRACT_FILES[@]}"; do
    src="${tmp}/ref/netstandard2.0/${contract}"
    dest="${WINRT_CONTRACTS_DIR}/${contract}"
    [[ -f "${src}" ]] || die "Microsoft.Windows.SDK.Contracts did not contain ref/netstandard2.0/${contract}"
    install -Dm644 "${src}" "${dest}"
  done
  rm -rf "${tmp}"

  info "Installed WinRT installer contracts: ${WINRT_CONTRACTS_DIR}"
}

patch_gamecore_installer() {
  local installer="$1"

  if [[ "${MINECRAFT_BEDROCK_NO_INSTALLER_PATCH:-0}" == "1" ]]; then
    warn "Skipping GameCore installer patch; Proton Mono may fail on WinRT high-contrast APIs"
    return 0
  fi

  require_command python
  python - "${installer}" <<'PY'
import sys
from pathlib import Path

path = Path(sys.argv[1])
data = bytearray(path.read_bytes())

# MinecraftInstaller.App::.ctor only uses AccessibilitySettings to choose a
# high-contrast ResourceDictionary. Proton Mono currently fails when invoking
# that WinRT constructor, so force the branch false while preserving offsets.
original = [
    0x73, None, None, None, None,  # newobj AccessibilitySettings::.ctor()
    0x06,                          # ldloc.0
    0x72, None, None, None, None,  # ldstr ";component/Themes/AppStyleSheet.xaml"
    0x16,                          # ldc.i4.0
    0x73, None, None, None, None,  # newobj Uri::.ctor(string, UriKind)
    0x6f, None, None, None, None,  # callvirt ResourceDictionary::set_Source
    0x6f, None, None, None, None,  # callvirt AccessibilitySettings::get_HighContrast()
    0x39, None, None, None, None,  # brfalse IL_00ea
    0x73,                          # newobj ResourceDictionary::.ctor()
]
patched = [
    0x16, 0x00, 0x00, 0x00, 0x00,  # ldc.i4.0; nop; nop; nop; nop
    0x06,
    0x72, None, None, None, None,
    0x16,
    0x73, None, None, None, None,
    0x6f, None, None, None, None,
    0x00, 0x00, 0x00, 0x00, 0x00,  # nop x5
    0x39, None, None, None, None,
    0x73,
]


def find(pattern):
    matches = []
    limit = len(data) - len(pattern) + 1
    for offset in range(max(limit, 0)):
        for idx, value in enumerate(pattern):
            if value is not None and data[offset + idx] != value:
                break
        else:
            matches.append(offset)
    return matches


matches = find(original)
if len(matches) == 1:
    offset = matches[0]
    data[offset:offset + 5] = b"\x16\x00\x00\x00\x00"
    data[offset + 22:offset + 27] = b"\x00\x00\x00\x00\x00"
    tmp = path.with_suffix(path.suffix + ".patched")
    tmp.write_bytes(data)
    tmp.replace(path)
    print("patched Proton Mono high-contrast WinRT call", file=sys.stderr)
    raise SystemExit(0)

if not matches and len(find(patched)) == 1:
    print("installer already has Proton Mono high-contrast patch", file=sys.stderr)
    raise SystemExit(0)

if matches:
    print(f"expected one installer patch target, found {len(matches)}", file=sys.stderr)
else:
    print("installer patch target not found; Microsoft may have changed the installer", file=sys.stderr)
raise SystemExit(1)
PY
}

cmd_patch_installer() {
  local installer="${1:-${INSTALLER_PATH}}"

  [[ -f "${installer}" ]] || die "installer not found: ${installer}"
  patch_gamecore_installer "${installer}"
}

stage_exe_installer() {
  local installer="$1"
  local staged

  cmd_install_winrt_contracts >&2
  mkdir -p "${INSTALLER_RUNTIME_DIR}"

  staged="${INSTALLER_RUNTIME_DIR}/$(basename "${installer}")"
  install -Dm644 "${installer}" "${staged}"
  patch_gamecore_installer "${staged}" >&2
  for contract in "${WINRT_CONTRACT_FILES[@]}"; do
    install -Dm644 "${WINRT_CONTRACTS_DIR}/${contract}" "${INSTALLER_RUNTIME_DIR}/${contract}"
    install -Dm644 "${WINRT_CONTRACTS_DIR}/${contract}" "${INSTALLER_RUNTIME_DIR}/${contract%.winmd}.dll"
  done

  printf '%s\n' "${staged}"
}

cmd_init_prefix() {
  info "Creating/updating Proton prefix at ${PREFIX_PATH}"
  run_proton_wait cmd.exe /c exit
}

cmd_install_prereqs() {
  local installer_option="${1:---gamecore}"
  local use_dotnet=0
  local proton_dir wine wineserver

  if [[ "${MINECRAFT_BEDROCK_SKIP_WINETRICKS:-0}" == "1" ]]; then
    info "Skipping winetricks prerequisites"
    return 0
  fi

  case "${installer_option}" in
    --legacy)
      ;;
    --gamecore|--windows-gdk|--gdk|--win10|--win11)
      if [[ "${MINECRAFT_BEDROCK_USE_NATIVE_DOTNET:-0}" == "1" && "${MINECRAFT_BEDROCK_SKIP_DOTNET:-0}" != "1" ]]; then
        use_dotnet=1
      fi
      ;;
    *)
      die "unknown installer option: ${installer_option}"
      ;;
  esac

  if ! command -v winetricks >/dev/null 2>&1; then
    if [[ "${use_dotnet}" == "1" ]]; then
      die "winetricks is required to install native .NET Framework 4.8"
    fi
    warn "winetricks is not installed; skipping optional prerequisites"
    return 0
  fi

  proton_dir="$(require_proton)"
  wine="${proton_dir}/files/bin/wine"
  wineserver="${proton_dir}/files/bin/wineserver"
  if [[ ! -x "${wine}" || ! -x "${wineserver}" ]]; then
    warn "Could not find Proton wine/wineserver binaries; skipping winetricks"
    return 0
  fi

  mkdir -p "${PREFIX_PATH}"

  if [[ "${use_dotnet}" == "1" ]]; then
    if [[ -f "${PREFIX_PATH}/dosdevices/c:/windows/dotnet48.installed.workaround" ]]; then
      info "Using existing native .NET Framework 4.8 install"
    else
      info "Installing native .NET Framework 4.8 for diagnostics. This can take several minutes."
      WINEPREFIX="${PREFIX_PATH}" \
        WINE="${wine}" \
        WINESERVER="${wineserver}" \
        WINEDEBUG="${WINEDEBUG:--all}" \
        winetricks -q dotnet48 || die "winetricks dotnet48 failed"

      info "Restoring prefix Windows version to win10"
      WINEPREFIX="${PREFIX_PATH}" \
        WINEDEBUG="${WINEDEBUG:--all}" \
        "${wine}" winecfg -v win10 || warn "could not restore Windows version to win10"
    fi
  fi

  info "Installing optional vcrun2022 prerequisite into ${PREFIX_PATH}"
  WINEPREFIX="${PREFIX_PATH}" \
    WINE="${wine}" \
    WINESERVER="${wineserver}" \
    WINEDEBUG="${WINEDEBUG:--all}" \
    winetricks -q vcrun2022 || warn "winetricks vcrun2022 failed; continuing"
}

windows_z_path() {
  local path="$1"

  printf 'Z:%s\n' "${path//\//\\}"
}

gameinput_redist_ok() {
  [[ -f "${PREFIX_PATH}/drive_c/Program Files/Microsoft GameInput/x64/GameInputRedist.dll" &&
     -f "${PREFIX_PATH}/drive_c/Program Files/Microsoft GameInput/x64/GameInputRedistService.exe" ]]
}

gameinput_registry_marker() {
  printf '%s\n' "${PREFIX_PATH}/.minecraft-bedrock-gameinput-registry"
}

write_gameinput_registry_file() {
  local reg_file="$1"

  require_command python
  mkdir -p "$(dirname "${reg_file}")"
  python - "${reg_file}" <<'PY'
import sys
from pathlib import Path

path = Path(sys.argv[1])
reg = (
    "Windows Registry Editor Version 5.00\r\n\r\n"
    r"[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\GameInput]" "\r\n"
    r'"RedistDir"="C:\\Program Files\\Microsoft GameInput\\x64"' "\r\n\r\n"
    r"[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\GameInput]" "\r\n"
    r'"RedistDir"="C:\\Program Files\\Microsoft GameInput\\x64"' "\r\n\r\n"
    r"[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\GameInputRedistService]" "\r\n"
    r'"DisplayName"="GameInput Redist Service"' "\r\n"
    r'"Description"="GameInput Redist Service"' "\r\n"
    r'"ImagePath"="C:\\Program Files\\Microsoft GameInput\\x64\\GameInputRedistService.exe"' "\r\n"
    r'"ObjectName"="LocalSystem"' "\r\n"
    r'"ErrorControl"=dword:00000000' "\r\n"
    r'"Start"=dword:00000003' "\r\n"
    r'"Type"=dword:00000010' "\r\n"
)
path.write_text(reg, encoding="utf-16")
PY
}

import_gameinput_registry() {
  local reg_file="${CACHE_DIR}/gameinput.reg"
  local marker

  [[ -d "${PREFIX_PATH}/drive_c/windows/system32" ]] || cmd_init_prefix
  write_gameinput_registry_file "${reg_file}"
  marker="$(gameinput_registry_marker)"
  if ! run_proton_wait reg.exe import "$(windows_z_path "${reg_file}")" >/dev/null; then
    return 1
  fi
  printf 'installed\n' > "${marker}"
}

extract_gameinput_redist() {
  local msi="$1"

  require_command python
  python - "${msi}" "${PREFIX_PATH}" <<'PY'
import struct
import sys
import zlib
from pathlib import Path

msi_path = Path(sys.argv[1])
prefix = Path(sys.argv[2])


def gameinput_redist_ok():
    return (
        prefix.joinpath(
            "drive_c/Program Files/Microsoft GameInput/x64/GameInputRedist.dll"
        ).exists()
        and prefix.joinpath(
            "drive_c/Program Files/Microsoft GameInput/x64/GameInputRedistService.exe"
        ).exists()
    )


def msi_embedded_cab(msi):
    if msi[:8] != bytes.fromhex("d0cf11e0a1b11ae1"):
        return None
    unpack = struct.unpack_from
    sector_size = 1 << unpack("<H", msi, 0x1E)[0]
    mini_sector_size = 1 << unpack("<H", msi, 0x20)[0]
    dir0 = unpack("<I", msi, 0x30)[0]
    mini_cutoff = unpack("<I", msi, 0x38)[0]
    mini_fat0 = unpack("<I", msi, 0x3C)[0]
    difat0 = unpack("<I", msi, 0x44)[0]
    difat_count = unpack("<I", msi, 0x48)[0]
    free = 0xFFFFFFFF
    end_chain = 0xFFFFFFFE

    def sector(number):
        start = (number + 1) * sector_size
        return msi[start:start + sector_size]

    difat = list(unpack("<109I", msi, 0x4C))
    next_sector = difat0
    for _ in range(difat_count):
        if next_sector in (free, end_chain):
            break
        values = list(unpack(f"<{sector_size // 4}I", sector(next_sector), 0))
        difat += values[:-1]
        next_sector = values[-1]

    fat = []
    for fat_sector in (entry for entry in difat if entry != free):
        fat += list(unpack(f"<{sector_size // 4}I", sector(fat_sector), 0))

    def chain(start):
        out = []
        number = start
        seen = set()
        while number not in (end_chain, free) and number < len(fat) and number not in seen:
            seen.add(number)
            out.append(number)
            number = fat[number]
        return out

    def read_big(start, size):
        return b"".join(sector(number) for number in chain(start))[:size]

    directory_chain = chain(dir0)
    directory = read_big(dir0, len(directory_chain) * sector_size)
    entries = []
    for index in range(0, len(directory), 128):
        entry = directory[index:index + 128]
        if len(entry) < 128:
            break
        if unpack("<H", entry, 64)[0]:
            entries.append((entry[66], unpack("<I", entry, 116)[0], unpack("<Q", entry, 120)[0]))

    root = next((entry for entry in entries if entry[0] == 5), None)
    if not root:
        return None

    mini_stream = read_big(root[1], root[2])
    mini_fat = []
    for mini_sector in chain(mini_fat0):
        mini_fat += list(unpack(f"<{sector_size // 4}I", sector(mini_sector), 0))

    def read_mini(start, size):
        out = b""
        number = start
        seen = set()
        while number not in (end_chain, free) and number < len(mini_fat) and number not in seen:
            seen.add(number)
            out += mini_stream[number * mini_sector_size:(number + 1) * mini_sector_size]
            number = mini_fat[number]
        return out[:size]

    for kind, start, size in entries:
        if kind != 2 or size < 4:
            continue
        payload = read_big(start, size) if size >= mini_cutoff else read_mini(start, size)
        if payload[:4] == b"MSCF":
            return payload
    return None


def cab_payload(cab):
    if not cab or cab[:4] != b"MSCF":
        return []
    unpack = struct.unpack_from
    coff_files = unpack("<I", cab, 16)[0]
    folder_count, file_count, flags = unpack("<HHH", cab, 26)
    offset = 36
    cb_folder = 0
    cb_data = 0
    if flags & 4:
        cb_header, cb_folder, cb_data = unpack("<HBB", cab, offset)
        offset += 4 + cb_header

    folders = []
    for _ in range(folder_count):
        coff, data_count, _kind = unpack("<IHH", cab, offset)
        offset += 8 + cb_folder
        folders.append((coff, data_count))

    files = []
    pointer = coff_files
    for _ in range(file_count):
        cb, uncompressed_offset, folder_index = unpack("<IIH", cab, pointer)
        pointer += 16
        pointer = cab.index(b"\x00", pointer) + 1
        files.append((cb, uncompressed_offset, folder_index))

    folder_data = []
    for coff, data_count in folders:
        pointer = coff
        out = b""
        previous = b""
        for _ in range(data_count):
            compressed_size = unpack("<IHH", cab, pointer)[1]
            pointer += 8 + cb_data
            block = cab[pointer:pointer + compressed_size]
            pointer += compressed_size
            if block[:2] != b"CK":
                return []
            decompressor = zlib.decompressobj(-15, zdict=previous[-32768:] if previous else b"")
            out += decompressor.decompress(block[2:]) + decompressor.flush()
            previous = out
        folder_data.append(out)

    return [
        (size, folder_data[folder_index][uncompressed_offset:uncompressed_offset + size])
        for size, uncompressed_offset, folder_index in files
    ]


def pe_kind(data):
    if data[:2] != b"MZ" or len(data) < 0x40:
        return None
    pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
    if pe_offset + 24 > len(data) or data[pe_offset:pe_offset + 4] != b"PE\0\0":
        return None
    characteristics = struct.unpack_from("<H", data, pe_offset + 22)[0]
    return "dll" if characteristics & 0x2000 else "exe"


cab = msi_embedded_cab(msi_path.read_bytes())
payloads = [
    (len(data), kind, data)
    for _size, data in cab_payload(cab)
    for kind in [pe_kind(data)]
    if kind
]
dlls = sorted((data for _size, kind, data in payloads if kind == "dll"), key=len, reverse=True)
exes = sorted((data for _size, kind, data in payloads if kind == "exe"), key=len, reverse=True)

if not dlls or not exes:
    raise SystemExit("could not identify GameInput payloads in GameInputRedist.msi")

x64 = prefix / "drive_c/Program Files/Microsoft GameInput/x64"
x86 = prefix / "drive_c/Program Files/Microsoft GameInput/x86"
system32 = prefix / "drive_c/windows/system32"
x64.mkdir(parents=True, exist_ok=True)
system32.mkdir(parents=True, exist_ok=True)

(x64 / "GameInputRedist.dll").write_bytes(dlls[0])
(system32 / "GameInputRedist.dll").write_bytes(dlls[0])
(x64 / "GameInputRedistService.exe").write_bytes(exes[0])
if len(dlls) >= 2:
    (x64 / "GameInputBridge.dll").write_bytes(dlls[1])
if len(exes) >= 2:
    (x64 / "GameInputRawInputProxy.exe").write_bytes(exes[1])
if len(dlls) >= 3:
    x86.mkdir(parents=True, exist_ok=True)
    (x86 / "GameInputRedist.dll").write_bytes(dlls[2])

if not gameinput_redist_ok():
    raise SystemExit("GameInput extraction did not produce expected files")
PY
}

game_dir_for_gameinput() {
  local source="${1:-}"
  local exe root

  if [[ -n "${source}" ]]; then
    if [[ -f "${source}" && "$(basename "${source}")" == "Minecraft.Windows.exe" ]]; then
      dirname "${source}"
      return 0
    fi
    if [[ -d "${source}" ]]; then
      root="$(find_game_root_in "${source}")" || return 1
      printf '%s\n' "${root}"
      return 0
    fi
    return 1
  fi

  exe="$(find_game_exe || true)"
  [[ -n "${exe}" ]] || return 1
  dirname "${exe}"
}

cmd_install_gameinput() {
  local source="${1:-}"
  local game_dir msi marker

  marker="$(gameinput_registry_marker)"
  if gameinput_redist_ok; then
    if [[ ! -f "${marker}" ]]; then
      if ! import_gameinput_registry; then
        warn "could not import GameInput registry entries"
        return 1
      fi
    fi
    info "Using existing Microsoft GameInput redist"
    return 0
  fi

  game_dir="$(game_dir_for_gameinput "${source}")" || die "Minecraft.Windows.exe was not found; install or import a GDK game archive first"
  msi="${game_dir}/Installers/GameInputRedist.msi"
  if [[ ! -f "${msi}" ]]; then
    warn "GameInputRedist.msi was not found in ${game_dir}/Installers"
    warn "Minecraft may show a missing component prompt on first launch."
    return 0
  fi

  [[ -d "${PREFIX_PATH}/drive_c/windows/system32" ]] || cmd_init_prefix
  info "Installing Microsoft GameInput redist from ${msi}"
  if ! extract_gameinput_redist "${msi}"; then
    return 1
  fi
  if ! import_gameinput_registry; then
    warn "could not import GameInput registry entries"
    return 1
  fi

  if gameinput_redist_ok; then
    info "Installed Microsoft GameInput redist"
  else
    warn "Microsoft GameInput redist install did not produce expected files"
    return 1
  fi
}

cmd_install_launcher() {
  local installer="${1:-}"
  local explicit_installer=0
  local lower
  local launcher game

  if [[ -n "${installer}" ]]; then
    explicit_installer=1
  elif [[ -n "${MINECRAFT_BEDROCK_INSTALLER:-}" ]]; then
    installer="${MINECRAFT_BEDROCK_INSTALLER}"
    explicit_installer=1
  else
    installer="${INSTALLER_PATH}"
  fi

  if [[ ! -f "${installer}" ]]; then
    if [[ "${explicit_installer}" == "1" ]]; then
      die "installer not found: ${installer}"
    fi
    cmd_download_installer
  fi

  [[ -f "${installer}" ]] || die "installer not found: ${installer}"

  lower="${installer,,}"
  info "Running Minecraft installer in Proton: ${installer}"
  if [[ "${lower}" == *.msi ]]; then
    require_graphical_env
    run_proton_wait msiexec.exe /i "${installer}"
  else
    require_graphical_env
    installer="$(stage_exe_installer "${installer}")"
    info "Staged GameCore installer with WinRT contracts: ${installer}"
    info "If the Minecraft installer window opens, complete or close it; setup continues after it exits."
    run_proton_wait "${installer}"
  fi

  launcher="$(find_launcher_exe || true)"
  game="$(find_game_exe || true)"
  if [[ -z "${launcher}" && -z "${game}" ]]; then
    warn "The Minecraft installer exited, but no installed launcher or game executable was found in ${PREFIX_PATH}."
    warn "The current GameCore installer depends on Microsoft Store install APIs that may fail under Wine/Proton."
    return 1
  fi
}

cmd_configure_launcher() {
  local settings_path="${PREFIX_PATH}/drive_c/users/steamuser/AppData/Roaming/.minecraft/launcher_settings.json"
  local options=()

  if [[ "${MINECRAFT_BEDROCK_DISABLE_GPU:-1}" == "1" ]]; then
    if [[ -n "${MINECRAFT_BEDROCK_CEF_OPTIONS:-}" ]]; then
      read -r -a options <<< "${MINECRAFT_BEDROCK_CEF_OPTIONS}"
    else
      options=("${DEFAULT_CEF_OPTIONS[@]}")
    fi
  fi

  mkdir -p "$(dirname "${settings_path}")"
  info "Writing launcher Wine/Proton settings to ${settings_path}"
  python - "${settings_path}" "${MINECRAFT_BEDROCK_DISABLE_GPU:-1}" "${options[@]}" <<'PY'
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
disable_gpu = sys.argv[2] == "1"
cef_options = sys.argv[3:]

try:
    settings = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
    settings = {}
except json.JSONDecodeError:
    settings = {}

settings.setdefault("channel", "release")
settings.setdefault("customChannels", [])
settings.setdefault("formatVersion", 0)
settings.setdefault("locale", "en-US")
settings.setdefault("quickPlayEnabled", True)
settings.setdefault("useArm64JreIfSupported", False)
settings.setdefault("useMagnifiedMode", False)
settings.setdefault("version", 17)

if disable_gpu:
    settings["disableGPU"] = True
    settings["additionalCEFOptions"] = list(dict.fromkeys(cef_options))
else:
    settings.pop("disableGPU", None)
    settings.pop("additionalCEFOptions", None)

path.write_text(json.dumps(settings, indent=2, sort_keys=False) + "\n", encoding="utf-8")
PY
}

patch_libhttpclient_xcurl_gate() {
  local game_dir="$1"
  local dll="${game_dir}/libHttpClient.GDK.dll"

  [[ -f "${dll}" ]] || return 0
  require_command python
  python - "${dll}" <<'PY'
import re
import shutil
import sys
from pathlib import Path

path = Path(sys.argv[1])
data = bytearray(path.read_bytes())
pattern = re.compile(
    rb"\x83\xc0\xfe\xba\x04\x00\x00\x00\x48\x8d\x0d.{4}\x83\xf8\x06"
    rb"\x0f\x87.{4}",
    re.S,
)
match = pattern.search(data)
if not match:
    if b"\x83\xc0\xfe\xba\x04\x00\x00\x00" in data and b"\x90" * 6 in data:
        print("libHttpClient XCurl provider gate already patched", file=sys.stderr)
        raise SystemExit(0)
    print("libHttpClient XCurl provider gate not found", file=sys.stderr)
    raise SystemExit(1)

offset = match.start() + 18
if bytes(data[offset:offset + 6]) == b"\x90" * 6:
    print("libHttpClient XCurl provider gate already patched", file=sys.stderr)
    raise SystemExit(0)
if bytes(data[offset:offset + 2]) != b"\x0f\x87":
    print("libHttpClient XCurl provider gate anchor misaligned", file=sys.stderr)
    raise SystemExit(1)

backup = path.with_suffix(path.suffix + ".minecraft-bedrock.bak")
if not backup.exists():
    shutil.copy2(path, backup)
data[offset:offset + 6] = b"\x90" * 6
tmp = path.with_suffix(path.suffix + ".patched")
tmp.write_bytes(data)
tmp.replace(path)
print("patched libHttpClient to force XCurl provider", file=sys.stderr)
PY
}

bump_game_stack_reserve() {
  local exe="$1"

  [[ -f "${exe}" ]] || return 0
  require_command python
  python - "${exe}" <<'PY'
import shutil
import struct
import sys
from pathlib import Path

path = Path(sys.argv[1])
target = 0x1000000
with path.open("r+b") as f:
    head = f.read(0x400)
    if head[:2] != b"MZ":
        raise SystemExit(0)
    pe = struct.unpack_from("<I", head, 0x3C)[0]
    if head[pe:pe + 4] != b"PE\0\0":
        raise SystemExit(0)
    optional = pe + 4 + 20
    if struct.unpack_from("<H", head, optional)[0] != 0x20B:
        raise SystemExit(0)
    field = optional + 72
    current = struct.unpack_from("<Q", head, field)[0]
    if current >= target:
        raise SystemExit(0)
    backup = path.with_suffix(path.suffix + ".stack.minecraft-bedrock.bak")
    if not backup.exists():
        shutil.copy2(path, backup)
    f.seek(field)
    f.write(struct.pack("<Q", target))
print(f"raised Minecraft stack reserve from {current // 1024} KiB to {target // 1024} KiB", file=sys.stderr)
PY
}

prepare_game_launch_env() {
  local exe="$1"
  local gnutls_config="${APP_HOME}/etc/gnutls-no-tls13.cfg"
  local overrides=(
    "vrclient="
    "vrclient_x64="
    "openvr_api="
    "wineopenxr="
    "amd_ags_x64="
  )

  bump_game_stack_reserve "${exe}" || warn "could not adjust Minecraft stack reserve; continuing"

  export MICROSOFT_WINDOWSAPPRUNTIME_BOOTSTRAP_INITIALIZE_SHOWUI=0
  export MICROSOFT_WINDOWSAPPRUNTIME_BOOTSTRAP_INITIALIZE_FAILFAST=0
  export MICROSOFT_WINDOWSAPPRUNTIME_DEPLOYMENT_INITIALIZE_ONERRORSHOWUI=0
  if [[ -n "${WINEDLLOVERRIDES:-}" ]]; then
    overrides+=("${WINEDLLOVERRIDES}")
  fi
  export WINEDLLOVERRIDES
  WINEDLLOVERRIDES="$(IFS=';'; printf '%s' "${overrides[*]}")"

  mkdir -p "$(dirname "${gnutls_config}")" "${STATE_DIR}/logs"
  if [[ ! -f "${gnutls_config}" ]]; then
    printf '[priorities]\nSYSTEM = NORMAL:-VERS-TLS1.3:%%COMPAT\n' > "${gnutls_config}"
  fi
  export GNUTLS_SYSTEM_PRIORITY_FILE="${gnutls_config}"
  export GNUTLS_SYSTEM_PRIORITY_FAIL_ON_INVALID=0
  export PROTON_LOG="${PROTON_LOG:-1}"
  export PROTON_LOG_DIR="${PROTON_LOG_DIR:-${STATE_DIR}/logs}"
  if [[ "${MINECRAFT_BEDROCK_DIAGNOSTICS:-0}" == "1" && -z "${WINEDEBUG:-}" ]]; then
    export WINEDEBUG="+seh,+loaddll,+module,+xgameruntime,+gdkc,+winhttp"
  fi
}

find_launcher_exe() {
  local candidate
  local candidates=(
    "${PREFIX_PATH}/drive_c/Program Files (x86)/Minecraft Launcher/MinecraftLauncher.exe"
    "${PREFIX_PATH}/drive_c/Program Files/Minecraft Launcher/MinecraftLauncher.exe"
    "${PREFIX_PATH}/drive_c/Program Files (x86)/Minecraft Launcher/Minecraft.exe"
    "${PREFIX_PATH}/drive_c/Program Files/Minecraft Launcher/Minecraft.exe"
  )

  for candidate in "${candidates[@]}"; do
    if [[ -f "${candidate}" ]]; then
      printf '%s\n' "${candidate}"
      return 0
    fi
  done

  [[ -d "${PREFIX_PATH}/drive_c" ]] || return 1
  find "${PREFIX_PATH}/drive_c" -type f \( -iname 'MinecraftLauncher.exe' -o -iname 'Minecraft.exe' \) -print -quit
}

find_game_exe() {
  local exe

  while IFS= read -r -d '' exe; do
    printf '%s\n' "${exe}"
    return 0
  done < <(find_game_exes)

  return 1
}

find_game_exes() {
  local base exe
  declare -A seen=()

  for base in "${CONTENT_PATH}" "${GAMES_DIR}" "${PREFIX_PATH}/drive_c"; do
    [[ -d "${base}" ]] || continue
    while IFS= read -r -d '' exe; do
      [[ -n "${seen[${exe}]:-}" ]] && continue
      seen["${exe}"]=1
      printf '%s\0' "${exe}"
    done < <(find "${base}" -type f -iname 'Minecraft.Windows.exe' -print0 2>/dev/null || true)
  done
}

cmd_patch_online() {
  local package_path ca_path tmp dll dep dep_path exe dir found=0

  require_command curl
  require_command bsdtar
  mkdir -p "${CACHE_DIR}"

  package_path="${CACHE_DIR}/$(basename "${MSYS2_CURL_URL}")"
  ca_path="${CACHE_DIR}/ca-bundle.crt"

  [[ -f "${package_path}" ]] || download_file "${MSYS2_CURL_URL}" "${package_path}"
  [[ -f "${ca_path}" ]] || download_file "${CA_BUNDLE_URL}" "${ca_path}"

  tmp="$(mktemp -d "${CACHE_DIR}/msys2-curl.XXXXXX")"
  bsdtar -xf "${package_path}" -C "${tmp}"
  dll="${tmp}/mingw64/bin/libcurl-4.dll"
  [[ -f "${dll}" ]] || die "MSYS2 curl package did not contain mingw64/bin/libcurl-4.dll"

  for dep in "${GDK_DEPS_DLLS[@]}"; do
    dep_path="${CACHE_DIR}/gdk-deps-${dep}"
    [[ -f "${dep_path}" ]] || download_file "${GDK_DEPS_URL}/${dep}" "${dep_path}"
  done

  while IFS= read -r -d '' exe; do
    found=1
    dir="$(dirname "${exe}")"
    info "Patching online support files in ${dir}"

    for dep in "${GDK_DEPS_DLLS[@]}"; do
      dep_path="${CACHE_DIR}/gdk-deps-${dep}"
      if [[ -e "${dir}/${dep}" && ! -e "${dir}/${dep}.minecraft-bedrock.bak" ]]; then
        cp -a "${dir}/${dep}" "${dir}/${dep}.minecraft-bedrock.bak"
      fi
      install -Dm644 "${dep_path}" "${dir}/${dep}"
    done
    patch_libhttpclient_xcurl_gate "${dir}" || warn "could not patch libHttpClient.GDK.dll; continuing"

    for dep in XCurl.dll Xcurl.dll; do
      if [[ -e "${dir}/${dep}" && ! -e "${dir}/${dep}.minecraft-bedrock.bak" ]]; then
        cp -a "${dir}/${dep}" "${dir}/${dep}.minecraft-bedrock.bak"
      fi
      install -Dm644 "${dll}" "${dir}/${dep}"
    done
    install -Dm644 "${ca_path}" "${dir}/etc/ssl/certs/ca-bundle.crt"
    install -Dm644 "${ca_path}" "${dir}/../etc/ssl/certs/ca-bundle.crt"
  done < <(find_game_exes)

  rm -rf "${tmp}"

  if [[ "${found}" == "0" ]]; then
    warn "Minecraft.Windows.exe was not found. Install Bedrock in the launcher, then rerun \`minecraft-bedrock patch-online\`."
    return 0
  fi
}

shortcut_helper() {
  local script_dir
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

  if [[ -x "${INSTALLED_SHORTCUT_HELPER}" ]]; then
    printf '%s\n' "${INSTALLED_SHORTCUT_HELPER}"
  elif [[ -x "${script_dir}/minecraft-bedrock-steam-shortcut.py" ]]; then
    printf '%s\n' "${script_dir}/minecraft-bedrock-steam-shortcut.py"
  elif [[ -f "${script_dir}/minecraft-bedrock-steam-shortcut.py" ]]; then
    printf '%s\n' "${script_dir}/minecraft-bedrock-steam-shortcut.py"
  else
    die "Steam shortcut helper not found"
  fi
}

cmd_add_steam_shortcut() {
  local helper steam_root exe user_args=()

  helper="$(shortcut_helper)"
  steam_root="$(find_steam_root)"
  exe="$(command -v minecraft-bedrock || true)"
  [[ -n "${exe}" ]] || exe="/usr/bin/minecraft-bedrock"

  if [[ -n "${MINECRAFT_BEDROCK_STEAM_USER_ID:-}" ]]; then
    user_args+=(--user-id "${MINECRAFT_BEDROCK_STEAM_USER_ID}")
  fi

  python "${helper}" add \
    --steam-root "${steam_root}" \
    "${user_args[@]}" \
    --name "${STEAM_SHORTCUT_NAME}" \
    --exe "${exe}" \
    --start-dir "$(dirname "${exe}")" \
    --launch-options "launch" \
    --tag Minecraft \
    --tag Bedrock \
    --tag Proton \
    "$@"
}

cmd_remove_steam_shortcut() {
  local helper steam_root exe user_args=()

  helper="$(shortcut_helper)"
  steam_root="$(find_steam_root)"
  exe="$(command -v minecraft-bedrock || true)"
  [[ -n "${exe}" ]] || exe="/usr/bin/minecraft-bedrock"

  if [[ -n "${MINECRAFT_BEDROCK_STEAM_USER_ID:-}" ]]; then
    user_args+=(--user-id "${MINECRAFT_BEDROCK_STEAM_USER_ID}")
  fi

  python "${helper}" remove \
    --steam-root "${steam_root}" \
    "${user_args[@]}" \
    --name "${STEAM_SHORTCUT_NAME}" \
    --exe "${exe}" \
    "$@"
}

cmd_launch() {
  local target="${1:-auto}"
  local exe=""
  local args=()
  local arg

  case "${target}" in
    auto)
      exe="$(find_game_exe || true)"
      [[ -n "${exe}" ]] || exe="$(find_launcher_exe || true)"
      ;;
    launcher)
      exe="$(find_launcher_exe || true)"
      ;;
    game)
      exe="$(find_game_exe || true)"
      ;;
    installer)
      cmd_install_launcher
      return $?
      ;;
    *)
      die "unknown launch target: ${target}"
      ;;
  esac

  if [[ -z "${exe}" && "${target}" == "auto" ]]; then
    warn "No installed launcher or game executable was found; running the Minecraft installer instead."
    cmd_install_launcher
    return $?
  fi

  [[ -n "${exe}" ]] || die "launch target not found. Run \`minecraft-bedrock install-launcher\` first."
  if [[ "${target}" == "launcher" || "${exe}" == *"MinecraftLauncher.exe" ]]; then
    while IFS= read -r -d '' arg; do
      args+=("${arg}")
    done < <(launcher_args)
  fi

  if [[ "${#args[@]}" -gt 0 ]]; then
    info "Launching ${exe} ${args[*]}"
  else
    info "Launching ${exe}"
  fi
  require_graphical_env
  if [[ "$(basename "${exe}")" == "Minecraft.Windows.exe" ]]; then
    prefer_gdk_proton_for_game
    patch_gdk_proton_runtime
    cmd_install_gameinput "$(dirname "${exe}")" || warn "GameInput setup failed; continuing launch"
    prepare_game_launch_env "${exe}"
    (cd "$(dirname "${exe}")" && run_proton_wait "${exe}" "${args[@]}")
    return $?
  fi
  run_proton_wait "${exe}" "${args[@]}"
}

cmd_paths() {
  local steam_root proton launcher game

  steam_root="$(try_find_steam_root || true)"
  proton="$(find_installed_proton || true)"
  launcher="$(find_launcher_exe || true)"
  game="$(find_game_exe || true)"

  printf 'Steam root: %s\n' "${steam_root:-not found}"
  printf 'Proton: %s\n' "${proton:-not found}"
  printf 'Compatdata: %s\n' "${COMPAT_DATA_PATH}"
  printf 'Prefix: %s\n' "${PREFIX_PATH}"
  printf 'Installer: %s\n' "${INSTALLER_PATH}"
  printf 'Installer runtime: %s\n' "${INSTALLER_RUNTIME_DIR}"
  printf 'WinRT contracts: %s\n' "${WINRT_CONTRACTS_DIR}"
  printf 'Games: %s\n' "${GAMES_DIR}"
  printf 'Content: %s\n' "${CONTENT_PATH}"
  printf 'Launcher: %s\n' "${launcher:-not found}"
  printf 'Game: %s\n' "${game:-not found}"
}

cmd_setup() {
  local installer_option="--gamecore"
  local game_archive_tag="${GAME_ARCHIVE_VERSION}"
  local installer="${INSTALLER_PATH}"
  local init_before_prereqs=1
  local launch_after=0
  local reset_before=0
  local reset_args=()
  local game

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --game-archive|--archive|--direct-game)
        installer_option="--game-archive"
        ;;
      --installed-game)
        installer_option="--installed-game"
        ;;
      --legacy)
        installer_option="--legacy"
        ;;
      --gamecore|--windows-gdk|--gdk|--win10|--win11)
        installer_option="$1"
        ;;
      --bubbles)
        GAME_ARCHIVE_REPO="${BUBBLES_GAME_ARCHIVE_REPO}"
        installer_option="--game-archive"
        ;;
      --repo|--game-archive-repo)
        shift
        [[ $# -gt 0 && -n "$1" ]] || die "--repo requires a GitHub owner/repo value"
        GAME_ARCHIVE_REPO="$1"
        installer_option="--game-archive"
        ;;
      --url|--game-archive-url)
        shift
        [[ $# -gt 0 && -n "$1" ]] || die "--url requires a game archive URL"
        GAME_ARCHIVE_URL="$1"
        installer_option="--game-archive"
        ;;
      --version|--tag)
        shift
        [[ $# -gt 0 && -n "$1" ]] || die "--version requires a release tag"
        game_archive_tag="$1"
        GAME_ARCHIVE_VERSION="$1"
        ;;
      --sha256|--game-archive-sha256)
        shift
        [[ $# -gt 0 && -n "$1" ]] || die "--sha256 requires a digest"
        GAME_ARCHIVE_SHA256="$1"
        ;;
      --include-prerelease)
        GAME_ARCHIVE_INCLUDE_PRERELEASE=1
        ;;
      --reset|--purge)
        reset_before=1
        ;;
      --launch)
        launch_after=1
        ;;
      --no-launch)
        launch_after=0
        ;;
      -h|--help)
        usage
        return 0
        ;;
      --keep-cache|--keep-proton|--keep-shortcut)
        reset_args+=("$1")
        ;;
      --)
        shift
        break
        ;;
      -*)
        die "unknown setup option: $1"
        ;;
      *)
        if [[ "${installer_option}" == "--game-archive" ]]; then
          game_archive_tag="$1"
          GAME_ARCHIVE_VERSION="$1"
        else
          die "unexpected setup argument: $1"
        fi
        ;;
    esac
    shift
  done

  [[ $# -eq 0 ]] || die "unexpected setup argument: $1"

  if [[ "${reset_before}" == "1" ]]; then
    cmd_purge --yes "${reset_args[@]}"
  fi

  case "${installer_option}" in
    --game-archive|--archive|--direct-game)
      prefer_gdk_proton_for_game
      cmd_ensure_proton
      patch_gdk_proton_runtime
      cmd_download_game "${game_archive_tag}"
      cmd_init_prefix
      cmd_install_prereqs --gamecore
      game="$(find_game_exe || true)"
      [[ -n "${game}" ]] || die "Minecraft.Windows.exe was not installed"
      cmd_install_gameinput "$(dirname "${game}")"
      cmd_patch_online
      cmd_add_steam_shortcut
      info "Setup complete. Restart Steam before using the new non-Steam shortcut."
      if [[ "${launch_after}" == "1" ]]; then
        cmd_launch game
      fi
      return 0
      ;;
    --installed-game)
      prefer_gdk_proton_for_game
      cmd_ensure_proton
      patch_gdk_proton_runtime
      cmd_init_prefix
      cmd_install_prereqs --gamecore
      game="$(find_game_exe || true)"
      [[ -n "${game}" ]] || die "Minecraft.Windows.exe was not found. Run \`minecraft-bedrock install-game <path>\` first."
      cmd_install_gameinput "$(dirname "${game}")"
      cmd_patch_online
      cmd_add_steam_shortcut
      info "Setup complete. Restart Steam before using the new non-Steam shortcut."
      if [[ "${launch_after}" == "1" ]]; then
        cmd_launch game
      fi
      return 0
      ;;
    --legacy)
      installer="${MINECRAFT_BEDROCK_INSTALLER:-${LEGACY_INSTALLER_PATH}}"
      ;;
    --gamecore|--windows-gdk|--gdk|--win10|--win11)
      installer="${MINECRAFT_BEDROCK_INSTALLER:-${INSTALLER_PATH}}"
      if [[ "${MINECRAFT_BEDROCK_USE_NATIVE_DOTNET:-0}" == "1" && "${MINECRAFT_BEDROCK_SKIP_DOTNET:-0}" != "1" && "${MINECRAFT_BEDROCK_SKIP_WINETRICKS:-0}" != "1" ]]; then
        init_before_prereqs=0
      fi
      ;;
    *)
      die "unknown setup option: ${installer_option}"
      ;;
  esac

  cmd_ensure_proton
  cmd_download_installer "${installer_option}"
  if [[ "${init_before_prereqs}" == "1" ]]; then
    cmd_init_prefix
  else
    info "Installing native .NET before Proton initializes the prefix; native .NET is fragile in already-initialized Proton prefixes."
  fi
  cmd_install_prereqs "${installer_option}"
  if [[ "${init_before_prereqs}" != "1" ]]; then
    cmd_init_prefix
  fi
  if ! cmd_install_launcher "${installer}"; then
    die "Minecraft launcher was not installed; not adding a Steam shortcut yet."
  fi
  cmd_configure_launcher
  cmd_patch_online
  cmd_add_steam_shortcut
  info "Setup complete. Restart Steam before using the new non-Steam shortcut."
  if [[ "${launch_after}" == "1" ]]; then
    cmd_launch
  fi
}

collect_managed_pids() {
  local proc pid proc_uid cmdline environ haystack
  local needle
  local needles=(
    "${APP_HOME}"
    "${CACHE_DIR}"
    "${COMPAT_DATA_PATH}"
    "${PREFIX_PATH}"
  )

  for proc in /proc/[0-9]*; do
    [[ -d "${proc}" ]] || continue
    pid="${proc##*/}"
    [[ "${pid}" != "$$" && "${pid}" != "${BASHPID}" ]] || continue

    proc_uid="$(stat -c '%u' "${proc}" 2>/dev/null || true)"
    [[ "${proc_uid}" == "${UID}" ]] || continue

    cmdline="$({ tr '\0' ' ' < "${proc}/cmdline"; } 2>/dev/null || true)"
    environ="$({ tr '\0' '\n' < "${proc}/environ"; } 2>/dev/null || true)"
    haystack="${cmdline}"$'\n'"${environ}"

    for needle in "${needles[@]}"; do
      [[ -n "${needle}" ]] || continue
      if [[ "${haystack}" == *"${needle}"* ]]; then
        printf '%s\n' "${pid}"
        break
      fi
    done
  done | sort -n -u
}

cmd_stop() {
  local proton_dir wineserver pid pids=() alive=()

  if [[ -d "${PREFIX_PATH}" ]]; then
    proton_dir="$(find_installed_proton || true)"
    wineserver="${proton_dir}/files/bin/wineserver"
    if [[ -n "${proton_dir}" && -x "${wineserver}" ]]; then
      info "Stopping Wine processes for ${PREFIX_PATH}"
      WINEPREFIX="${PREFIX_PATH}" \
        WINEDEBUG="${WINEDEBUG:--all}" \
        "${wineserver}" -k || warn "wineserver -k failed; continuing"
    fi
  fi

  while IFS= read -r pid; do
    pids+=("${pid}")
  done < <(collect_managed_pids)

  if [[ "${#pids[@]}" -eq 0 ]]; then
    info "No managed Wine/Proton processes found."
    return 0
  fi

  info "Stopping managed process(es): ${pids[*]}"
  kill -TERM "${pids[@]}" 2>/dev/null || true
  sleep 2

  for pid in "${pids[@]}"; do
    if kill -0 "${pid}" 2>/dev/null; then
      alive+=("${pid}")
    fi
  done

  if [[ "${#alive[@]}" -gt 0 ]]; then
    warn "Force-stopping managed process(es): ${alive[*]}"
    kill -KILL "${alive[@]}" 2>/dev/null || true
  fi
}

append_unique_path() {
  local path="$1"
  local existing

  [[ -n "${path}" ]] || return 0

  for existing in "${PURGE_PATHS[@]}"; do
    [[ "${existing}" == "${path}" ]] && return 0
  done

  PURGE_PATHS+=("${path}")
}

append_unique_proton_path() {
  local path="$1"
  local existing

  [[ -n "${path}" ]] || return 0
  [[ -f "${path}/.minecraft-bedrock-managed" ]] || return 0

  for existing in "${PURGE_PROTON_PATHS[@]}"; do
    [[ "${existing}" == "${path}" ]] && return 0
  done

  PURGE_PROTON_PATHS+=("${path}")
}

safe_rm_rf() {
  local path="$1"
  local resolved

  [[ -n "${path}" ]] || return 0
  [[ -e "${path}" || -L "${path}" ]] || return 0

  resolved="$(realpath -m -- "${path}")"
  case "${resolved}" in
    "/"|"${HOME}"|"${HOME}/."|"${HOME}/.."|"/usr"|"/usr/"*|"/etc"|"/etc/"*)
      die "refusing to remove unsafe path: ${resolved}"
      ;;
  esac

  info "Removing ${resolved}"
  rm -rf -- "${resolved}"
}

collect_purge_targets() {
  local keep_cache="$1"
  local keep_proton="$2"
  local steam_root recorded path

  PURGE_PATHS=()
  PURGE_PROTON_PATHS=()

  append_unique_path "${COMPAT_DATA_PATH}"
  append_unique_path "${APP_HOME}"
  append_unique_path "${STATE_DIR}"
  if [[ "${keep_cache}" != "1" ]]; then
    append_unique_path "${CACHE_DIR}"
  fi

  if [[ "${keep_proton}" == "1" ]]; then
    return 0
  fi

  if [[ -f "${STATE_DIR}/gdk-proton-path" ]]; then
    recorded="$(<"${STATE_DIR}/gdk-proton-path")"
    append_unique_proton_path "${recorded}"
  fi

  steam_root="$(try_find_steam_root || true)"
  if [[ -n "${steam_root}" && -d "${steam_root}/compatibilitytools.d" ]]; then
    while IFS= read -r -d '' path; do
      append_unique_proton_path "${path}"
    done < <(find "${steam_root}/compatibilitytools.d" -maxdepth 2 -type f -name '.minecraft-bedrock-managed' -print0 | while IFS= read -r -d '' path; do
      printf '%s\0' "$(dirname "${path}")"
    done)
  fi
}

confirm_purge() {
  local keep_shortcut="$1"
  local path
  local reply

  printf 'minecraft-bedrock purge will remove:\n' >&2
  if [[ "${keep_shortcut}" != "1" ]]; then
    printf '  Steam shortcut: %s\n' "${STEAM_SHORTCUT_NAME}" >&2
  fi
  for path in "${PURGE_PROTON_PATHS[@]}"; do
    printf '  Managed Proton: %s\n' "${path}" >&2
  done
  for path in "${PURGE_PATHS[@]}"; do
    printf '  Path: %s\n' "${path}" >&2
  done
  printf 'Type "purge" to continue: ' >&2
  read -r reply
  [[ "${reply}" == "purge" ]] || die "purge aborted"
}

cmd_purge() {
  local assume_yes=0 keep_cache=0 keep_proton=0 keep_shortcut=0
  local path

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -y|--yes)
        assume_yes=1
        ;;
      --keep-cache)
        keep_cache=1
        ;;
      --keep-proton)
        keep_proton=1
        ;;
      --keep-shortcut)
        keep_shortcut=1
        ;;
      -h|--help)
        usage
        return 0
        ;;
      *)
        die "unknown purge option: $1"
        ;;
    esac
    shift
  done

  collect_purge_targets "${keep_cache}" "${keep_proton}"

  if [[ "${assume_yes}" != "1" ]]; then
    confirm_purge "${keep_shortcut}"
  fi

  cmd_stop || warn "could not stop managed Wine/Proton processes"

  if [[ "${keep_shortcut}" != "1" ]]; then
    cmd_remove_steam_shortcut || warn "could not remove Steam shortcut"
  fi

  for path in "${PURGE_PROTON_PATHS[@]}"; do
    safe_rm_rf "${path}"
  done

  for path in "${PURGE_PATHS[@]}"; do
    safe_rm_rf "${path}"
  done

  info "Purge complete."
}

main() {
  local command="${1:-launch}"
  [[ $# -gt 0 ]] && shift || true

  case "${command}" in
    setup) cmd_setup "$@" ;;
    stop) cmd_stop "$@" ;;
    purge) cmd_purge "$@" ;;
    install-proton) cmd_install_proton "$@" ;;
    download-installer) cmd_download_installer "$@" ;;
    install-winrt-contracts) cmd_install_winrt_contracts "$@" ;;
    patch-installer) cmd_patch_installer "$@" ;;
    init-prefix) cmd_init_prefix "$@" ;;
    install-prereqs) cmd_install_prereqs "$@" ;;
    patch-proton-runtime) prefer_gdk_proton_for_game; patch_gdk_proton_runtime "$@" ;;
    install-gameinput) prefer_gdk_proton_for_game; cmd_ensure_proton; patch_gdk_proton_runtime; cmd_install_gameinput "$@" ;;
    install-launcher) cmd_install_launcher "$@" ;;
    list-game-versions) cmd_list_game_versions "$@" ;;
    download-game) cmd_download_game "$@" ;;
    install-game) cmd_install_game "$@" ;;
    configure-launcher) cmd_configure_launcher "$@" ;;
    patch-online) cmd_patch_online "$@" ;;
    add-steam-shortcut) cmd_add_steam_shortcut "$@" ;;
    launch) cmd_launch "$@" ;;
    paths) cmd_paths "$@" ;;
    help|-h|--help) usage ;;
    *) usage >&2; die "unknown command: ${command}" ;;
  esac
}

main "$@"