ping-rust 0.2.2

Menu-driven installer and manager for the shoes proxy server
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
use std::{
    io::{self, IsTerminal},
    path::{Path, PathBuf},
};

use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand, ValueEnum};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, Input};
use qrcode::{render::unicode, QrCode};
use uuid::Uuid;

use crate::{
    client::{self, ClientFormat},
    config::{
        self, AnyTlsMode, AnyTlsUser, GenerationOptions, GenerationRequest, Protocol,
        ShadowsocksCipher, ShadowsocksMode, SnellCipher,
    },
    deployment, fast_add, install_self,
    installer::{self, InstallMethod},
    menu, operations, self_update,
    service::{self, ServiceAction},
};

/// 构建时注入的 git commit;无 .git 的源码构建为 "unknown"。
pub const GIT_COMMIT: &str = env!("PING_RUST_GIT_COMMIT");

/// `--version` / `-V` 的输出:stdout 第一行保持 `ping-rust <版本>`(已发布版本的 self-update
/// 校验按整行精确比较 stdout),commit 单独输出到 stderr。
pub fn version_output() -> (String, String) {
    (
        format!("ping-rust {}", env!("CARGO_PKG_VERSION")),
        format!("commit {GIT_COMMIT}"),
    )
}

/// 仅当参数恰好为单个 `--version` 或 `-V` 时返回 true。
pub fn is_version_request<I: IntoIterator<Item = String>>(args: I) -> bool {
    let args: Vec<String> = args.into_iter().skip(1).collect();
    args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V")
}

#[derive(Debug, Parser)]
#[command(name = "ping-rust")]
#[command(version, about = "shoes 代理的一键安装与管理工具")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// 打开数字菜单(不带子命令时的默认行为)
    Menu,
    /// 首次安装时零输入部署默认 VLESS-REALITY
    #[command(hide = true)]
    Bootstrap,
    /// 将已校验的当前二进制原子安装到目标目录
    #[command(hide = true)]
    InstallSelf {
        #[arg(long)]
        install_dir: PathBuf,
        #[arg(long)]
        quiet: bool,
        #[arg(long)]
        no_bootstrap: bool,
    },
    /// 安装 shoes
    Install {
        #[arg(long, value_enum, default_value_t = InstallMethod::Release)]
        method: InstallMethod,
    },
    /// 生成服务端配置
    Generate(Box<GenerateArgs>),
    /// 像 233boy 一样快速添加配置并直接输出分享链接
    #[command(alias = "a")]
    Add(AddArgs),
    /// 管理 shoes systemd 服务
    Service {
        #[arg(value_enum)]
        action: ServiceAction,
    },
    /// 查看服务状态并检查 NaiveProxy 测试证书有效期
    Status,
    /// 重新生成 NaiveProxy 自签测试证书(dry-run、事务和受控重启)
    RegenerateTestCertificate {
        /// 配置名称或 UUID;只有一个配置时可省略
        profile: Option<String>,
    },
    /// 查看安装、配置和服务信息
    #[command(alias = "i")]
    Info {
        /// 配置 UUID 或名称;省略时显示全部配置
        profile: Option<String>,
    },
    /// 重新输出配置的分享链接
    Url {
        /// 配置 UUID 或名称;只有一个配置时可省略
        profile: Option<String>,
        /// 覆盖保存的服务器公网 IP 或域名
        #[arg(long)]
        server_address: Option<String>,
    },
    /// 显示配置分享链接的终端二维码
    Qr {
        /// 配置 UUID 或名称;只有一个配置时可省略
        profile: Option<String>,
        /// 覆盖保存的服务器公网 IP 或域名
        #[arg(long)]
        server_address: Option<String>,
    },
    /// 删除一个由 ping-rust 管理的配置
    Delete {
        profile: Uuid,
        /// 跳过确认保护(脚本调用时必需)
        #[arg(long)]
        yes: bool,
    },
    /// 导出客户端配置
    Export {
        #[arg(value_enum)]
        format: ClientFormat,
        /// 配置 UUID;只有一个配置时可省略
        #[arg(long)]
        profile: Option<Uuid>,
        /// VPS 公网域名或 IP
        #[arg(long)]
        server: String,
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// 查看服务日志
    Logs {
        #[arg(short = 'n', long, default_value_t = 100)]
        lines: usize,
    },
    /// 检查 TCP/UDP 端口是否可用
    CheckPort {
        port: u16,
        #[arg(long, value_enum, default_value_t = PortKind::Both)]
        kind: PortKind,
    },
    /// 备份配置
    Backup { output: Option<PathBuf> },
    /// 恢复配置
    Restore { archive: PathBuf },
    /// 开启 BBR
    EnableBbr,
    /// 更新 shoes
    Update {
        #[arg(long, value_enum, default_value_t = InstallMethod::Release)]
        method: InstallMethod,
        /// 明确允许 shoes Release 降级或来源未知的旧安装
        #[arg(long)]
        allow_downgrade: bool,
    },
    /// 更新 ping-rust 自身(不会修改 shoes)
    SelfUpdate {
        /// 安装指定版本,例如 v0.1.2;默认使用最新 Release
        #[arg(long, value_name = "VERSION")]
        version: Option<String>,
        /// 即使版本相同也重新安装
        #[arg(long)]
        force: bool,
    },
    /// 卸载 shoes(默认保留配置)
    Uninstall {
        #[arg(long)]
        purge: bool,
    },
}

#[derive(Debug, Args)]
pub struct AddArgs {
    #[arg(value_enum)]
    pub protocol: Protocol,
    /// 快速添加位置参数端口,例如 `prs add reality 443`
    #[arg(value_name = "PORT", conflicts_with_all = ["port", "random_port"])]
    pub legacy_port: Option<u16>,
    /// 指定监听端口
    #[arg(long, conflicts_with_all = ["legacy_port", "random_port"])]
    pub port: Option<u16>,
    /// 显式要求随机可用端口(未指定端口时本来就是默认行为)
    #[arg(long)]
    pub random_port: bool,
    /// 配置名称;默认自动生成
    #[arg(long)]
    pub name: Option<String>,
    /// 客户端连接使用的服务器公网 IP 或域名
    #[arg(long)]
    pub server_address: Option<String>,
    /// Reality SNI 或 TLS 证书名称
    #[arg(long)]
    pub server_name: Option<String>,
    /// shoes 未安装时自动确认安装
    #[arg(long)]
    pub yes: bool,
    /// stdout 只输出一行分享 URI(Snell v3 无标准 URI,不支持)
    #[arg(long)]
    pub plain: bool,
    /// 显式创建 Shadowsocks 2022 + ShadowTLS v3(TCP-only)
    #[arg(long)]
    pub shadowtls: bool,
    /// NaiveProxy 使用测试自签名证书;生产请提供 --cert/--key
    #[arg(long)]
    pub self_signed: bool,
    /// NaiveProxy 用户名
    #[arg(long)]
    pub username: Option<String>,
    /// NaiveProxy/其它协议密码
    #[arg(long)]
    pub password: Option<String>,
    /// NaiveProxy 服务器证书
    #[arg(long, requires = "key")]
    pub cert: Option<PathBuf>,
    /// NaiveProxy 服务器私钥
    #[arg(long, requires = "cert")]
    pub key: Option<PathBuf>,
    /// NaiveProxy padding(默认开启)
    #[arg(long, conflicts_with = "no_padding")]
    pub padding: bool,
    #[arg(long)]
    pub no_padding: bool,
    #[arg(long, conflicts_with = "no_udp")]
    pub udp: bool,
    #[arg(long = "no-udp", conflicts_with = "udp")]
    pub no_udp: bool,
    /// NaiveProxy 静态 fallback 目录
    #[arg(long)]
    pub fallback: Option<String>,
}

#[derive(Debug, Args)]
pub struct GenerateArgs {
    /// 配置显示名称
    #[arg(long)]
    name: Option<String>,
    #[arg(value_enum)]
    protocol: Protocol,
    #[arg(long, default_value_t = 443)]
    port: u16,
    #[arg(long)]
    output: Option<PathBuf>,
    /// Reality 系列 SNI 或 QUIC/TLS 证书域名;Reality 未指定时随机选择非 Apple 大厂域名
    #[arg(long)]
    server_name: Option<String>,
    /// Reality fallback,格式为 host:port
    #[arg(long)]
    dest: Option<String>,
    /// Reality short ID;不指定时安全随机生成
    #[arg(long)]
    short_id: Option<String>,
    /// Reality 允许的最大时间差(毫秒)
    #[arg(long, default_value_t = 60_000)]
    reality_max_time_diff: u64,
    /// 禁用协议 UDP 支持
    #[arg(long = "no-udp", alias = "disable-udp", conflicts_with = "udp")]
    disable_udp: bool,
    /// 显式启用协议 UDP 支持(默认已启用)
    #[arg(long, conflicts_with = "disable_udp")]
    udp: bool,
    /// Hysteria2/TUIC 的 QUIC endpoint 数;0 表示跟随 shoes 线程数
    #[arg(long, default_value_t = 0)]
    quic_endpoints: usize,
    /// 为 TUIC v5 启用 0-RTT
    #[arg(long)]
    zero_rtt: bool,
    /// Shadowsocks/Snell 加密方式;省略时按协议使用安全默认值
    #[arg(long, value_enum)]
    cipher: Option<ShadowsocksCipher>,
    /// Shadowsocks、Snell 或 SOCKS5 密码;省略时安全随机生成
    #[arg(long)]
    password: Option<String>,
    /// 为 Shadowsocks 启用 ShadowTLS v3(TCP-only)
    #[arg(long)]
    shadowtls: bool,
    /// ShadowTLS v3 密码;省略时安全随机生成
    #[arg(long, requires = "shadowtls")]
    shadowtls_password: Option<String>,
    /// ShadowTLS 远程握手目标,格式为 host:port;默认 SNI:443
    #[arg(long, requires = "shadowtls")]
    handshake: Option<String>,
    /// SOCKS5 用户名;省略时安全随机生成
    #[arg(long)]
    username: Option<String>,
    /// 显式创建无认证 SOCKS5(不推荐用于公网监听)
    #[arg(long, conflicts_with_all = ["username", "password"])]
    no_auth: bool,
    /// AnyTLS 外层安全模式
    #[arg(long, value_enum, default_value_t = AnyTlsMode::default())]
    anytls_mode: AnyTlsMode,
    /// AnyTLS 用户,可重复;格式为 `[名称:]密码`
    #[arg(long = "user")]
    anytls_users: Vec<AnyTlsUser>,
    /// AnyTLS padding 条目,可重复,例如 --padding stop=8 --padding 0=30-30
    #[arg(long = "padding", num_args = 0..=1, default_missing_value = "true")]
    anytls_padding: Vec<String>,
    /// AnyTLS 认证失败 fallback,格式为 host:port
    #[arg(long)]
    fallback: Option<String>,
    /// VLESS-WS-TLS/VMess-WS-TLS 的 WebSocket 路径;不指定时安全随机生成
    #[arg(long)]
    websocket_path: Option<String>,
    /// 使用 TLS 的协议预设所需 PEM 证书;不指定时生成自签名证书
    #[arg(long, requires = "key")]
    cert: Option<PathBuf>,
    /// 与 --cert 配套的 PEM 私钥
    #[arg(long, requires = "cert")]
    key: Option<PathBuf>,
    /// NaiveProxy 使用测试自签名证书
    #[arg(long)]
    self_signed: bool,
    #[arg(long)]
    no_padding: bool,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum PortKind {
    Tcp,
    Udp,
    Both,
}

pub async fn run(cli: Cli) -> Result<()> {
    match cli.command.unwrap_or(Command::Menu) {
        Command::Menu => menu::run().await,
        Command::Bootstrap => {
            if !bootstrap_default_reality().await? {
                println!("检测到已有 shoes 配置,跳过默认 VLESS-REALITY 部署。");
            }
            Ok(())
        }
        Command::InstallSelf {
            install_dir,
            quiet,
            no_bootstrap,
        } => {
            let report = install_self::install(&install_dir, quiet)?;
            println!("安装成功:ping-rust {}", env!("CARGO_PKG_VERSION"));
            if !no_bootstrap {
                if !quiet {
                    println!("正在零输入部署默认 VLESS-REALITY(随机端口)...");
                }
                if crate::utils::is_root()? {
                    bootstrap_default_reality().await?;
                } else {
                    install_self::run_bootstrap_as_root(&report.destination)?;
                }
            }
            println!("管理命令:sudo {}", report.command);
            Ok(())
        }
        Command::Install { method } => {
            let report = installer::install(method, false).await?;
            service::install_unit(false)?;
            println!("{} {}", "shoes 安装成功:".green(), report.version);
            println!("来源:{}", report.source);
            println!("路径:{}", report.destination.display());
            println!("systemd unit 已写入;生成配置后再启动服务。");
            Ok(())
        }
        Command::Generate(args) => {
            let GenerateArgs {
                name,
                protocol,
                port,
                output,
                server_name,
                dest,
                short_id,
                reality_max_time_diff,
                disable_udp,
                udp,
                quic_endpoints,
                zero_rtt,
                cipher,
                password,
                shadowtls,
                shadowtls_password,
                handshake,
                username,
                no_auth,
                anytls_mode,
                mut anytls_users,
                anytls_padding,
                fallback,
                websocket_path,
                cert,
                key,
                self_signed,
                no_padding,
            } = *args;
            if password.is_some()
                && !matches!(
                    protocol,
                    Protocol::Shadowsocks
                        | Protocol::Snell
                        | Protocol::Socks5
                        | Protocol::NaiveProxy
                )
            {
                bail!("--password 仅适用于 Shadowsocks、Snell v3、SOCKS5 或 NaiveProxy");
            }
            if username.is_some() && !matches!(protocol, Protocol::Socks5 | Protocol::NaiveProxy) {
                bail!("--username 仅适用于 SOCKS5 或 NaiveProxy");
            }
            if fallback.is_some() && !matches!(protocol, Protocol::AnyTls | Protocol::NaiveProxy) {
                bail!("--fallback 仅适用于 AnyTLS 或 NaiveProxy");
            }
            if !anytls_padding.is_empty()
                && !matches!(protocol, Protocol::AnyTls | Protocol::NaiveProxy)
            {
                bail!("--padding 仅适用于 AnyTLS 或 NaiveProxy");
            }
            if matches!(protocol, Protocol::NaiveProxy) && server_name.is_none() {
                bail!("NaiveProxy requires --server-name matching the TLS certificate");
            }
            if matches!(protocol, Protocol::NaiveProxy) && udp {
                bail!("NaiveProxy UDP-over-TCP 尚未通过端到端验证,当前版本仅支持 TCP");
            }
            if matches!(protocol, Protocol::NaiveProxy)
                && (!anytls_padding.is_empty() && anytls_padding != ["true"]
                    || no_padding && !anytls_padding.is_empty())
            {
                bail!("NaiveProxy --padding 不需要参数,且不能与 --no-padding 并用");
            }
            let shadowsocks_cipher = cipher.unwrap_or_default();
            let snell_cipher = if matches!(protocol, Protocol::Snell) {
                cipher
                    .map(SnellCipher::from_shadowsocks)
                    .transpose()?
                    .unwrap_or_default()
            } else {
                SnellCipher::default()
            };
            if matches!(protocol, Protocol::AnyTls) && anytls_users.is_empty() {
                anytls_users.push(config::generated_anytls_user("default"));
            }
            let server_name = config::resolve_server_name(server_name, protocol, anytls_mode);
            let output = output.unwrap_or_else(|| PathBuf::from(crate::utils::CONFIG_FILE));
            let managed = output == Path::new(crate::utils::CONFIG_FILE);
            let request = GenerationRequest {
                name,
                protocol,
                port,
                output,
                server_address: None,
                server_name,
                reality_dest: dest,
                certificate: cert,
                certificate_key: key,
                options: GenerationOptions {
                    reality_short_id: short_id,
                    reality_max_time_diff,
                    udp_enabled: udp || !disable_udp,
                    quic_endpoints,
                    tuic_zero_rtt: zero_rtt,
                    shadowsocks_cipher,
                    shadowsocks_password: if matches!(protocol, Protocol::Shadowsocks) {
                        password.clone()
                    } else {
                        None
                    },
                    shadowsocks_mode: if shadowtls {
                        ShadowsocksMode::ShadowTlsV3
                    } else {
                        ShadowsocksMode::Plain
                    },
                    shadowtls_password,
                    shadowtls_handshake: handshake,
                    snell_cipher,
                    snell_password: if matches!(protocol, Protocol::Snell) {
                        password.clone()
                    } else {
                        None
                    },
                    socks5_username: if matches!(protocol, Protocol::Socks5) {
                        username.clone()
                    } else {
                        None
                    },
                    socks5_password: if matches!(protocol, Protocol::Socks5) {
                        password.clone()
                    } else {
                        None
                    },
                    socks5_no_auth: no_auth,
                    anytls_mode,
                    anytls_users,
                    anytls_padding_scheme: (matches!(protocol, Protocol::AnyTls)
                        && !anytls_padding.is_empty())
                    .then_some(anytls_padding),
                    anytls_fallback: if matches!(protocol, Protocol::AnyTls) {
                        fallback.clone()
                    } else {
                        None
                    },
                    websocket_path,
                    naive_username: if matches!(protocol, Protocol::NaiveProxy) {
                        username.clone()
                    } else {
                        None
                    },
                    naive_password: if matches!(protocol, Protocol::NaiveProxy) {
                        password.clone()
                    } else {
                        None
                    },
                    naive_padding: !no_padding,
                    naive_udp_enabled: false,
                    naive_fallback: if matches!(protocol, Protocol::NaiveProxy) {
                        fallback.clone()
                    } else {
                        None
                    },
                    naive_self_signed: self_signed,
                },
            };
            let result = if managed {
                deployment::generate_and_activate(request).await?
            } else {
                config::generate(request).await?
            };
            print_credentials(&result);
            if matches!(protocol, Protocol::Socks5) && no_auth {
                println!("警告:SOCKS5 无认证且无传输加密,公开到公网可能被第三方滥用。");
            }
            if managed {
                println!("{}", "配置验证通过,shoes 已启用并启动。".green());
            }
            Ok(())
        }
        Command::Add(args) => run_add(args).await,
        Command::Service { action } => execute_service(action),
        Command::Status => execute_service(ServiceAction::Status),
        Command::RegenerateTestCertificate { profile } => {
            let state = config::load_state()?;
            let id = client::select_profile(&state.profiles, profile.as_deref())?.id;
            regenerate_test_certificate(id).await
        }
        Command::Logs { lines } => service::logs(lines),
        Command::Info { profile } => show_info(profile.as_deref()).await,
        Command::Url {
            profile,
            server_address,
        } => print_saved_url(profile.as_deref(), server_address.as_deref()),
        Command::Qr {
            profile,
            server_address,
        } => print_saved_qr(profile.as_deref(), server_address.as_deref()),
        Command::Delete { profile, yes } => {
            if !yes {
                anyhow::bail!("删除配置需要显式添加 --yes;也可使用交互菜单确认");
            }
            let deleted = deployment::delete_and_activate(profile).await?;
            println!("已删除配置 {} ({})", deleted.name, deleted.id);
            Ok(())
        }
        Command::Export {
            format,
            profile,
            server,
            output,
        } => {
            let content = client::export(profile, format, &server, output.as_deref())?;
            if let Some(path) = output {
                println!("客户端配置已写入:{}", path.display());
            } else {
                println!("{content}");
            }
            Ok(())
        }
        Command::CheckPort { port, kind } => {
            let (tcp, udp) = match kind {
                PortKind::Tcp => (true, false),
                PortKind::Udp => (false, true),
                PortKind::Both => (true, true),
            };
            print_port_status(port, operations::check_port(port, tcp, udp));
            Ok(())
        }
        Command::Backup { output } => {
            let path = operations::backup(output)?;
            println!("备份已创建:{}", path.display());
            println!("备份包含私钥和密码,请按敏感文件保管。");
            Ok(())
        }
        Command::Restore { archive } => {
            let rollback = operations::restore(&archive).await?;
            println!("配置恢复成功。");
            if let Some(path) = rollback {
                println!("恢复前配置保留于:{}", path.display());
            }
            Ok(())
        }
        Command::EnableBbr => {
            operations::enable_bbr()?;
            println!("{}", "BBR 已启用并验证生效。".green());
            Ok(())
        }
        Command::Update {
            method,
            allow_downgrade,
        } => {
            let report = update_shoes_with_options(method, allow_downgrade).await?;
            println!("{} {}", "shoes 更新完成:".green(), report.version);
            Ok(())
        }
        Command::SelfUpdate { version, force } => {
            run_self_update(version.as_deref(), force).await.map(|_| ())
        }
        Command::Uninstall { purge } => {
            crate::utils::require_linux_root()?;
            let _lock =
                crate::utils::exclusive_lock(std::path::Path::new(crate::utils::LOCK_FILE))?;
            let unit_removed = service::uninstall_unit()?;
            let binary_removed = installer::uninstall_binary()?;
            let aliases_removed = crate::utils::remove_command_aliases()?;
            if purge {
                let config_dir = std::path::Path::new(crate::utils::CONFIG_DIR);
                if config_dir.exists() {
                    std::fs::remove_dir_all(config_dir)?;
                }
            }
            println!(
                "卸载完成:二进制={},systemd={},快捷命令清理={},配置清理={}",
                binary_removed, unit_removed, aliases_removed, purge
            );
            Ok(())
        }
    }
}

pub(crate) async fn update_shoes(method: InstallMethod) -> Result<installer::InstallReport> {
    update_shoes_with_options(method, false).await
}

pub(crate) async fn update_shoes_with_options(
    method: InstallMethod,
    allow_downgrade: bool,
) -> Result<installer::InstallReport> {
    crate::utils::require_linux_root()?;
    let lock = crate::utils::exclusive_lock(std::path::Path::new(crate::utils::LOCK_FILE))?;
    let unit_exists = std::path::Path::new(crate::utils::SERVICE_FILE).exists();
    let was_active = unit_exists && service::is_active()?;
    let mut report =
        installer::install_locked_with_options(method, true, allow_downgrade, lock).await?;
    if !was_active {
        if let Err(error) = report.commit_provenance() {
            report
                .rollback_binary()
                .context("shoes 安装来源保存失败,二进制回滚失败")?;
            return Err(error.context("shoes 安装来源保存失败,旧二进制已恢复"));
        }
        return Ok(report);
    }
    if let Err(restart) = service::restart_and_verify() {
        let binary_rollback = report.rollback_binary();
        let service_rollback = if binary_rollback.is_ok() {
            service::restart_and_verify()
        } else {
            Ok(())
        };
        return match (binary_rollback, service_rollback) {
            (Ok(()), Ok(())) => {
                Err(restart.context("新版 shoes 启动失败,旧二进制和服务已恢复"))
            }
            (Err(binary), _) => anyhow::bail!(
                "新版 shoes 启动失败且旧二进制恢复失败:启动={restart:#};二进制={binary:#}"
            ),
            (Ok(()), Err(service)) => anyhow::bail!(
                "新版 shoes 启动失败,旧二进制已恢复但服务恢复失败:启动={restart:#};服务={service:#}"
            ),
        };
    }
    if let Err(error) = report.commit_provenance() {
        report
            .rollback_binary()
            .context("shoes 安装来源保存失败,二进制回滚失败")?;
        service::restart_and_verify().context("shoes 安装来源保存失败,旧服务恢复失败")?;
        return Err(error.context("shoes 安装来源保存失败,旧二进制和服务已恢复"));
    }
    Ok(report)
}

async fn run_add(mut args: AddArgs) -> Result<()> {
    if args.shadowtls && !matches!(args.protocol, Protocol::Shadowsocks) {
        bail!("--shadowtls 仅适用于 Shadowsocks");
    }
    if args.plain && matches!(args.protocol, Protocol::NaiveProxy) {
        bail!("NaiveProxy 没有可互操作的标准分享 URI;请使用 sing-box JSON 导出");
    }
    if args.plain && matches!(args.protocol, Protocol::Snell) {
        bail!("Snell v3 没有可互操作的标准分享 URI,不能使用 --plain;请直接运行 prs add snell 查看连接参数");
    }
    if args.plain && args.shadowtls {
        bail!("ShadowTLS v3 没有可互操作的标准分享 URI,不能使用 --plain;请使用 sing-box 或 Mihomo 导出");
    }
    if args.protocol != Protocol::NaiveProxy
        && (args.self_signed
            || args.cert.is_some()
            || args.key.is_some()
            || args.username.is_some()
            || args.password.is_some()
            || args.padding
            || args.no_padding
            || args.udp
            || args.no_udp
            || args.fallback.is_some())
    {
        bail!("这些 TLS/认证参数仅适用于 NaiveProxy 快速添加");
    }
    if matches!(args.protocol, Protocol::NaiveProxy) {
        if args.udp {
            bail!("NaiveProxy UDP-over-TCP 尚未通过端到端验证,当前版本仅支持 TCP");
        }
        if !args.yes && io::stdin().is_terminal() {
            if args.server_name.is_none() {
                args.server_name = Some(
                    Input::<String>::with_theme(&ColorfulTheme::default())
                        .with_prompt("NaiveProxy 域名 / SNI")
                        .interact_text()?,
                );
            }
            if !args.self_signed && args.cert.is_none() {
                println!("TLS 证书模式:\n1) 使用已有受信任证书(推荐)\n2) 自签名证书(仅测试,不推荐)\n0) 返回");
                let choice = Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("请选择 [0-2]")
                    .default("1".to_owned())
                    .interact_text()?;
                match choice.trim() {
                    "1" => {
                        let cert = Input::<String>::with_theme(&ColorfulTheme::default())
                            .with_prompt("PEM 证书路径")
                            .interact_text()?;
                        let key = Input::<String>::with_theme(&ColorfulTheme::default())
                            .with_prompt("PEM 私钥路径")
                            .interact_text()?;
                        args.cert = Some(cert.into());
                        args.key = Some(key.into());
                    }
                    "2" => {
                        args.self_signed = true;
                        println!("警告:自签名证书仅供测试,不推荐用于生产环境。");
                    }
                    "0" => return Ok(()),
                    _ => bail!("NaiveProxy TLS 证书模式编号无效"),
                }
            }
        }
        if args.server_name.is_none() {
            bail!("NaiveProxy requires --server-name matching the TLS certificate");
        }
        if !args.self_signed && (args.cert.is_none() || args.key.is_none()) {
            bail!("NaiveProxy requires a trusted TLS certificate for production. Provide --server-name, --cert and --key, or explicitly use testing self-signed mode (--self-signed).");
        }
        if args.self_signed && (args.cert.is_some() || args.key.is_some()) {
            bail!("NaiveProxy --self-signed cannot be combined with --cert/--key");
        }
    }
    ensure_shoes_for_add(args.yes).await?;
    let result = fast_add::execute(fast_add::AddRequest {
        name: args.name,
        protocol: args.protocol,
        port: args.port.or(args.legacy_port),
        server_address: args.server_address,
        server_name: args.server_name,
        shadowsocks_cipher: None,
        shadowsocks_password: None,
        shadowsocks_mode: if args.shadowtls {
            ShadowsocksMode::ShadowTlsV3
        } else {
            ShadowsocksMode::Plain
        },
        shadowtls_password: None,
        shadowtls_handshake: None,
        certificate: args.cert,
        certificate_key: args.key,
        naive_self_signed: args.self_signed,
        naive_username: if matches!(args.protocol, Protocol::NaiveProxy) {
            args.username
        } else {
            None
        },
        naive_password: if matches!(args.protocol, Protocol::NaiveProxy) {
            args.password
        } else {
            None
        },
        naive_padding: args.padding || !args.no_padding,
        naive_fallback: args.fallback,
    })
    .await?;
    if args.plain {
        println!(
            "{}",
            result
                .share_uri
                .as_deref()
                .context("该协议没有标准分享 URI")?
        );
        return Ok(());
    }
    print_add_result(&result);
    Ok(())
}

pub(crate) async fn bootstrap_default_reality() -> Result<bool> {
    if !bootstrap_required(
        Path::new(crate::utils::CONFIG_FILE),
        Path::new(crate::utils::STATE_FILE),
    ) {
        return Ok(false);
    }
    println!();
    println!(
        "{}",
        "首次安装:自动部署 VLESS-REALITY".bright_cyan().bold()
    );
    println!("正在自动安装 shoes、选择随机端口并生成安全凭据……");
    ensure_shoes_for_add(true).await?;
    let server_address = fast_add::resolve_server_address(None).await?;
    let result = fast_add::execute(fast_add::AddRequest {
        name: Some("reality-default".to_owned()),
        protocol: Protocol::Reality,
        port: None,
        server_address: Some(server_address),
        server_name: None,
        shadowsocks_cipher: None,
        shadowsocks_password: None,
        shadowsocks_mode: ShadowsocksMode::Plain,
        shadowtls_password: None,
        shadowtls_handshake: None,
        certificate: None,
        certificate_key: None,
        naive_self_signed: false,
        naive_username: None,
        naive_password: None,
        naive_padding: true,
        naive_fallback: None,
    })
    .await?;
    print_add_result(&result);
    Ok(true)
}

fn bootstrap_required(config: &Path, state: &Path) -> bool {
    !config.exists() && !state.exists()
}

pub(crate) fn print_add_result(result: &fast_add::AddResult) {
    let profile = &result.generation.profile;
    println!("{}", "部署成功,shoes 服务已启动。".green().bold());
    print_profile_details_with_qr(profile, result.share_uri.as_deref());
    if result.share_uri.is_some() {
        println!("\n复制上方链接即可导入客户端。");
        println!("{}", "安全提示:分享链接包含访问凭据,请勿公开。".yellow());
    } else {
        if matches!(
            profile.credentials,
            config::Credentials::Shadowsocks {
                shadowtls: Some(_),
                ..
            }
        ) {
            println!(
                "\nShadowTLS v3 没有通用标准分享 URI;普通二维码也不支持;请使用 sing-box 或 Mihomo 导出。"
            );
        } else if matches!(profile.credentials, config::Credentials::NaiveProxy { .. }) {
            println!("\nNaiveProxy 没有通用标准分享 URI 或普通二维码;请使用包含 Naive 支持的 sing-box JSON 导出。");
        } else {
            println!("\nSnell v3 没有通用标准分享 URI;配置已成功部署,请按客户端支持情况手动填写或导出 Clash Meta(仅 AES-128-GCM)。");
        }
    }
}

pub(crate) fn print_profile_details_with_qr(
    profile: &config::ManagedProfile,
    share_uri: Option<&str>,
) {
    match profile_details_with_qr_text(profile, share_uri) {
        Ok(text) => println!("{text}"),
        Err(error) => {
            println!("{}", profile_details_text(profile, share_uri));
            eprintln!("二维码生成失败:{error:#};URL 已保留,可直接复制。");
        }
    }
}

fn profile_details_lines(profile: &config::ManagedProfile, share_uri: Option<&str>) -> Vec<String> {
    let mut lines = vec![format!(
        "\n-------------- {} -------------",
        profile.config_file_name()
    )];
    let address = profile.server_address.as_deref().unwrap_or("未保存");
    match &profile.credentials {
        config::Credentials::Reality {
            user_id,
            public_key,
            short_id,
            server_name,
            ..
        } => {
            lines.push("协议 (protocol)         = vless".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("用户ID (id)             = {user_id}"));
            lines.push("流控 (flow)             = xtls-rprx-vision".to_owned());
            lines.push("传输协议 (network)      = tcp".to_owned());
            lines.push("传输层安全 (TLS)        = reality".to_owned());
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "指纹 (Fingerprint)      = {}",
                config::REALITY_FINGERPRINT
            ));
            lines.push(format!("公钥 (Public key)       = {public_key}"));
            lines.push(format!("短 ID (shortId)         = {short_id}"));
        }
        config::Credentials::Hysteria2 {
            password,
            server_name,
            alpn_protocols,
        } => {
            lines.push("协议 (protocol)         = hysteria2".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("密码 (password)         = {password}"));
            lines.push("传输层安全 (TLS)        = tls".to_owned());
            lines.push(format!(
                "应用层协议协商 (Alpn)   = {}",
                alpn_protocols.join(",")
            ));
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "跳过证书验证 (allowInsecure) = {}",
                profile.self_signed_certificate
            ));
        }
        config::Credentials::Tuic {
            user_id,
            password,
            server_name,
            alpn_protocols,
            zero_rtt_handshake,
        } => {
            lines.push("协议 (protocol)         = tuic".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("用户ID (id)             = {user_id}"));
            lines.push(format!("密码 (password)         = {password}"));
            lines.push("传输层安全 (TLS)        = tls".to_owned());
            lines.push(format!(
                "应用层协议协商 (Alpn)   = {}",
                alpn_protocols.join(",")
            ));
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "跳过证书验证 (allowInsecure) = {}",
                profile.self_signed_certificate
            ));
            lines.push("拥塞控制算法 (congestion_control) = bbr".to_owned());
            lines.push(format!("0-RTT                   = {zero_rtt_handshake}"));
        }
        config::Credentials::Shadowsocks {
            cipher,
            password,
            shadowtls,
            ..
        } => {
            if let Some(shadowtls) = shadowtls {
                lines.push("协议                   = Shadowsocks 2022".to_owned());
                lines.push(format!("地址 (address)          = {address}"));
                lines.push(format!("端口 (port)             = {}", profile.port));
                lines.push(format!("Cipher                 = {}", cipher.as_str()));
                lines.push(format!("SS2022 Key             = {password}"));
                lines.push("传输/伪装              = ShadowTLS v3".to_owned());
                lines.push(format!("ShadowTLS Password      = {}", shadowtls.password));
                lines.push(format!(
                    "SNI                    = {}",
                    shadowtls.server_name
                ));
                lines.push(format!(
                    "Handshake              = {}",
                    shadowtls.handshake_address
                ));
                lines.push("UDP/UoT                = NOT_IMPLEMENTED (TCP only)".to_owned());
            } else {
                lines.push("协议 (protocol)         = shadowsocks".to_owned());
                lines.push(format!("地址 (address)          = {address}"));
                lines.push(format!("端口 (port)             = {}", profile.port));
                lines.push(format!("密码 (password)         = {password}"));
                lines.push(format!("加密方式 (encryption)   = {}", cipher.as_str()));
            }
        }
        config::Credentials::Snell {
            cipher,
            password,
            udp_enabled,
        } => {
            lines.push("协议 (protocol)         = snell".to_owned());
            lines.push("版本 (version)          = 3".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("密码 (password)         = {password}"));
            lines.push(format!("加密方式 (cipher)       = {}", cipher.as_str()));
            lines.push(format!("UDP-over-TCP            = {udp_enabled}"));
        }
        config::Credentials::Socks5 {
            username,
            password,
            udp_enabled,
        } => {
            lines.push("协议 (protocol)         = socks5".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            if let (Some(username), Some(password)) = (username, password) {
                lines.push(format!("用户名 (username)       = {username}"));
                lines.push(format!("密码 (password)         = {password}"));
            } else {
                lines.push("认证 (authentication)   = none".to_owned());
            }
            lines.push(format!(
                "UDP ASSOCIATE           = {}",
                if *udp_enabled { "enabled" } else { "disabled" }
            ));
            lines.push("传输加密               = none".to_owned());
            lines.push(
                "注意:SOCKS5 本身不提供传输加密,请勿将其误认为 TLS/Reality 代理。".to_owned(),
            );
        }
        config::Credentials::NaiveProxy {
            username,
            password,
            server_name,
            padding,
            udp_enabled,
            fallback,
        } => {
            lines.push("协议                  = naiveproxy".to_owned());
            lines.push(format!("地址                  = {address}"));
            lines.push(format!("端口                  = {}", profile.port));
            lines.push(format!("用户名                = {username}"));
            lines.push(format!("密码                  = {password}"));
            lines.push(format!("SNI / server name     = {server_name}"));
            lines.push("ALPN                  = h2".to_owned());
            lines.push(format!(
                "Padding               = {}",
                if *padding { "enabled" } else { "disabled" }
            ));
            lines.push(format!(
                "UDP over TCP           = {}",
                if *udp_enabled { "enabled" } else { "disabled" }
            ));
            lines.push(format!(
                "Fallback              = {}",
                fallback.as_deref().unwrap_or("none")
            ));
            lines.push(format!(
                "TLS certificate mode   = {}",
                if profile.self_signed_certificate {
                    "self-signed (testing)"
                } else {
                    "external trusted"
                }
            ));
            if profile.self_signed_certificate {
                lines.push("警告:测试模式,需要客户端信任该证书。".to_owned());
                lines.extend(profile.naive_certificate_details());
            }
        }
        config::Credentials::AnyTls {
            users,
            server_name,
            alpn_protocols,
            security,
            ..
        } => {
            lines.push("协议 (protocol)         = anytls".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            for user in users {
                if !user.name.is_empty() {
                    lines.push(format!("用户名 (Username)      = {}", user.name));
                }
                lines.push(format!("密码 (password)         = {}", user.password));
            }
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "应用层协议协商 (Alpn)   = {}",
                alpn_protocols.join(",")
            ));
            match security {
                config::AnyTlsSecurity::Tls => {
                    lines.push("传输层安全 (TLS)        = tls".to_owned());
                    lines.push(format!(
                        "跳过证书验证 (allowInsecure) = {}",
                        profile.self_signed_certificate
                    ));
                }
                config::AnyTlsSecurity::Reality {
                    public_key,
                    short_id,
                    ..
                } => {
                    lines.push("传输层安全 (TLS)        = reality".to_owned());
                    lines.push(format!(
                        "指纹 (Fingerprint)      = {}",
                        config::REALITY_FINGERPRINT
                    ));
                    lines.push(format!("公钥 (Public key)       = {public_key}"));
                    lines.push(format!("短 ID (shortId)         = {short_id}"));
                }
            }
        }
        config::Credentials::VlessTls {
            user_id,
            server_name,
            alpn_protocols,
            vision,
            websocket_path,
        } => {
            lines.push("协议 (protocol)         = vless".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("用户ID (id)             = {user_id}"));
            lines.push(format!(
                "流控 (flow)             = {}",
                if *vision { "xtls-rprx-vision" } else { "none" }
            ));
            lines.push(format!(
                "传输协议 (network)      = {}",
                if websocket_path.is_some() {
                    "ws"
                } else {
                    "tcp"
                }
            ));
            if let Some(path) = websocket_path {
                lines.push(format!("WebSocket 路径 (path)  = {path}"));
            }
            lines.push("传输层安全 (TLS)        = tls".to_owned());
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "应用层协议协商 (Alpn)   = {}",
                alpn_protocols.join(",")
            ));
        }
        config::Credentials::Trojan {
            password,
            server_name,
            alpn_protocols,
            security,
        } => {
            lines.push("协议 (protocol)         = trojan".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("密码 (password)         = {password}"));
            lines.push(format!("SNI (serverName)        = {server_name}"));
            match security {
                config::TlsSecurity::Tls => {
                    lines.push("传输层安全 (TLS)        = tls".to_owned());
                    lines.push(format!(
                        "应用层协议协商 (Alpn)   = {}",
                        alpn_protocols.join(",")
                    ));
                }
                config::TlsSecurity::Reality {
                    public_key,
                    short_id,
                    ..
                } => {
                    lines.push("传输层安全 (TLS)        = reality".to_owned());
                    lines.push(format!("公钥 (Public key)       = {public_key}"));
                    lines.push(format!("短 ID (shortId)         = {short_id}"));
                }
            }
        }
        config::Credentials::VmessTls {
            user_id,
            server_name,
            alpn_protocols,
            websocket_path,
        } => {
            lines.push("协议 (protocol)         = vmess".to_owned());
            lines.push(format!("地址 (address)          = {address}"));
            lines.push(format!("端口 (port)             = {}", profile.port));
            lines.push(format!("用户ID (id)             = {user_id}"));
            lines.push("加密方式 (security)     = auto".to_owned());
            lines.push("传输协议 (network)      = ws".to_owned());
            lines.push(format!("WebSocket 路径 (path)  = {websocket_path}"));
            lines.push("传输层安全 (TLS)        = tls".to_owned());
            lines.push(format!("SNI (serverName)        = {server_name}"));
            lines.push(format!(
                "应用层协议协商 (Alpn)   = {}",
                alpn_protocols.join(",")
            ));
        }
    }
    if profile.h2mux.enabled {
        lines.push(format!(
            "H2MUX 客户端偏好       = on (max_connections={}, min_streams={}, max_streams={}, padding={})",
            profile.h2mux.max_connections,
            profile.h2mux.min_streams,
            profile.h2mux.max_streams,
            profile.h2mux.padding
        ));
        lines.push("shoes 服务端自动识别 H2MUX;普通 URI/QR 不包含此偏好。".to_owned());
    } else if profile.h2mux_eligible() {
        lines.push("H2MUX 客户端偏好       = off".to_owned());
    }
    if let Some(uri) = share_uri {
        lines.push("------------- 链接 (URL) -------------".to_owned());
        lines.push(uri.to_owned());
    }
    if profile.self_signed_certificate && profile.protocol() != Protocol::NaiveProxy {
        lines.push("警告! 客户端需启用跳过证书验证 (allowInsecure),或换用受信任证书。".to_owned());
    }
    lines
}

fn profile_details_text(profile: &config::ManagedProfile, share_uri: Option<&str>) -> String {
    let mut lines = profile_details_lines(profile, share_uri);
    lines.push("------------- END -------------".to_owned());
    lines.join("\n")
}

fn profile_details_with_qr_text(
    profile: &config::ManagedProfile,
    share_uri: Option<&str>,
) -> Result<String> {
    let mut lines = profile_details_lines(profile, share_uri);
    if let Some(uri) = share_uri {
        lines.push("------------- 二维码 (QR) -------------".to_owned());
        lines.push(terminal_qr_text(uri)?);
    }
    lines.push("------------- END -------------".to_owned());
    Ok(lines.join("\n"))
}

fn terminal_qr_text(value: &str) -> Result<String> {
    let code = QrCode::new(value.as_bytes()).context("二维码内容过长,无法编码")?;
    Ok(code.render::<unicode::Dense1x2>().quiet_zone(true).build())
}

fn terminal_qr_or_url_text(value: &str) -> (String, Option<String>) {
    match terminal_qr_text(value) {
        Ok(qr) => (qr, None),
        Err(error) => (value.to_owned(), Some(format!("{error:#}"))),
    }
}

fn share_uri_with_qr_text(uri: &str) -> Result<String> {
    Ok([
        "------------- 链接 (URL) -------------".to_owned(),
        uri.to_owned(),
        "------------- 二维码 (QR) -------------".to_owned(),
        terminal_qr_text(uri)?,
        "------------- END -------------".to_owned(),
    ]
    .join("\n"))
}

pub(crate) fn print_share_uri_with_qr(uri: &str) {
    match share_uri_with_qr_text(uri) {
        Ok(text) => println!("\n{text}"),
        Err(error) => {
            println!(
                "\n------------- 链接 (URL) -------------\n{uri}\n------------- END -------------"
            );
            eprintln!("二维码生成失败:{error:#};URL 已保留,可直接复制。");
        }
    }
}

pub(crate) async fn ensure_shoes_for_add(yes: bool) -> Result<()> {
    if Path::new(crate::utils::SHOES_BIN).is_file() {
        return Ok(());
    }
    let approved = yes
        || (io::stdin().is_terminal()
            && Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("shoes 尚未安装,是否从 GitHub Release 自动安装并继续?")
                .default(true)
                .interact()?);
    if !approved {
        bail!("shoes 尚未安装;请先运行 ping-rust install,或添加 --yes 自动安装");
    }
    let report = installer::install(InstallMethod::Release, false).await?;
    service::install_unit(false)?;
    eprintln!("shoes 安装成功:{}({})", report.version, report.source);
    Ok(())
}

pub async fn run_self_update(version: Option<&str>, force: bool) -> Result<bool> {
    let report = self_update::update(version, force).await?;
    let updated = should_exit_after_self_update(&report);
    match report {
        self_update::UpdateReport::Current { current, available } => {
            if current == available {
                println!("ping-rust 已是当前版本:{current}");
            } else {
                println!("当前版本 {current} 不低于最新 Release {available},无需更新。");
            }
        }
        self_update::UpdateReport::Updated {
            from,
            to,
            destination,
        } => {
            println!("{} {from} → {to}", "ping-rust 自更新完成:".green());
            println!("路径:{}", destination.display());
            println!("当前旧进程即将退出,请重新运行 ping-rust 使用新版本。");
        }
    };
    Ok(updated)
}

fn should_exit_after_self_update(report: &self_update::UpdateReport) -> bool {
    matches!(report, self_update::UpdateReport::Updated { .. })
}

fn ping_version_status(current: &str, latest_tag: &str) -> &'static str {
    match (
        semver::Version::parse(current),
        semver::Version::parse(latest_tag.trim_start_matches('v')),
    ) {
        (Ok(current), Ok(latest)) if latest > current => "有更新",
        (Ok(_), Ok(_)) => "已是最新",
        _ => "Release tag 无法解析",
    }
}

fn upstream_drift(pin: &str, head: &str) -> bool {
    pin != head
}

pub async fn print_update_status() -> Result<()> {
    #[derive(serde::Deserialize)]
    struct ReleaseTag {
        tag_name: String,
    }
    #[derive(serde::Deserialize)]
    struct CommitSha {
        sha: String,
    }

    let ping_latest = async {
        Ok::<_, anyhow::Error>(
            crate::github_api::get::<ReleaseTag>(
                "https://api.github.com/repos/Jyanbai/ping-rust/releases/latest",
            )
            .await?
            .tag_name,
        )
    }
    .await;
    let shoes_latest = async {
        Ok::<_, anyhow::Error>(
            crate::github_api::get::<ReleaseTag>(
                "https://api.github.com/repos/cfal/shoes/releases/latest",
            )
            .await?
            .tag_name,
        )
    }
    .await;
    let upstream = async {
        Ok::<_, anyhow::Error>(
            crate::github_api::get::<CommitSha>(
                "https://api.github.com/repos/cfal/shoes/commits/master",
            )
            .await?
            .sha,
        )
    }
    .await;
    let installed = Path::new(crate::utils::SHOES_BIN).is_file();
    let known = if installed {
        installer::load_provenance()
    } else {
        Default::default()
    };
    println!("\nping-rust:");
    println!("  当前:{}", env!("CARGO_PKG_VERSION"));
    match ping_latest {
        Ok(tag) => {
            println!("  GitHub Latest:{tag}");
            println!(
                "  状态:{}",
                ping_version_status(env!("CARGO_PKG_VERSION"), &tag)
            );
        }
        Err(error) => println!("  GitHub Latest:查询失败({error})"),
    }
    println!("shoes:");
    println!("  二进制:{}", if installed { "已安装" } else { "未安装" });
    println!(
        "  已知安装来源:{}",
        if known.source.is_empty() {
            "unknown"
        } else {
            &known.source
        }
    );
    println!(
        "  已知安装版本:{}",
        known.version.as_deref().unwrap_or("未知")
    );
    if let Some(notice) = installer::unverified_installed_notice(&known) {
        println!("  {}", notice.yellow());
    }
    println!(
        "  已知 revision/tag:{}",
        known
            .revision
            .as_deref()
            .or(known.release_tag.as_deref())
            .unwrap_or("未知")
    );
    println!("ping-rust 验证 pin:");
    println!("  commit: {}", installer::verified_pin());
    println!("  version: {}", installer::verified_version());
    println!(
        "shoes 默认安装 Release(已验证固定): {}",
        installer::SHOES_RELEASE_TAG
    );
    println!("shoes GitHub Latest Release:");
    match shoes_latest {
        Ok(tag) => {
            println!("  tag: {tag}");
            if let Some(notice) = installer::newer_upstream_release_notice(&tag) {
                println!("  {notice}");
            }
        }
        Err(error) => println!("  tag: 查询失败({error})"),
    }
    println!("shoes upstream master:");
    match upstream {
        Ok(sha) => {
            println!("  HEAD: {sha}");
            println!(
                "Upstream drift: {}",
                if upstream_drift(installer::verified_pin(), &sha) {
                    "detected;生产 pin 保持不变,请查看 shoes upstream drift CI"
                } else {
                    "none"
                }
            );
        }
        Err(error) => println!("  HEAD: 查询失败({error})"),
    }
    Ok(())
}

pub(crate) fn execute_service(action: ServiceAction) -> Result<()> {
    if matches!(action, ServiceAction::Status) {
        if let Some(notice) = installer::unverified_installed_notice(&installer::load_provenance())
        {
            eprintln!("{}", notice.yellow());
        }
    }
    if matches!(action, ServiceAction::Status) && Path::new(crate::utils::STATE_FILE).exists() {
        let state = config::load_state().context("读取测试证书状态失败")?;
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        for profile in &state.profiles {
            if let Some(warning) = profile.naive_certificate_warning(now) {
                eprintln!("{}:{warning}", profile.name);
            }
        }
    }
    service::execute(action)
}

pub(crate) async fn regenerate_test_certificate(id: Uuid) -> Result<()> {
    let result =
        deployment::update_and_activate(id, config::ProfileChange::RegenerateNaiveCertificate)
            .await?;
    println!("NaiveProxy 测试证书已重新生成;受控重启已完成。");
    print_profile_details_with_qr(&result.profile, None);
    Ok(())
}

pub async fn show_info(selector: Option<&str>) -> Result<()> {
    let version = installer::installed_version()
        .await
        .unwrap_or_else(|_| "未安装".to_owned());
    let active = service::is_active().unwrap_or(false);
    println!("shoes:{version}");
    println!("二进制:{}", crate::utils::SHOES_BIN);
    println!("配置:{}", crate::utils::CONFIG_FILE);
    println!("服务:{}", if active { "运行中" } else { "未运行" });
    if !std::path::Path::new(crate::utils::STATE_FILE).exists() {
        println!("管理状态:未创建");
    } else {
        let state = config::load_state()?;
        if state.profiles.is_empty() {
            println!("配置:无");
        } else {
            let profiles = if let Some(selector) = selector {
                vec![client::select_profile(&state.profiles, Some(selector))?]
            } else {
                state.profiles.iter().collect::<Vec<_>>()
            };
            println!("配置数量:{}", profiles.len());
            for profile in profiles {
                for line in profile.naive_certificate_details() {
                    println!("  {line}");
                }
                println!(
                    "- {} | {} | 0.0.0.0:{} | {} | {}",
                    profile.id,
                    profile.name,
                    profile.port,
                    profile.protocol_name(),
                    profile.server_name()
                );
                if let config::Credentials::Snell {
                    cipher,
                    password,
                    udp_enabled,
                } = &profile.credentials
                {
                    println!("  Snell 版本:3");
                    println!("  加密方式:{}", cipher.as_str());
                    println!("  密码:{password}");
                    println!(
                        "  UDP-over-TCP:{}",
                        if *udp_enabled { "启用" } else { "关闭" }
                    );
                }
                if let config::Credentials::Socks5 {
                    username,
                    password,
                    udp_enabled,
                } = &profile.credentials
                {
                    println!("  用户名:{}", username.as_deref().unwrap_or("无认证"));
                    if let Some(password) = password {
                        println!("  密码:{password}");
                    }
                    println!(
                        "  UDP ASSOCIATE:{}",
                        if *udp_enabled { "启用" } else { "关闭" }
                    );
                    println!("  传输加密:无");
                }
                if let Some(server) = profile.server_address.as_deref() {
                    println!("  客户端地址:{server}");
                    match client::share_uri(profile, server) {
                        Ok(uri) => println!("  URL:{uri}"),
                        Err(error) => println!("  URL:无法生成({error})"),
                    }
                } else {
                    println!("  URL:未保存公网地址,可用 url --server-address 指定");
                }
            }
        }
    }
    Ok(())
}

fn print_saved_url(selector: Option<&str>, server_address: Option<&str>) -> Result<()> {
    let state = config::load_state()?;
    let profile = client::select_profile(&state.profiles, selector)?;
    println!("{}", client::stored_share_uri(profile, server_address)?);
    if profile.h2mux.enabled {
        eprintln!("提示:标准 URI 不包含 H2MUX 客户端偏好;此链接仍可用于普通连接。");
    }
    Ok(())
}

fn print_saved_qr(selector: Option<&str>, server_address: Option<&str>) -> Result<()> {
    let state = config::load_state()?;
    let profile = client::select_profile(&state.profiles, selector)?;
    let uri = client::stored_share_uri(profile, server_address)?;
    let (output, error) = terminal_qr_or_url_text(&uri);
    println!("{output}");
    if profile.h2mux.enabled {
        eprintln!("提示:二维码不包含 H2MUX 客户端偏好;此链接仍可用于普通连接。");
    }
    if let Some(error) = error {
        eprintln!("二维码生成失败:{error};已改为输出原始 URL,可直接复制。");
    }
    Ok(())
}

pub fn print_port_status(port: u16, status: operations::PortStatus) {
    if let Some(result) = status.tcp_available {
        match result {
            Ok(()) => println!("TCP {port}: {}", "可用".green()),
            Err(error) => println!("TCP {port}: {} ({error})", "被占用/不可绑定".red()),
        }
    }
    if let Some(result) = status.udp_available {
        match result {
            Ok(()) => println!("UDP {port}: {}", "可用".green()),
            Err(error) => println!("UDP {port}: {} ({error})", "被占用/不可绑定".red()),
        }
    }
}

pub fn print_credentials(result: &config::GenerationResult) {
    println!(
        "{} {}",
        "配置已写入:".green(),
        result.config_path.display()
    );
    println!("配置 ID:{}", result.profile_id);
    match &result.credentials {
        config::Credentials::Reality {
            user_id,
            private_key,
            public_key,
            short_id,
            server_name,
        } => {
            println!("协议:VLESS-Reality-Vision");
            println!("UUID:{user_id}");
            println!("SNI:{server_name}");
            println!("Short ID:{short_id}");
            println!("Reality 私钥:{private_key}");
            println!("Reality 公钥:{public_key}");
            println!(
                "{}",
                "安全提示:私钥仅保存在服务器配置中,请勿分享。".yellow()
            );
        }
        config::Credentials::Hysteria2 {
            password,
            server_name,
            alpn_protocols,
        } => {
            println!("协议:Hysteria2");
            println!("服务器名称:{server_name}");
            println!("密码:{password}");
            println!("ALPN:{}", alpn_protocols.join(", "));
            print_certificate_notice(result);
        }
        config::Credentials::Snell {
            cipher,
            password,
            udp_enabled,
        } => {
            println!("协议:Snell v3");
            println!("加密:{}", cipher.as_str());
            println!("密码:{password}");
            println!(
                "UDP-over-TCP:{}",
                if *udp_enabled { "启用" } else { "关闭" }
            );
        }
        config::Credentials::Socks5 {
            username,
            password,
            udp_enabled,
        } => {
            println!("协议:SOCKS5");
            println!("用户名:{}", username.as_deref().unwrap_or("无认证"));
            if let Some(password) = password {
                println!("密码:{password}");
            }
            println!(
                "UDP ASSOCIATE:{}",
                if *udp_enabled { "启用" } else { "关闭" }
            );
            println!("传输加密:无");
            println!("注意:SOCKS5 本身不提供传输加密,请勿将其误认为 TLS/Reality 代理。");
        }
        config::Credentials::Tuic {
            user_id,
            password,
            server_name,
            alpn_protocols,
            zero_rtt_handshake,
        } => {
            println!("协议:TUIC v5");
            println!("服务器名称:{server_name}");
            println!("UUID:{user_id}");
            println!("密码:{password}");
            println!("ALPN:{}", alpn_protocols.join(", "));
            println!(
                "0-RTT:{}",
                if *zero_rtt_handshake {
                    "启用"
                } else {
                    "关闭"
                }
            );
            print_certificate_notice(result);
        }
        config::Credentials::Shadowsocks {
            cipher,
            password,
            udp_enabled,
            shadowtls,
        } => {
            if let Some(shadowtls) = shadowtls {
                println!("协议:Shadowsocks 2022");
                println!("加密:{}", cipher.as_str());
                println!("SS2022 Key:{password}");
                println!("传输/伪装:ShadowTLS v3");
                println!("ShadowTLS Password:{}", shadowtls.password);
                println!("SNI:{}", shadowtls.server_name);
                println!("Handshake:{}", shadowtls.handshake_address);
                println!("UDP/UoT:NOT_IMPLEMENTED(TCP only)");
            } else {
                println!("协议:Shadowsocks");
                println!("加密:{}", cipher.as_str());
                println!("密码:{password}");
                println!("UDP:{}", if *udp_enabled { "启用" } else { "关闭" });
            }
        }
        config::Credentials::NaiveProxy {
            username,
            password,
            server_name,
            padding,
            udp_enabled,
            fallback,
        } => {
            println!("协议:NaiveProxy");
            println!("用户名:{username}");
            println!("密码:{password}");
            println!("SNI:{server_name}");
            println!("ALPN:h2");
            println!("Padding:{}", if *padding { "启用" } else { "关闭" });
            println!(
                "UDP-over-TCP:{}",
                if *udp_enabled {
                    "启用"
                } else {
                    "NOT_IMPLEMENTED"
                }
            );
            println!("Fallback:{}", fallback.as_deref().unwrap_or("none"));
            print_certificate_notice(result);
        }
        config::Credentials::AnyTls {
            users,
            server_name,
            alpn_protocols,
            udp_enabled,
            security,
        } => {
            println!("协议:AnyTLS");
            println!("服务器名称:{server_name}");
            println!("ALPN:{}", alpn_protocols.join(", "));
            println!("UDP:{}", if *udp_enabled { "启用" } else { "关闭" });
            for user in users {
                let label = if user.name.is_empty() {
                    "default"
                } else {
                    &user.name
                };
                println!("用户 {label}:{}", user.password);
            }
            match security {
                config::AnyTlsSecurity::Tls => print_certificate_notice(result),
                config::AnyTlsSecurity::Reality {
                    private_key,
                    public_key,
                    short_id,
                } => {
                    println!("Short ID:{short_id}");
                    println!("Reality 私钥:{private_key}");
                    println!("Reality 公钥:{public_key}");
                    println!("{}", "安全提示:Reality 私钥不得导出或分享。".yellow());
                }
            }
        }
        config::Credentials::VlessTls {
            user_id,
            server_name,
            alpn_protocols,
            vision,
            websocket_path,
        } => {
            println!(
                "协议:{}",
                if websocket_path.is_some() {
                    "VLESS-WS-TLS"
                } else if *vision {
                    "VLESS-TLS-Vision"
                } else {
                    "VLESS-TLS"
                }
            );
            println!("UUID:{user_id}");
            println!("服务器名称:{server_name}");
            println!("ALPN:{}", alpn_protocols.join(", "));
            if let Some(path) = websocket_path {
                println!("WebSocket 路径:{path}");
            }
            print_certificate_notice(result);
        }
        config::Credentials::Trojan {
            password,
            server_name,
            security,
            ..
        } => {
            println!("协议:{}", result.profile.protocol_name());
            println!("密码:{password}");
            println!("服务器名称:{server_name}");
            match security {
                config::TlsSecurity::Tls => print_certificate_notice(result),
                config::TlsSecurity::Reality {
                    private_key,
                    public_key,
                    short_id,
                } => {
                    println!("Short ID:{short_id}");
                    println!("Reality 私钥:{private_key}");
                    println!("Reality 公钥:{public_key}");
                    println!("{}", "安全提示:Reality 私钥不得导出或分享。".yellow());
                }
            }
        }
        config::Credentials::VmessTls {
            user_id,
            server_name,
            alpn_protocols,
            websocket_path,
        } => {
            println!("协议:VMess-WS-TLS");
            println!("UUID:{user_id}");
            println!("服务器名称:{server_name}");
            println!("ALPN:{}", alpn_protocols.join(", "));
            println!("WebSocket 路径:{websocket_path}");
            print_certificate_notice(result);
        }
    }
}

fn print_certificate_notice(result: &config::GenerationResult) {
    if let Some(cert) = &result.certificate_path {
        println!("证书:{}", cert.display());
    }
    if let Some(key) = &result.certificate_key_path {
        println!("私钥:{}", key.display());
    }
    println!(
        "{}",
        "若使用自动生成的自签名证书,生产环境应将证书导入客户端信任库;不要长期关闭证书校验。"
            .yellow()
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn version_output_includes_git_commit() {
        let (stdout, stderr) = version_output();
        assert_eq!(stdout, format!("ping-rust {}", env!("CARGO_PKG_VERSION")));
        let commit = stderr.strip_prefix("commit ").expect("commit line");
        assert!(
            commit == "unknown"
                || (commit.len() >= 7 && commit.chars().all(|c| c.is_ascii_hexdigit()))
        );
        let args = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(is_version_request(args(&["ping-rust", "--version"])));
        assert!(is_version_request(args(&["prs", "-V"])));
        assert!(!is_version_request(args(&[
            "ping-rust",
            "self-update",
            "--version",
            "v0.2.2"
        ])));
        assert!(!is_version_request(args(&["ping-rust"])));
    }

    #[test]
    fn parses_self_update_options() {
        let cli =
            Cli::try_parse_from(["ping-rust", "self-update", "--version", "v0.1.2", "--force"])
                .unwrap();
        match cli.command.unwrap() {
            Command::SelfUpdate { version, force } => {
                assert_eq!(version.as_deref(), Some("v0.1.2"));
                assert!(force);
            }
            command => panic!("unexpected command: {command:?}"),
        }
    }

    #[test]
    fn self_update_current_continues_but_updated_exits_menu() {
        let current = self_update::UpdateReport::Current {
            current: semver::Version::new(0, 1, 20),
            available: semver::Version::new(0, 1, 20),
        };
        let updated = self_update::UpdateReport::Updated {
            from: semver::Version::new(0, 1, 20),
            to: semver::Version::new(0, 2, 0),
            destination: PathBuf::from("/tmp/ping-rust"),
        };
        assert!(!should_exit_after_self_update(&current));
        assert!(should_exit_after_self_update(&updated));
    }

    #[test]
    fn update_status_comparison_is_fail_soft_and_drift_is_explicit() {
        assert_eq!(ping_version_status("0.1.20", "v0.1.20"), "已是最新");
        assert_eq!(ping_version_status("0.1.20", "v0.2.0"), "有更新");
        assert_eq!(
            ping_version_status("0.1.20", "latest"),
            "Release tag 无法解析"
        );
        assert!(!upstream_drift("abc", "abc"));
        assert!(upstream_drift("abc", "def"));
    }

    #[test]
    fn keeps_shoes_update_as_distinct_command() {
        let cli = Cli::try_parse_from(["ping-rust", "update"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Update {
                method: InstallMethod::Release,
                allow_downgrade: false
            })
        ));
        let cli = Cli::try_parse_from([
            "ping-rust",
            "update",
            "--method",
            "release",
            "--allow-downgrade",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Update {
                allow_downgrade: true,
                ..
            })
        ));
    }

    #[test]
    fn parses_new_protocol_options_without_changing_generate_shape() {
        let ss = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "shadowsocks",
            "--cipher",
            "2022-blake3-aes-128-gcm",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = ss.command else {
            panic!("expected generate command");
        };
        assert_eq!(args.protocol, Protocol::Shadowsocks);
        assert_eq!(args.cipher, Some(ShadowsocksCipher::Aes128Gcm2022));

        let anytls = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "anytls",
            "--anytls-mode",
            "reality",
            "--user",
            "alice:secret",
            "--padding",
            "stop=8",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = anytls.command else {
            panic!("expected generate command");
        };
        assert_eq!(args.protocol, Protocol::AnyTls);
        assert_eq!(args.anytls_mode, AnyTlsMode::Reality);

        let websocket = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "vless-ws-tls",
            "--websocket-path",
            "/vless",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = websocket.command else {
            panic!("expected generate command");
        };
        assert_eq!(args.protocol, Protocol::VlessWsTls);
        assert_eq!(args.websocket_path.as_deref(), Some("/vless"));

        for protocol in ["vless-tls", "trojan-tls", "trojan-reality", "vmess-ws-tls"] {
            assert!(Cli::try_parse_from(["prs", "add", protocol]).is_ok());
        }

        let snell = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "snell",
            "--port",
            "8389",
            "--cipher",
            "aes-128-gcm",
            "--password",
            "secret",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = snell.command else {
            panic!("expected Snell generate command");
        };
        assert_eq!(args.protocol, Protocol::Snell);
        assert_eq!(args.port, 8389);
        assert_eq!(args.cipher, Some(ShadowsocksCipher::Aes128Gcm));
        assert_eq!(args.password.as_deref(), Some("secret"));

        let socks5 = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "socks5",
            "--name",
            "tools",
            "--port",
            "1080",
            "--username",
            "alice",
            "--password",
            "socks-secret",
            "--no-udp",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = socks5.command else {
            panic!("expected SOCKS5 generate command");
        };
        assert_eq!(args.protocol, Protocol::Socks5);
        assert_eq!(args.username.as_deref(), Some("alice"));
        assert_eq!(args.password.as_deref(), Some("socks-secret"));
        assert!(args.disable_udp);
        assert!(!args.no_auth);

        let anonymous =
            Cli::try_parse_from(["ping-rust", "generate", "socks", "--no-auth", "--udp"]).unwrap();
        let Some(Command::Generate(args)) = anonymous.command else {
            panic!("expected SOCKS5 generate command");
        };
        assert_eq!(args.protocol, Protocol::Socks5);
        assert!(args.no_auth);
        assert!(args.udp);
    }

    #[test]
    fn parses_prs_add_aliases_and_output_controls() {
        let cli = Cli::try_parse_from([
            "prs",
            "a",
            "r",
            "443",
            "--server-address",
            "203.0.113.9",
            "--yes",
            "--plain",
        ])
        .unwrap();
        let Some(Command::Add(args)) = cli.command else {
            panic!("expected add command");
        };
        assert_eq!(args.protocol, Protocol::Reality);
        assert_eq!(args.legacy_port, Some(443));
        assert!(args.yes);
        assert!(args.plain);

        let cli = Cli::try_parse_from(["prs", "add", "ss", "--random-port"]).unwrap();
        let Some(Command::Add(args)) = cli.command else {
            panic!("expected add command");
        };
        assert_eq!(args.protocol, Protocol::Shadowsocks);
        assert!(args.random_port);

        for command in [["prs", "add", "snell"], ["prs", "a", "snell"]] {
            let cli = Cli::try_parse_from(command).unwrap();
            let Some(Command::Add(args)) = cli.command else {
                panic!("expected Snell add command");
            };
            assert_eq!(args.protocol, Protocol::Snell);
        }
        for command in [["prs", "add", "socks5"], ["prs", "a", "socks5"]] {
            let cli = Cli::try_parse_from(command).unwrap();
            let Some(Command::Add(args)) = cli.command else {
                panic!("expected SOCKS5 add command");
            };
            assert_eq!(args.protocol, Protocol::Socks5);
        }
    }

    #[test]
    fn rejects_conflicting_fast_add_port_options() {
        assert!(Cli::try_parse_from(["prs", "add", "reality", "443", "--random-port"]).is_err());
    }

    #[test]
    fn parses_info_url_and_qr_commands() {
        assert!(matches!(
            Cli::try_parse_from(["prs", "i", "main"]).unwrap().command,
            Some(Command::Info { profile: Some(profile) }) if profile == "main"
        ));
        assert!(matches!(
            Cli::try_parse_from(["prs", "url", "main"]).unwrap().command,
            Some(Command::Url { profile: Some(profile), .. }) if profile == "main"
        ));
        assert!(matches!(
            Cli::try_parse_from(["prs", "qr", "main"]).unwrap().command,
            Some(Command::Qr { profile: Some(profile), .. }) if profile == "main"
        ));
    }

    #[test]
    fn bootstrap_only_runs_when_both_managed_files_are_absent() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("config.yaml");
        let state = dir.path().join("state.json");
        assert!(bootstrap_required(&config, &state));
        std::fs::write(&config, b"servers: []").unwrap();
        assert!(!bootstrap_required(&config, &state));
        std::fs::remove_file(&config).unwrap();
        std::fs::write(&state, b"{}").unwrap();
        assert!(!bootstrap_required(&config, &state));
        assert!(matches!(
            Cli::try_parse_from(["ping-rust", "bootstrap"])
                .unwrap()
                .command,
            Some(Command::Bootstrap)
        ));
    }

    #[test]
    fn parses_hidden_install_self_options() {
        assert!(matches!(
            Cli::try_parse_from([
                "ping-rust",
                "install-self",
                "--install-dir",
                "/tmp/ping-rust-bin",
                "--quiet",
                "--no-bootstrap",
            ])
            .unwrap()
            .command,
            Some(Command::InstallSelf {
                install_dir,
                quiet: true,
                no_bootstrap: true,
            }) if install_dir == Path::new("/tmp/ping-rust-bin")
        ));
    }

    #[test]
    fn parses_naiveproxy_certificate_regeneration() {
        assert!(
            Cli::try_parse_from(["ping-rust", "regenerate-test-certificate", "legacy-naive"])
                .is_ok()
        );
    }

    #[test]
    fn parses_naiveproxy_quick_and_generate_tls_modes() {
        let cli = Cli::try_parse_from([
            "prs",
            "a",
            "naiveproxy",
            "443",
            "--server-name",
            "naive.example.com",
            "--self-signed",
            "--no-padding",
            "--username",
            "alice",
        ])
        .unwrap();
        let Some(Command::Add(args)) = cli.command else {
            panic!("expected add");
        };
        assert_eq!(args.protocol, Protocol::NaiveProxy);
        assert!(args.self_signed);
        assert!(args.no_padding);
        assert_eq!(args.username.as_deref(), Some("alice"));
        let cli = Cli::try_parse_from([
            "ping-rust",
            "generate",
            "naiveproxy",
            "--server-name",
            "naive.example.com",
            "--self-signed",
            "--padding",
        ])
        .unwrap();
        let Some(Command::Generate(args)) = cli.command else {
            panic!("expected generate");
        };
        assert_eq!(args.anytls_padding, ["true"]);
    }

    #[test]
    fn shadowsocks_details_include_import_fields() {
        let profile = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "ss-main".to_owned(),
            port: 34333,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Shadowsocks {
                cipher: ShadowsocksCipher::Aes256Gcm2022,
                password: "generated-password".to_owned(),
                udp_enabled: true,
                shadowtls: None,
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: false,
            naive_certificate_validity: None,
        };
        let output = profile_details_text(&profile, Some("ss://import-link"));
        for expected in [
            "SHADOWSOCKS-34333.yaml",
            "协议 (protocol)         = shadowsocks",
            "地址 (address)          = 203.0.113.8",
            "端口 (port)             = 34333",
            "密码 (password)         = generated-password",
            "加密方式 (encryption)   = 2022-blake3-aes-256-gcm",
            "ss://import-link",
            "------------- END -------------",
        ] {
            assert!(
                output.contains(expected),
                "missing {expected:?} in {output}"
            );
        }

        let qr_output = profile_details_with_qr_text(&profile, Some("ss://import-link")).unwrap();
        let url_position = qr_output.find("ss://import-link").unwrap();
        let qr_position = qr_output
            .find("------------- 二维码 (QR) -------------")
            .unwrap();
        let end_position = qr_output.find("------------- END -------------").unwrap();
        assert!(url_position < qr_position);
        assert!(qr_position < end_position);
        assert!(qr_output
            .chars()
            .any(|value| matches!(value, '▀' | '▄' | '█')));

        let without_url = profile_details_with_qr_text(&profile, None).unwrap();
        assert!(!without_url.contains("二维码 (QR)"));
    }

    #[test]
    fn snell_details_show_every_manual_client_field_without_fake_url() {
        let profile = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "snell-main".to_owned(),
            port: 8389,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Snell {
                cipher: SnellCipher::Chacha20IetfPoly1305,
                password: "snell-secret".to_owned(),
                udp_enabled: true,
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: false,
            naive_certificate_validity: None,
        };
        let output = profile_details_text(&profile, None);
        for expected in [
            "SNELL-8389.yaml",
            "协议 (protocol)         = snell",
            "版本 (version)          = 3",
            "地址 (address)          = 203.0.113.8",
            "端口 (port)             = 8389",
            "密码 (password)         = snell-secret",
            "加密方式 (cipher)       = chacha20-ietf-poly1305",
            "UDP-over-TCP            = true",
        ] {
            assert!(
                output.contains(expected),
                "missing {expected:?} in {output}"
            );
        }
        assert!(!output.contains("链接 (URL)"));
        assert!(!output.contains("二维码 (QR)"));
    }

    #[test]
    fn socks5_details_show_auth_udp_encryption_and_share_uri() {
        let profile = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "socks-main".to_owned(),
            port: 1080,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Socks5 {
                username: Some("default".to_owned()),
                password: Some("socks-secret".to_owned()),
                udp_enabled: true,
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: false,
            naive_certificate_validity: None,
        };
        let output = profile_details_with_qr_text(
            &profile,
            Some("socks5://default:socks-secret@203.0.113.8:1080#socks-main"),
        )
        .unwrap();
        for expected in [
            "SOCKS5-1080.yaml",
            "协议 (protocol)         = socks5",
            "地址 (address)          = 203.0.113.8",
            "端口 (port)             = 1080",
            "用户名 (username)       = default",
            "密码 (password)         = socks-secret",
            "UDP ASSOCIATE           = enabled",
            "传输加密               = none",
            "SOCKS5 本身不提供传输加密",
            "------------- 链接 (URL) -------------",
            "socks5://default:socks-secret@203.0.113.8:1080#socks-main",
            "------------- 二维码 (QR) -------------",
        ] {
            assert!(
                output.contains(expected),
                "missing {expected:?} in {output}"
            );
        }
    }

    #[test]
    fn standalone_qr_falls_back_to_the_original_url_when_encoding_fails() {
        let uri = format!("vless://{}", "x".repeat(10_000));
        let (output, error) = terminal_qr_or_url_text(&uri);
        assert_eq!(output, uri);
        assert!(
            error
                .as_deref()
                .is_some_and(|message| message.contains("二维码内容过长")),
            "missing explicit QR fallback error: {error:?}"
        );
    }

    #[test]
    fn share_uri_qr_block_keeps_url_before_terminal_qr() {
        let output = share_uri_with_qr_text("vless://import-link").unwrap();
        let url_position = output.find("vless://import-link").unwrap();
        let qr_position = output.find("二维码 (QR)").unwrap();
        let end_position = output.find("------------- END -------------").unwrap();
        assert!(url_position < qr_position);
        assert!(qr_position < end_position);
        assert!(output.chars().any(|value| matches!(value, '▀' | '▄' | '█')));
    }

    #[test]
    fn all_protocol_details_include_client_fields() {
        let reality = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "reality".to_owned(),
            port: 443,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Reality {
                user_id: Uuid::nil(),
                private_key: "never-print-private".to_owned(),
                public_key: "reality-public".to_owned(),
                short_id: "0123456789abcdef".to_owned(),
                server_name: "www.cloudflare.com".to_owned(),
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: false,
            naive_certificate_validity: None,
        };
        let reality_uri = client::share_uri(&reality, "203.0.113.8").unwrap();
        let reality_output = profile_details_text(&reality, Some(&reality_uri));
        for expected in [
            "协议 (protocol)         = vless",
            "用户ID (id)",
            "xtls-rprx-vision",
            "reality-public",
            "0123456789abcdef",
            "vless://",
        ] {
            assert!(reality_output.contains(expected));
        }
        assert!(!reality_output.contains("never-print-private"));

        let hysteria2 = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "hysteria2".to_owned(),
            port: 2443,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Hysteria2 {
                password: "hy2-password".to_owned(),
                server_name: "proxy.example.com".to_owned(),
                alpn_protocols: vec!["h3".to_owned()],
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: true,
            naive_certificate_validity: None,
        };
        let hysteria2_uri = client::share_uri(&hysteria2, "203.0.113.8").unwrap();
        let hysteria2_output = profile_details_text(&hysteria2, Some(&hysteria2_uri));
        for expected in [
            "协议 (protocol)         = hysteria2",
            "密码 (password)         = hy2-password",
            "应用层协议协商 (Alpn)   = h3",
            "allowInsecure) = true",
            "hysteria2://",
        ] {
            assert!(hysteria2_output.contains(expected));
        }

        let tuic = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "tuic".to_owned(),
            port: 3443,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::Tuic {
                user_id: Uuid::nil(),
                password: "tuic-password".to_owned(),
                server_name: "proxy.example.com".to_owned(),
                alpn_protocols: vec!["h3".to_owned()],
                zero_rtt_handshake: false,
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: true,
            naive_certificate_validity: None,
        };
        let tuic_uri = client::share_uri(&tuic, "203.0.113.8").unwrap();
        let tuic_output = profile_details_text(&tuic, Some(&tuic_uri));
        for expected in [
            "协议 (protocol)         = tuic",
            "用户ID (id)",
            "密码 (password)         = tuic-password",
            "congestion_control) = bbr",
            "tuic://",
        ] {
            assert!(tuic_output.contains(expected));
        }

        let anytls = config::ManagedProfile {
            h2mux: Default::default(),
            id: Uuid::nil(),
            name: "anytls".to_owned(),
            port: 4443,
            server_address: Some("203.0.113.8".to_owned()),
            credentials: config::Credentials::AnyTls {
                users: vec![config::AnyTlsUser {
                    name: "default".to_owned(),
                    password: "anytls-password".to_owned(),
                }],
                server_name: "proxy.example.com".to_owned(),
                alpn_protocols: vec!["h2".to_owned(), "http/1.1".to_owned()],
                udp_enabled: true,
                security: config::AnyTlsSecurity::Tls,
            },
            certificate_path: None,
            certificate_key_path: None,
            self_signed_certificate: true,
            naive_certificate_validity: None,
        };
        let anytls_uri = client::share_uri(&anytls, "203.0.113.8").unwrap();
        let anytls_output = profile_details_text(&anytls, Some(&anytls_uri));
        for expected in [
            "协议 (protocol)         = anytls",
            "用户名 (Username)      = default",
            "密码 (password)         = anytls-password",
            "传输层安全 (TLS)        = tls",
            "anytls://",
        ] {
            assert!(anytls_output.contains(expected));
        }
    }
}