sefy 0.19.0

An inconspicuous encrypted store for notes, credentials and files
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
//! What each subcommand does once the vault is open.

use crate::autosync::AutoSync;
use crate::cli::{
    AddKind, EditArgs, ExportFormat, FillArgs, FindArgs, GenArgs, GetArgs, HistoryArgs, ListArgs,
    OpenArgs, OtpArgs, PullArgs, RecordArgs, RemoteArgs, RestoreArgs, RunArgs,
};
use crate::output;
use crate::session::{self, Master};
use anyhow::{Context, Result, bail};
use sefy_core::{
    Change, ChangeKind, Classes, Field, Item, ItemKind, ItemSummary, NewItem, Opener, Outcome,
    Payload, Query, Recipe, Strength, Target, Totp, Vault, Version,
};
use std::io::Read;
use std::path::{Path, PathBuf};
use zeroize::Zeroizing;

/// Creates a vault, refusing to touch a file that already exists.
pub fn init(path: &Path, password_env: Option<&str>) -> Result<()> {
    if path.exists() {
        bail!("{} already exists", path.display());
    }
    let password = session::new_password(password_env)?;
    Vault::create(path, password.as_bytes())?;
    println!("created {}", path.display());
    Ok(())
}

/// Adds an item and saves the vault.
pub fn add(vault: &mut Vault, kind: AddKind) -> Result<()> {
    let (item, description) = match kind {
        AddKind::Note {
            title,
            text,
            editor,
            tag,
        } => {
            let text = match text {
                Some(text) => text,
                None if editor => crate::editor::edit("")?,
                None => read_stdin().context("cannot read the note text from stdin")?,
            };
            (
                NewItem::new(title.clone(), Payload::Note { text }).with_tags(tag),
                title,
            )
        }
        AddKind::Login {
            title,
            login,
            url,
            totp,
            notes,
            item_password_env,
            tag,
        } => {
            // Only this item's own variable is consulted: falling back to
            // --password-env would silently store the master password as the
            // account's password.
            let password =
                session::secret("Password for this item: ", item_password_env.as_deref())?;
            let mut fields = vec![
                Field::public("login", login),
                Field::secret("password", password),
            ];
            push_optional(&mut fields, "url", url, false);
            let totp = totp
                .map(|key| checked(sefy_core::otp::FIELD, key))
                .transpose()?;
            push_optional(&mut fields, sefy_core::otp::FIELD, totp, true);
            push_optional(&mut fields, "notes", notes, false);
            (
                NewItem::new(title.clone(), Payload::fields(ItemKind::Login, fields))
                    .with_tags(tag),
                title,
            )
        }
        AddKind::Card {
            title,
            holder,
            expires,
            notes,
            no_cvv,
            no_pin,
            number_env,
            cvv_env,
            pin_env,
            tag,
        } => {
            let number = session::secret("Card number: ", number_env.as_deref())?;
            let mut fields = vec![Field::secret("number", number)];
            push_optional(&mut fields, "holder", holder, false);
            let expires = expires
                .map(|value| checked(sefy_core::expiry::FIELD, value))
                .transpose()?;
            push_optional(&mut fields, sefy_core::expiry::FIELD, expires, false);
            if !no_cvv {
                push_typed(
                    &mut fields,
                    "cvv",
                    session::secret("CVV (empty if there is none): ", cvv_env.as_deref())?,
                )?;
            }
            if !no_pin {
                push_typed(
                    &mut fields,
                    "pin",
                    session::secret("PIN (empty if unknown): ", pin_env.as_deref())?,
                )?;
            }
            push_optional(&mut fields, "notes", notes, false);
            (
                NewItem::new(title.clone(), Payload::fields(ItemKind::Card, fields)).with_tags(tag),
                title,
            )
        }
        AddKind::SshKey {
            title,
            private_key,
            public_key,
            host,
            notes,
            no_passphrase,
            passphrase_env,
            tag,
        } => {
            let private = std::fs::read_to_string(&private_key)
                .with_context(|| format!("cannot read {}", private_key.display()))?;
            let mut fields = vec![Field::secret("private-key", private)];
            if !no_passphrase {
                push_typed(
                    &mut fields,
                    "passphrase",
                    session::secret(
                        "Passphrase for the key (empty if it has none): ",
                        passphrase_env.as_deref(),
                    )?,
                )?;
            }
            // The conventional sibling is picked up when it is there, and its
            // absence is not an error: a key without its public half is still
            // worth storing, and the public half can be derived from it.
            let public_path = public_key.unwrap_or_else(|| sibling_public_key(&private_key));
            match std::fs::read_to_string(&public_path) {
                Ok(public) => fields.push(Field::public("public-key", public.trim())),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(error)
                        .with_context(|| format!("cannot read {}", public_path.display()));
                }
            }
            push_optional(&mut fields, "host", host, false);
            push_optional(&mut fields, "notes", notes, false);
            (
                NewItem::new(title.clone(), Payload::fields(ItemKind::SshKey, fields))
                    .with_tags(tag),
                title,
            )
        }
        AddKind::Wifi(args) => record(ItemKind::Wifi, args)?,
        AddKind::ApiToken(args) => record(ItemKind::ApiToken, args)?,
        AddKind::Bank(args) => record(ItemKind::Bank, args)?,
        AddKind::File { path, title, tag } => {
            let bytes =
                std::fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?;
            let filename = path
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "file".to_owned());
            let title = title.unwrap_or_else(|| filename.clone());
            (
                NewItem::new(title.clone(), Payload::File { filename, bytes }).with_tags(tag),
                title,
            )
        }
    };

    let id = vault.add(item)?;
    vault.save()?;
    println!("added {description:?} as {id}");
    Ok(())
}

/// Builds a record of a kind that is nothing but its template.
///
/// Every field comes from the template's row: public ones from `--set`, secret
/// ones asked for in the order the row lists them, or read from the variable
/// `--secret-env` names. A name the row does not have is kept as an extra
/// field, the way `edit --set` keeps one.
fn record(kind: ItemKind, args: RecordArgs) -> Result<(NewItem, String)> {
    let template = kind
        .template()
        .with_context(|| format!("a {kind} is not a record"))?;
    let given = assignments("--set", "NAME=VALUE", &args.set)?;
    let from_env = assignments("--secret-env", "NAME=VAR", &args.secret_env)?;
    let secret_names = || {
        template
            .fields
            .iter()
            .filter(|spec| spec.secret)
            .map(|spec| spec.name)
            .collect::<Vec<_>>()
            .join(", ")
    };

    for (name, _) in &given {
        if template.field(name).is_some_and(|spec| spec.secret) {
            bail!(
                "{name} is secret, so it is not taken on the command line\n\
                 leave it to the prompt, or pass --secret-env {name}=VAR"
            );
        }
    }
    for (name, _) in &from_env {
        if template.field(name).is_some_and(|spec| !spec.secret) {
            bail!("{name} is not secret; pass it with --set {name}=VALUE");
        }
    }
    for name in &args.skip {
        if !template.field(name).is_some_and(|spec| spec.secret) {
            bail!(
                "--skip names a secret field of a {kind}, and {name:?} is not one; \
                 those are: {}",
                secret_names()
            );
        }
    }

    let mut fields = Vec::new();
    for spec in template.fields {
        if spec.secret {
            if args.skip.iter().any(|name| name == spec.name) {
                continue;
            }
            let value = match from_env.iter().find(|(name, _)| name == spec.name) {
                Some((_, variable)) => session::secret("", Some(variable))?,
                None => session::secret(
                    &format!("{} ({}; empty to leave out): ", spec.name, spec.description),
                    None,
                )?,
            };
            push_typed(&mut fields, spec.name, value)?;
        } else if let Some((_, value)) = given.iter().find(|(name, _)| name == spec.name) {
            fields.push(Field::public(spec.name, checked(spec.name, value.clone())?));
        }
    }
    for (name, value) in &given {
        if template.field(name).is_none() {
            fields.push(Field::public(name.clone(), checked(name, value.clone())?));
        }
    }
    for (name, variable) in &from_env {
        if template.field(name).is_none() {
            push_typed(&mut fields, name, session::secret("", Some(variable))?)?;
        }
    }

    if fields.is_empty() {
        bail!("a {kind} needs at least one field; nothing was given or typed");
    }
    Ok((
        NewItem::new(args.title.clone(), Payload::fields(kind, fields)).with_tags(args.tag),
        args.title,
    ))
}

/// Adds a secret that was typed or read from a variable, unless it was empty.
///
/// Nothing typed is nothing stored: "no PIN" and "a PIN that is the empty
/// string" are different facts, and only the first is ever meant.
fn push_typed(fields: &mut Vec<Field>, name: &str, value: String) -> Result<()> {
    if !value.is_empty() {
        fields.push(Field::secret(name, checked(name, value)?));
    }
    Ok(())
}

/// Splits `NAME=VALUE` options, refusing a malformed one or a name given twice.
fn assignments(option: &str, shape: &str, raw: &[String]) -> Result<Vec<(String, String)>> {
    let mut pairs: Vec<(String, String)> = Vec::new();
    for assignment in raw {
        let (name, value) = assignment
            .split_once('=')
            .filter(|(name, _)| !name.is_empty())
            .with_context(|| format!("{option} takes {shape}, not {assignment:?}"))?;
        if pairs.iter().any(|(seen, _)| seen == name) {
            bail!("{option} names {name:?} twice");
        }
        pairs.push((name.to_owned(), value.to_owned()));
    }
    Ok(pairs)
}

/// Checks a value on its way into a field, for the fields that have a shape:
/// a one-time password key, and the date a record stops working. The core
/// says which and how, so every way a value arrives holds it to the same.
fn checked(name: &str, value: String) -> Result<String> {
    Ok(sefy_core::model::normalize_value(name, &value)?)
}

/// Says, on stderr, that a record is past or near the last day it works.
///
/// Said where a secret is taken, because that is when it matters: a token
/// that stopped working last week is why the command about to use it will
/// fail. On stderr, so a pipe still receives the secret alone.
fn warn_if_due(item: &Item) {
    if let Some(warning) = due(item, now()) {
        eprintln!("warning: {warning}");
    }
}

/// What [`warn_if_due`] says about `item` at `now`, if anything.
fn due(item: &Item, now: i64) -> Option<String> {
    let sefy_core::expiry::Stated::Date(date) = sefy_core::expiry::of(&item.payload)? else {
        return None;
    };
    let days = date.days_left(now);
    (days <= sefy_core::expiry::SOON_DAYS).then(|| {
        format!(
            "{:?} {} ({date})",
            item.summary.title,
            crate::when::due(days)
        )
    })
}

/// The value an item hands over, and the name of what was taken.
///
/// One answer for `get` and `run`: a note gives its text, a record the field
/// named or else the one its kind is mostly about. A file and a kind this
/// build does not know give nothing — each with the way to what was meant.
/// `naming` is how the caller's command line names a field, for the messages.
fn value_of(item: &Item, field: Option<&str>, naming: &str) -> Result<(String, String)> {
    let title = &item.summary.title;
    match &item.payload {
        // A field named on a note is refused rather than ignored: whoever
        // named one expected a record, and the text may not be what they
        // meant to hand over.
        Payload::Note { text } => match field {
            None => Ok((text.clone(), "text".to_owned())),
            Some(_) => bail!("{title:?} is a note, which has no fields; leave out {naming}"),
        },
        Payload::Fields { kind, fields } => {
            let name = match field {
                Some(name) => name,
                // Nothing was named, so sefy takes what the kind is mostly
                // about. A record whose fields are all public has no such
                // field, and guessing at one would hand over the wrong value.
                None => kind
                    .template()
                    .and_then(|template| template.default_field())
                    .map(|field| field.name)
                    .with_context(|| {
                        format!("{title:?} has no default field; name one with {naming}")
                    })?,
            };
            match fields.iter().find(|field| field.name == name) {
                Some(field) => Ok((field.value.clone(), field.name.clone())),
                None => bail!(
                    "{title:?} has no {name:?}; it holds: {}",
                    field_names(fields)
                ),
            }
        }
        Payload::File { .. } => bail!(
            "{title:?} is a file; write it to disk with: sefy extract {}",
            item.summary.id
        ),
        Payload::Unknown { kind } => bail!(
            "{title:?} is a {kind}, which this version of sefy does not know\n\
             it was written by a newer sefy — upgrade to read it\n\
             (the item is safe: it is listed, exported and synced as it is)"
        ),
    }
}

/// Copies a secret to the clipboard, or prints it when asked to.
pub fn get(vault: &Vault, args: GetArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;
    let (value, description) = value_of(&item, args.field.as_deref(), "--field")?;
    warn_if_due(&item);

    if args.stdout {
        println!("{value}");
        return Ok(());
    }

    if args.clear_after > 0 {
        // Said before the wait, not after: the user needs to know why the
        // command is sitting there.
        println!(
            "copied {description} of {:?} to the clipboard; clearing in {}s",
            item.summary.title, args.clear_after
        );
    } else {
        println!(
            "copied {description} of {:?} to the clipboard",
            item.summary.title
        );
    }
    flush_stdout();

    let hold = output::to_clipboard(&value, args.clear_after)?;
    if hold.cleared {
        println!("clipboard cleared");
    }
    Ok(())
}

/// Generates a password or a passphrase, keeps it if asked, and hands it over.
///
/// `vault` is there exactly when `--save` is. The record is written before the
/// value goes to the clipboard: a clipboard that cannot be reached must not
/// cost a password the site has already accepted. It is synced before then
/// too, when syncing after a write is on: the clipboard wait can be long and
/// is often cut short, and the record should not wait on it.
pub fn generate(vault: Option<&mut Vault>, args: GenArgs, auto: &mut AutoSync) -> Result<()> {
    let recipe = if let Some(count) = args.words {
        Recipe::Words {
            count,
            language: args.lang.into(),
            separator: args.separator.clone(),
        }
    } else if args.pronounceable {
        Recipe::Pronounceable {
            length: args.length,
        }
    } else {
        Recipe::Characters {
            length: args.length,
            classes: Classes {
                uppercase: !args.no_uppercase,
                digits: !args.no_digits,
                symbols: !args.no_symbols,
            },
        }
    };
    let generated = sefy_core::generate(&recipe)?;

    // What the password must not lean on: the words of the record it is for.
    let context: Vec<&str> = [
        args.save.as_deref(),
        args.login.as_deref(),
        args.url.as_deref(),
    ]
    .into_iter()
    .flatten()
    .collect();
    let strength = sefy_core::estimate_generated(&generated.value, generated.bits, &context);

    let unit = match recipe {
        Recipe::Words { count, .. } => format!("{count} words"),
        _ => format!("{} characters", generated.value.chars().count()),
    };
    let mut description = format!(
        "generated {unit}: {:.0} bits of entropy, strength {}/{}",
        generated.bits,
        strength.score,
        Strength::MAX_SCORE
    );
    if let Some(warning) = &strength.warning {
        description.push_str(&format!(" - {warning}"));
    }

    // Under --stdout everything but the secret goes to stderr, so a pipe
    // receives the secret and nothing else.
    let say = |line: &str| {
        if args.stdout {
            eprintln!("{line}");
        } else {
            println!("{line}");
        }
    };

    if let (Some(vault), Some(title)) = (vault, &args.save) {
        let mut fields = Vec::new();
        push_optional(&mut fields, "login", args.login.clone(), false);
        fields.push(Field::secret("password", generated.value.as_str()));
        push_optional(&mut fields, "url", args.url.clone(), false);
        let id = vault.add(
            NewItem::new(title.clone(), Payload::fields(ItemKind::Login, fields))
                .with_tags(args.tag.clone()),
        )?;
        vault.save()?;
        say(&format!("added {title:?} as {id}"));
        auto.catch_up(vault);
    }
    say(&description);
    if generated.bits < sefy_core::generate::OFFLINE_BITS {
        say(&format!(
            "under {:.0} bits: fine behind a site that limits sign-in attempts, \
             too few for a master password; add length or words",
            sefy_core::generate::OFFLINE_BITS
        ));
    }

    if args.stdout {
        println!("{}", generated.value.as_str());
        return Ok(());
    }

    if args.clear_after > 0 {
        println!(
            "copied it to the clipboard; clearing in {}s",
            args.clear_after
        );
    } else {
        println!("copied it to the clipboard");
    }
    flush_stdout();

    let hold = output::to_clipboard(&generated.value, args.clear_after)?;
    if hold.cleared {
        println!("clipboard cleared");
    }
    Ok(())
}

/// Makes sure a message is on screen before a wait, not buffered behind it.
fn flush_stdout() {
    use std::io::Write;
    let _ = std::io::stdout().flush();
}

/// Shows an item's fields, keeping its secrets hidden.
pub fn show(vault: &Vault, reference: &str) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    field("id", &item.summary.id.to_string());
    field("title", &item.summary.title);
    field("kind", item.summary.kind.as_str());
    if !item.summary.tags.is_empty() {
        field("tags", &item.summary.tags.join(", "));
    }
    // Said only when there is something to go back to: a line announcing an
    // empty history on every item would be noise on the common case.
    let earlier = vault.earlier_versions(item.summary.id)?;
    if earlier > 0 {
        field(
            "history",
            &format!(
                "{} (sefy history {})",
                output::count(earlier, "earlier version"),
                item.summary.id
            ),
        );
    }

    match &item.payload {
        Payload::Note { text } => {
            println!("---");
            println!("{text}");
        }
        Payload::Fields { fields, .. } => {
            for stored in fields {
                if stored.name == sefy_core::otp::FIELD {
                    // The key is rarely what is wanted; the code it makes is.
                    field(&stored.name, "<hidden — sefy otp gives the code>");
                } else if stored.secret {
                    // Never printed here; `sefy get` is the one way a secret
                    // leaves, and it says which field to ask for by name.
                    field(
                        &stored.name,
                        &format!("<hidden — use sefy get --field {}>", stored.name),
                    );
                } else if stored.name == sefy_core::expiry::FIELD
                    && let Some(date) = sefy_core::Expiry::parse(&stored.value)
                {
                    // The distance is the part that is read; the date is
                    // what was written.
                    let days = date.days_left(now());
                    let distance = if days < 0 {
                        crate::when::due(days)
                    } else {
                        crate::when::days_away(days)
                    };
                    field(&stored.name, &format!("{} ({distance})", stored.value));
                } else {
                    field(&stored.name, &stored.value);
                }
            }
        }
        Payload::File { filename, bytes } => {
            field("file", filename);
            field("size", &format!("{} bytes", bytes.len()));
        }
        Payload::Unknown { kind } => {
            println!("---");
            println!("This item is a {kind}, a kind this version of sefy does not know.");
            println!("A newer sefy wrote it. Upgrade to read its contents.");
            println!("Nothing is lost: the item keeps its place in this vault.");
        }
    }
    Ok(())
}

/// Prints one labelled line of `sefy show`, aligned to a fixed column.
///
/// A single place to pad from: hand-spaced labels drift the moment one of them
/// is longer than the rest, and `password` already had. The width leaves a
/// space after the longest label rather than butting against it.
fn field(label: &str, value: &str) {
    // Wide enough for the longest label any built-in template uses; a longer
    // one from a field the user named themselves simply pushes its own value
    // along rather than shifting every other line.
    const LABEL_WIDTH: usize = "private-key:".len() + 1;
    println!("{:<LABEL_WIDTH$}{value}", format!("{label}:"));
}

/// Adds a field when the user gave a value for it, and leaves it out when not.
///
/// An absent option stays absent rather than being stored empty: "this login
/// has no URL" and "its URL is the empty string" are different facts, and only
/// the first one is true.
fn push_optional(fields: &mut Vec<Field>, name: &str, value: Option<String>, secret: bool) {
    if let Some(value) = value {
        fields.push(if secret {
            Field::secret(name, value)
        } else {
            Field::public(name, value)
        });
    }
}

/// The path a public key conventionally sits at, beside its private half.
fn sibling_public_key(private_key: &Path) -> PathBuf {
    let mut name = private_key.as_os_str().to_os_string();
    name.push(".pub");
    PathBuf::from(name)
}

/// Names of a record's fields, for a message that says what is on offer.
fn field_names(fields: &[Field]) -> String {
    fields
        .iter()
        .map(|field| field.name.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Lists items, optionally narrowed by kind and tags.
pub fn ls(vault: &Vault, args: ListArgs) -> Result<()> {
    let mut query = Query::all().tags(args.tag);
    if let Some(kind) = args.kind {
        query = query.kind(kind.into());
    }
    output::table(&vault.search(&query)?);
    Ok(())
}

/// Searches items by text, kind and tags.
pub fn find(vault: &Vault, args: FindArgs) -> Result<()> {
    let mut query = Query::all().tags(args.tag);
    if let Some(text) = args.text {
        query = query.text(text);
    }
    if let Some(kind) = args.kind {
        query = query.kind(kind.into());
    }
    // Always a listing. `find` is what a script calls, and a command that
    // printed a table into a pipe but opened a menu on a terminal would be two
    // commands wearing one name. Browsing is `sefy` with no arguments.
    output::table(&vault.search(&query)?);
    Ok(())
}

/// Browses the vault: pick an item, then show it.
///
/// What `sefy` with no subcommand does. The command line is exact and
/// remembering is not - this is the way in for "it is in there somewhere",
/// and it is a separate command rather than a mode of `find` so that neither
/// has to ask where it is running.
pub fn browse(vault: &Vault) -> Result<()> {
    if !crate::picker::available() {
        bail!(
            "sefy with no command opens an interactive picker, and this is not a terminal\n\
             list items with: sefy ls"
        );
    }
    pick_from(vault, &vault.list()?)
}

/// Shows the picker over `items` and acts on what comes back.
///
/// Acting means `show`: the item without its secrets. Copying the password
/// straight to the clipboard would be the quicker path and the wrong default -
/// the picker is also how someone browses their own vault, and browsing should
/// not leave a secret on the clipboard of a machine they were only looking at.
pub fn pick_from(vault: &Vault, items: &[ItemSummary]) -> Result<()> {
    if items.is_empty() {
        println!("no items");
        return Ok(());
    }

    let Some(picked) = crate::picker::choose(items, "Item")? else {
        // Escape. Nothing to say - the user closed a menu.
        return Ok(());
    };

    show(vault, &picked.id.to_string())
}

/// Changes an item's title, contents or tags.
pub fn edit(vault: &mut Vault, args: EditArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let existing = vault.get(summary.id)?;

    let payload = build_edited_payload(&existing.payload, &args)?;
    let tags = if args.clear_tags {
        Some(Vec::new())
    } else if args.tag.is_empty() {
        None
    } else {
        Some(args.tag.clone())
    };

    if args.title.is_none() && payload.is_none() && tags.is_none() {
        bail!("nothing to change; pass --title, --tag, or a field to edit");
    }

    vault.update(summary.id, args.title, payload, tags)?;
    vault.save()?;
    println!("updated {}", summary.id);
    Ok(())
}

/// Applies the edit flags to an item's current payload.
///
/// Returns `None` when no flag touches the payload, so the item keeps what it
/// has. Flags meant for another kind of item are an error rather than a silent
/// no-op.
fn build_edited_payload(existing: &Payload, args: &EditArgs) -> Result<Option<Payload>> {
    let touches_fields =
        !args.set.is_empty() || !args.set_secret.is_empty() || !args.unset.is_empty();

    match existing {
        Payload::Note { text: current } => {
            if touches_fields {
                bail!("this item is a note; --set, --set-secret and --unset apply to records");
            }
            if args.editor {
                return Ok(Some(Payload::Note {
                    text: crate::editor::edit(current)?,
                }));
            }
            Ok(args.text.clone().map(|text| Payload::Note { text }))
        }
        Payload::Fields { kind, fields } => {
            if args.text.is_some() || args.editor {
                bail!("this item is a {kind}; --text and --editor apply to notes");
            }
            if !touches_fields {
                return Ok(None);
            }
            Ok(Some(Payload::Fields {
                kind: kind.clone(),
                fields: edit_fields(kind, fields, args)?,
            }))
        }
        Payload::File { .. } => {
            if args.text.is_some() || args.editor || touches_fields {
                bail!("this item is a file; only --title and tags can be edited");
            }
            Ok(None)
        }
        // Title and tags live beside the contents, not inside them, so they can
        // still be changed — returning `None` here leaves the payload alone and
        // lets the caller apply them. Anything that would rewrite the contents
        // is refused: this build cannot read them and must not replace them.
        Payload::Unknown { kind } => {
            if args.text.is_some() || args.editor || touches_fields {
                bail!(
                    "this item is a {kind}, a kind this version of sefy does not know;\n\
                     only --title and tags can be edited"
                );
            }
            Ok(None)
        }
    }
}

/// Applies `--set`, `--set-secret` and `--unset` to a record's fields.
///
/// A field keeps its place: an edit changes what a record says, not the order
/// it reads in. A field that is new lands at the end, unless the kind's
/// template has an opinion about where it belongs.
fn edit_fields(kind: &ItemKind, existing: &[Field], args: &EditArgs) -> Result<Vec<Field>> {
    let mut fields = existing.to_vec();

    for assignment in &args.set {
        let (name, value) = assignment
            .split_once('=')
            .with_context(|| format!("--set takes NAME=VALUE, not {assignment:?}"))?;
        // A value passed on the command line is public by default: it has
        // already been through the shell history, so calling it secret would
        // be a promise sefy cannot keep. An existing field keeps whatever
        // secrecy it was stored with — the user is changing the value, not
        // declaring the field harmless.
        set_field(
            kind,
            &mut fields,
            name,
            checked(name, value.to_owned())?,
            None,
        );
    }

    for name in &args.set_secret {
        let value = session::secret(&format!("New value for {name}: "), None)?;
        set_field(kind, &mut fields, name, checked(name, value)?, Some(true));
    }

    for name in &args.unset {
        let before = fields.len();
        fields.retain(|field| &field.name != name);
        if fields.len() == before {
            bail!(
                "no field named {name:?}; it holds: {}",
                field_names(existing)
            );
        }
    }

    if fields.is_empty() {
        bail!("a {kind} cannot be left without any field");
    }
    Ok(fields)
}

/// Writes one field, in place if it is already there and at the end if not.
fn set_field(
    kind: &ItemKind,
    fields: &mut Vec<Field>,
    name: &str,
    value: String,
    secret: Option<bool>,
) {
    if let Some(field) = fields.iter_mut().find(|field| field.name == name) {
        field.value = value;
        if let Some(secret) = secret {
            field.secret = secret;
        }
        return;
    }

    // A name the template knows brings the template's idea of secrecy with it,
    // so `--set totp=…` on a login is hidden without having to be told.
    let secret = secret.unwrap_or_else(|| {
        kind.template()
            .and_then(|template| template.field(name))
            .is_some_and(|field| field.secret)
    });
    fields.push(Field {
        name: name.to_owned(),
        value,
        secret,
    });
}

/// Lists the versions of an item's contents, or compares one with now.
pub fn history(vault: &Vault, args: HistoryArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    refuse_unknown(&summary)?;
    let versions = vault.history(summary.id)?;

    match args.version {
        None => list_versions(&summary, &versions),
        Some(number) => {
            let index = version_index(&summary, &versions, number)?;
            compare_with_now(&summary, &versions, index);
        }
    }
    Ok(())
}

/// Brings back an earlier version of an item's contents, or one field of it.
pub fn restore(vault: &mut Vault, args: RestoreArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    refuse_unknown(&summary)?;
    let versions = vault.history(summary.id)?;
    let index = version_index(&summary, &versions, args.version)?;
    let wanted = &versions[index];
    let title = &summary.title;

    if wanted.current {
        println!(
            "version {} is what {title:?} holds now; nothing to restore",
            args.version
        );
        return Ok(());
    }
    if let Some(name) = &args.field
        && !matches!(wanted.payload, Payload::Fields { .. })
    {
        bail!(
            "{title:?} is a {}, which is restored whole; leave out --field {name}",
            summary.kind
        );
    }

    let changed = match vault.restore(summary.id, &wanted.uuid, args.field.as_deref()) {
        Ok(changed) => changed,
        Err(sefy_core::Error::FieldNotInVersion { name, available }) => bail!(
            "version {} of {title:?} has no {name:?}; it held: {}",
            args.version,
            available.join(", ")
        ),
        Err(other) => return Err(other.into()),
    };
    if !changed {
        println!(
            "nothing to restore: {title:?} already holds what version {} did{}",
            args.version,
            args.field
                .as_deref()
                .map(|name| format!(" in {name}"))
                .unwrap_or_default()
        );
        return Ok(());
    }
    vault.save()?;

    let what = match &args.field {
        Some(name) => format!("the {name} of {title:?}"),
        None => format!("{title:?}"),
    };
    println!(
        "restored {what} from version {} ({})",
        args.version,
        written(wanted)
    );
    println!(
        "what it replaced is kept as version {}; sefy history {} lists them",
        versions.len(),
        summary.id
    );
    Ok(())
}

/// Stops at an item whose contents this build cannot read.
fn refuse_unknown(summary: &ItemSummary) -> Result<()> {
    if !summary.kind.is_known() {
        bail!(
            "{:?} is a {}, which this version of sefy does not know\n\
             it was written by a newer sefy — upgrade to read its history",
            summary.title,
            summary.kind
        );
    }
    Ok(())
}

/// Turns the number a listing showed into a place in the history.
fn version_index(summary: &ItemSummary, versions: &[Version], number: usize) -> Result<usize> {
    if number == 0 || number > versions.len() {
        bail!(
            "{:?} has {}, numbered from 1; there is no version {number}",
            summary.title,
            output::count(versions.len(), "version")
        );
    }
    Ok(number - 1)
}

/// When and where a version was written, for a line about it.
fn written(version: &Version) -> String {
    match &version.device {
        Some(device) => format!(
            "written {} on {device}",
            crate::when::date_time(version.made_at)
        ),
        None => format!("written {}", crate::when::date_time(version.made_at)),
    }
}

/// Prints one line per version, oldest first: when, where, and what changed.
fn list_versions(summary: &ItemSummary, versions: &[Version]) {
    println!(
        "{:?} ({}), {}",
        summary.title,
        summary.kind,
        output::count(versions.len(), "version")
    );
    println!();

    let number_width = versions.len().to_string().len();
    let device_width = versions
        .iter()
        .map(|version| {
            version
                .device
                .as_deref()
                .map_or(1, |name| name.chars().count())
        })
        .max()
        .unwrap_or(1);

    for (index, version) in versions.iter().enumerate() {
        let mut what = if index == 0 {
            // The first kept version is the item's creation only if it is
            // dated then; one migrated from before history is simply the
            // earliest there is.
            if version.made_at == summary.created_at {
                "created".to_owned()
            } else {
                "earliest kept".to_owned()
            }
        } else {
            let names = sefy_core::history::changed(&versions[index - 1].payload, &version.payload);
            if names.is_empty() {
                "no change".to_owned()
            } else {
                names.join(", ")
            }
        };
        if version.conflict {
            what.push_str("  (lost a merge conflict)");
        }
        if version.current {
            what.push_str("  (current)");
        }
        println!(
            "  {:>number_width$}  {}  {:<device_width$}  {what}",
            index + 1,
            crate::when::date_time(version.made_at),
            version.device.as_deref().unwrap_or("-"),
        );
    }

    if versions.len() > 1 {
        println!();
        println!(
            "compare one with now: sefy history {id} VERSION\n\
             bring one back:       sefy restore {id} VERSION{by_field}",
            id = summary.id,
            by_field = if summary.kind.is_record() {
                " [--field NAME]"
            } else {
                ""
            }
        );
    } else {
        println!();
        println!("no earlier versions yet; the next change to its contents keeps this one");
    }
}

/// Shows how one version differs from the current contents, part by part.
///
/// A secret is only ever said to differ. Text — a note, a public field, a file
/// name — is shown line by line, with long unchanged stretches folded.
fn compare_with_now(summary: &ItemSummary, versions: &[Version], index: usize) {
    let then = &versions[index];
    let now = versions
        .last()
        .expect("history ends with the current version");
    let number = index + 1;

    if then.current {
        println!(
            "version {number} is what {:?} holds now; there is nothing to compare it with",
            summary.title
        );
        return;
    }
    println!(
        "version {number} of {:?}, {}, against what it holds now (version {}):",
        summary.title,
        written(then),
        versions.len()
    );
    println!();

    let changes: Vec<Change> = sefy_core::history::compare(&then.payload, &now.payload);
    let width = changes
        .iter()
        .map(|change| change.name.chars().count())
        .max()
        .unwrap_or(0);

    for change in &changes {
        let label = format!("{:<width$}", change.name);
        match (change.kind, change.secret) {
            (ChangeKind::Same, _) => println!("{label}  same"),
            (ChangeKind::Changed, true) => {
                println!(
                    "{label}  {}",
                    secret_difference(change, &then.payload, &now.payload)
                );
            }
            (ChangeKind::Removed, true) => println!("{label}  only in version {number} (secret)"),
            (ChangeKind::Added, true) => println!("{label}  only now (secret)"),
            (ChangeKind::Changed, false) => {
                println!("{label}  changed");
                let old = sefy_core::history::text_of(&then.payload, &change.name).unwrap_or("");
                let new = sefy_core::history::text_of(&now.payload, &change.name).unwrap_or("");
                crate::diff::print(&sefy_core::history::lines(old, new));
            }
            (ChangeKind::Removed, false) => {
                println!("{label}  only in version {number}");
                let old = sefy_core::history::text_of(&then.payload, &change.name).unwrap_or("");
                crate::diff::print(&sefy_core::history::lines(old, ""));
            }
            (ChangeKind::Added, false) => {
                println!("{label}  only now");
                let new = sefy_core::history::text_of(&now.payload, &change.name).unwrap_or("");
                crate::diff::print(&sefy_core::history::lines("", new));
            }
        }
    }

    if changes.iter().any(|change| change.kind != ChangeKind::Same) {
        println!();
        println!(
            "bring it back: sefy restore {} {number}{}",
            summary.id,
            if matches!(then.payload, Payload::Fields { .. }) {
                " [--field NAME]"
            } else {
                ""
            }
        );
    }
}

/// How a secret part differs, without a word of what it holds.
///
/// A file's bytes are the one secret part whose size is worth saying: it tells
/// two versions of a key file apart without showing either.
fn secret_difference(change: &Change, then: &Payload, now: &Payload) -> String {
    match (then, now) {
        (Payload::File { bytes: old, .. }, Payload::File { bytes: new, .. })
            if change.name == "contents" =>
        {
            format!(
                "changed ({} then, {} now)",
                output::count(old.len(), "byte"),
                output::count(new.len(), "byte")
            )
        }
        _ => "changed (secret, not shown)".to_owned(),
    }
}

/// Removes an item, asking first unless told not to.
pub fn rm(vault: &mut Vault, reference: &str, yes: bool) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;

    // The history goes with the item, and a question that did not say so
    // would be asking about less than it removes.
    let earlier = vault.earlier_versions(summary.id)?;
    let and_history = if earlier > 0 {
        format!(" and {}", output::count(earlier, "earlier version"))
    } else {
        String::new()
    };
    if !yes
        && !confirm(&format!(
            "remove {:?} ({}){and_history}? [y/N] ",
            summary.title, summary.id
        ))?
    {
        println!("kept");
        return Ok(());
    }

    vault.remove(summary.id)?;
    vault.save()?;
    println!("removed {}", summary.id);
    Ok(())
}

/// Writes a stored file back to disk.
pub fn extract(
    vault: &Vault,
    reference: &str,
    output_path: Option<PathBuf>,
    force: bool,
) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    let Payload::File { filename, bytes } = &item.payload else {
        bail!(
            "{:?} is a {}, not a file",
            item.summary.title,
            item.summary.kind
        );
    };

    let destination = output_path.unwrap_or_else(|| PathBuf::from(filename));
    if destination.exists() && !force {
        bail!(
            "{} already exists; pass --force to overwrite",
            destination.display()
        );
    }

    std::fs::write(&destination, bytes)
        .with_context(|| format!("cannot write {}", destination.display()))?;
    println!("wrote {} ({} bytes)", destination.display(), bytes.len());
    Ok(())
}

/// Lists the tags in use with their item counts.
pub fn tags(vault: &Vault) -> Result<()> {
    let tags = vault.tags()?;
    if tags.is_empty() {
        println!("no tags");
        return Ok(());
    }
    let width = tags
        .iter()
        .map(|(name, _)| name.chars().count())
        .max()
        .unwrap_or(4);
    for (name, count) in tags {
        println!("{name:<width$}  {count}");
    }
    Ok(())
}

/// Writes the vault's contents out in the clear, in the chosen format.
pub fn export(
    vault: &Vault,
    output_path: Option<PathBuf>,
    format: ExportFormat,
    with_history: bool,
    acknowledged: bool,
    force: bool,
) -> Result<()> {
    if !acknowledged {
        bail!(
            "export writes every secret in this vault in the clear\n\
             the resulting file protects nothing - encrypt it, or delete it when done\n\
             pass --i-know-this-writes-plaintext to go ahead"
        );
    }
    let target = match (format, with_history) {
        (ExportFormat::Sefy, history) => Target::Sefy { history },
        (ExportFormat::Keepass, history) => Target::KeePass { history },
        (ExportFormat::Csv, false) => Target::Csv,
        (ExportFormat::Csv, true) => bail!(
            "a CSV has no place for earlier versions\n\
             use --format keepass or --format sefy to carry them"
        ),
    };
    if let Some(path) = &output_path
        && path.exists()
        && !force
    {
        bail!(
            "{} already exists; pass --force to overwrite",
            path.display()
        );
    }

    let exported = sefy_core::exchange::export(vault, target)?;
    let report = &exported.report;

    match &output_path {
        Some(path) => {
            std::fs::write(path, exported.text.as_bytes())
                .with_context(|| format!("cannot write {}", path.display()))?;
            let mut written = output::count(report.written, "item");
            if report.versions > 0 {
                written.push_str(&format!(
                    " and {}",
                    output::count(report.versions, "earlier version")
                ));
            }
            eprintln!("wrote {} in the clear: {written}", path.display());
        }
        None => println!("{}", exported.text.as_str()),
    }

    // On stderr either way, so a pipe receives the file and nothing else.
    if !report.left_out.is_empty() {
        let kinds: Vec<String> = report
            .left_out
            .iter()
            .map(|(kind, count)| output::count(*count, kind.as_str()))
            .collect();
        eprintln!(
            "left out: {} - {} holds logins only; --format keepass carries every kind",
            kinds.join(", "),
            target.name()
        );
    }
    if report.trimmed > 0 {
        eprintln!(
            "{} {} fields a CSV has no column for; those fields are left out",
            output::count(report.trimmed, "login"),
            if report.trimmed == 1 { "has" } else { "have" }
        );
    }
    if report.unreadable > 0 {
        let what = match target {
            Target::Sefy { .. } => "written without its contents",
            _ => "left out",
        };
        eprintln!(
            "{} of a kind this version of sefy does not know: {what}",
            output::count(report.unreadable, "item")
        );
    }
    Ok(())
}

/// Adds what another sefy, a password manager or a browser exported.
pub fn import(vault: &mut Vault, input: Option<PathBuf>) -> Result<()> {
    let bytes = Zeroizing::new(match &input {
        Some(path) => {
            std::fs::read(path).with_context(|| format!("cannot read {}", path.display()))?
        }
        None => {
            let mut bytes = Vec::new();
            std::io::stdin()
                .read_to_end(&mut bytes)
                .context("cannot read the file to import from stdin")?;
            bytes
        }
    });
    let text = std::str::from_utf8(&bytes).map_err(|_| {
        anyhow::anyhow!(
            "the file is not UTF-8 text\n\
             save it again as UTF-8 - spreadsheet programs offer it as \"CSV UTF-8\""
        )
    })?;

    let report = sefy_core::exchange::import(vault, text)?;

    let added = report.added_total();
    let mut line = format!(
        "imported {} from {}",
        output::count(added, "item"),
        report.format.describe()
    );
    if added > 0 {
        let kinds: Vec<String> = report
            .added
            .iter()
            .map(|(kind, count)| output::count(*count, kind.as_str()))
            .collect();
        line.push_str(&format!(": {}", kinds.join(", ")));
    }
    println!("{line}");
    if report.versions > 0 {
        println!(
            "with {} kept in their history",
            output::count(report.versions, "earlier version")
        );
    }
    if report.skipped > 0 {
        // Silence here would read as "imported nothing" on a re-import, when
        // what actually happened is that the vault already had it all.
        println!(
            "{} already here, left alone",
            output::count(report.skipped, "item")
        );
    }

    for (outcome, heading) in [
        (Outcome::NotImported, "not imported:"),
        (Outcome::InPart, "imported in part:"),
        (Outcome::Reshaped, "imported in another shape:"),
    ] {
        let notices: Vec<_> = report
            .notices
            .iter()
            .filter(|notice| notice.outcome == outcome)
            .collect();
        if notices.is_empty() {
            continue;
        }
        println!("{heading}");
        for notice in notices {
            println!("  {:?} - {}", notice.title, notice.reason);
        }
    }
    if !report.columns_left_out.is_empty() {
        println!(
            "columns left out as the exporting program's own bookkeeping: {}",
            report.columns_left_out.join(", ")
        );
    }

    if let Some(kept) = &report.kept_copy {
        println!("{}", kept_line(kept));
    }
    if let Some(path) = input {
        println!(
            "{} still holds all of it in the clear; delete it once the import looks right",
            path.display()
        );
    }
    Ok(())
}

/// Folds another vault file into this one, or says what doing so would change.
pub fn merge(
    vault: &mut Vault,
    other: &Path,
    other_password_env: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    if other == vault.path() {
        bail!("that is this vault; merging a file into itself would do nothing");
    }

    // Asked for separately: a copy from another machine may be under a
    // different password, and assuming otherwise would just fail confusingly.
    let password = session::secret(
        &format!("Password for {}: ", other.display()),
        other_password_env,
    )?;
    let source = session::open(other, &password)?;

    if dry_run {
        let report = sefy_core::merge::preview(vault, &source)?;
        println!("here, from {}:", other.display());
        print_lines(&preview_lines(&report, true));
        println!("{NOTHING_DONE}");
        return Ok(());
    }

    let report = sefy_core::merge(vault, &source)?;

    print_lines(&merge_lines(
        &report,
        "nothing to merge; the two vaults already agree",
    ));
    Ok(())
}

/// Replaces the master password and rewrites the file under it.
pub fn change_password(vault: &mut Vault, password_env: Option<&str>) -> Result<()> {
    let password = session::new_password(password_env)?;
    let change = vault.change_password(password.as_bytes())?;
    println!("password changed");
    if change.resealed > 0 {
        println!(
            "{} beside the vault sealed under it too",
            output::count(change.resealed, "copy")
        );
    }
    for left in &change.left {
        // Named rather than deleted: it is not known what it is, only that the
        // old password does not open it.
        println!(
            "{} does not open under the old password and was left as it was",
            left.display()
        );
    }
    // Whoever holds the old password is holding a password that opens nothing
    // here any more, and whose retiring was presumably the point.
    let locked = session::lock_everywhere();
    if !locked.is_empty() {
        println!(
            "locked the {}: it held the old password",
            locked.join(" and the ")
        );
    }
    Ok(())
}

/// Opens an item's site and puts its password on the clipboard.
///
/// The two halves of signing in, in the order they are used: the browser is
/// already loading while the password is waiting to be pasted. Doing it as one
/// command also removes the step where a user goes looking for the URL, finds
/// it with `show`, and copies it by hand from a terminal.
///
/// The clipboard is the same path `get` uses, timeout and all: a password left
/// on the clipboard after the browser is open is exactly the exposure the
/// timeout exists for, and the browser being open does not change it.
pub fn open(vault: &Vault, args: OpenArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    let Payload::Fields { kind, fields } = &item.payload else {
        bail!(
            "{:?} is a {}, which has no site to open",
            item.summary.title,
            item.summary.kind.as_str()
        );
    };

    let url = fields
        .iter()
        .find(|field| field.name == URL_FIELD)
        .with_context(|| {
            format!(
                "{:?} has no {URL_FIELD:?} field; it holds: {}\n\
                 add one with: sefy edit {} --set url=https://…",
                item.summary.title,
                field_names(fields),
                item.summary.id
            )
        })?;

    crate::browser::open(&url.value)?;
    println!("opened {}", url.value);
    warn_if_due(&item);

    if args.no_password {
        return Ok(());
    }

    // The password is a convenience on top of opening the site, so a record
    // without one is not an error: the site is open, which is what was asked.
    let Some(secret) = kind
        .template()
        .and_then(|template| template.default_field())
        .and_then(|spec| fields.iter().find(|field| field.name == spec.name))
    else {
        return Ok(());
    };

    println!(
        "copied {} of {:?} to the clipboard; clearing in {}s",
        secret.name, item.summary.title, args.clear_after
    );
    flush_stdout();

    let hold = output::to_clipboard(&secret.value, args.clear_after)?;
    if hold.cleared {
        println!("clipboard cleared");
    }
    Ok(())
}

/// Copies a record's current one-time code, storing or drawing its key first
/// when asked.
///
/// `--set` is the moment of enrolment: the site shows a key and asks for the
/// first code to prove it was taken. Storing and answering are one command so
/// the key is in the vault before the site considers two-factor sign-in on.
pub fn otp(vault: &mut Vault, args: OtpArgs, auto: &mut AutoSync) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;
    let title = &item.summary.title;
    let Payload::Fields { kind, fields } = &item.payload else {
        bail!(
            "{title:?} is a {}; one-time passwords belong to a record such as a login",
            item.summary.kind
        );
    };
    let mut fields = fields.clone();
    warn_if_due(&item);

    // Under --stdout everything but the code goes to stderr, so a pipe
    // receives the code and nothing else.
    let say = |line: &str| {
        if args.stdout {
            eprintln!("{line}");
        } else {
            println!("{line}");
        }
    };

    if args.set || args.key_env.is_some() {
        let key = session::secret("Setup key or otpauth:// link: ", args.key_env.as_deref())?;
        let key = checked(sefy_core::otp::FIELD, key)?;
        set_field(kind, &mut fields, sefy_core::otp::FIELD, key, Some(true));
        vault.update(
            summary.id,
            None,
            Some(Payload::Fields {
                kind: kind.clone(),
                fields: fields.clone(),
            }),
            None,
        )?;
        vault.save()?;
        say(&format!("stored the one-time password key of {title:?}"));
        // Before the code or the picture: both can wait on the person for a
        // while, and the key should reach the other machines regardless.
        auto.catch_up(vault);
    }

    let stored = fields
        .iter()
        .find(|field| field.name == sefy_core::otp::FIELD)
        .with_context(|| {
            format!(
                "{title:?} has no one-time password key\n\
                 store the one the site shows with: sefy otp {} --set",
                summary.id
            )
        })?;
    let totp = Totp::parse(&stored.value).with_context(|| {
        format!(
            "the {} field of {title:?} cannot make a code\n\
             replace it with: sefy otp {} --set",
            sefy_core::otp::FIELD,
            summary.id
        )
    })?;

    if args.qr {
        let login = fields
            .iter()
            .find(|field| field.name == "login")
            .map(|field| field.value.as_str());
        return crate::qr::show(&totp.link(title, login));
    }

    let now = unix_now()?;
    let code = totp.code_at(now);
    if args.stdout {
        println!("{code}");
        return Ok(());
    }

    let valid = totp.remaining(now);
    if args.clear_after > 0 {
        println!(
            "copied the one-time code of {title:?} to the clipboard; \
             valid for {valid}s, clearing in {}s",
            args.clear_after
        );
    } else {
        println!("copied the one-time code of {title:?} to the clipboard; valid for {valid}s");
    }
    flush_stdout();

    let hold = output::to_clipboard(&code, args.clear_after)?;
    if hold.cleared {
        println!("clipboard cleared");
    }
    Ok(())
}

/// Hands over a record's fields one at a time, Enter between them.
///
/// Which fields, and in what order, is the template's word: a login gives its
/// login, its password and a one-time code, a card its number, holder, the
/// month it runs out and CVV. A one-time code is made when its turn comes rather than up front,
/// so time spent on the fields before it does not eat into its life.
pub fn fill(vault: &Vault, args: FillArgs) -> Result<()> {
    use std::io::IsTerminal;

    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;
    let title = &item.summary.title;
    let Payload::Fields { kind, fields } = &item.payload else {
        bail!(
            "{title:?} is a {}; fill hands over the fields of a record such as a login",
            item.summary.kind
        );
    };

    let steps: Vec<&Field> = kind
        .template()
        .into_iter()
        .flat_map(|template| template.fill_order())
        .filter_map(|spec| fields.iter().find(|field| field.name == spec.name))
        .collect();
    if steps.is_empty() {
        bail!(
            "{title:?} holds nothing a {kind} fills in; it holds: {}\n\
             take a field with: sefy get {} --field NAME",
            field_names(fields),
            summary.id
        );
    }
    if !std::io::stdin().is_terminal() {
        bail!(
            "fill waits for Enter between fields, and input is not a terminal\n\
             take one field at a time with: sefy get {} --field NAME --stdout",
            summary.id
        );
    }
    warn_if_due(&item);

    let mut clipboard = output::open_clipboard()?;
    let total = steps.len();
    for (index, field) in steps.iter().enumerate() {
        let (value, label) = if field.name == sefy_core::otp::FIELD {
            let totp = Totp::parse(&field.value).with_context(|| {
                format!(
                    "the {} field of {title:?} cannot make a code\n\
                     replace it with: sefy otp {} --set",
                    sefy_core::otp::FIELD,
                    summary.id
                )
            })?;
            let now = unix_now()?;
            (
                totp.code_at(now),
                format!("one-time code (valid for {}s)", totp.remaining(now)),
            )
        } else if field.name == sefy_core::expiry::FIELD
            && let Some(date) = sefy_core::Expiry::parse(&field.value)
        {
            // As printed on a card, which is what a payment form asks for.
            (
                date.printed(),
                format!("{} ({})", field.name, date.printed()),
            )
        } else {
            (field.value.clone(), field.name.clone())
        };
        let position = format!("{}/{total}", index + 1);

        if index + 1 < total {
            clipboard.put(&value)?;
            print!("{position} {label} is on the clipboard; paste it, then press Enter ");
            flush_stdout();
            let mut line = String::new();
            if std::io::stdin().read_line(&mut line)? == 0 {
                // Input closed mid-way: nothing more will be pasted, so what
                // is on the clipboard now has no reason to stay there.
                clipboard.take_back(&value);
                println!();
                bail!("input closed before the last field; the clipboard is cleared");
            }
        } else {
            if args.clear_after > 0 {
                println!(
                    "{position} {label} is on the clipboard; clearing in {}s",
                    args.clear_after
                );
            } else {
                println!("{position} {label} is on the clipboard");
            }
            flush_stdout();
            let hold = clipboard.hold(&value, args.clear_after)?;
            if hold.cleared {
                println!("clipboard cleared");
            }
            break;
        }
    }
    Ok(())
}

/// Starts a command with secrets from the vault in its environment.
///
/// Every variable is settled before anything starts: a reference that matches
/// nothing, or two things, stops the run rather than starting the command with
/// part of what it needs. The vault is closed first, and the variable that
/// carried the master password is left out of the command's environment — the
/// command was given a token, not the key to every other secret.
pub fn run(
    vault: Vault,
    args: RunArgs,
    password_env: Option<&str>,
) -> Result<std::convert::Infallible> {
    let mappings = args
        .env
        .iter()
        .map(|assignment| Mapping::parse(assignment))
        .collect::<Result<Vec<_>>>()?;

    // Compared without case on every system: Windows holds one variable under
    // both spellings, and a script refused here is one that would have lost a
    // value there.
    for (index, mapping) in mappings.iter().enumerate() {
        if let Some(earlier) = mappings[..index]
            .iter()
            .find(|earlier| earlier.variable.eq_ignore_ascii_case(mapping.variable))
        {
            if earlier.variable == mapping.variable {
                bail!("--env sets {} twice", mapping.variable);
            }
            bail!(
                "--env sets {} and {}, which Windows holds as one variable",
                earlier.variable,
                mapping.variable
            );
        }
    }

    let mut set = Vec::with_capacity(mappings.len());
    for mapping in &mappings {
        let value = mapping
            .value(&vault)
            .with_context(|| format!("cannot set {}", mapping.variable))?;
        set.push((mapping.variable.to_owned(), value));
    }
    drop(vault);

    let (program, arguments) = args
        .command
        .split_first()
        .context("no command to run; name one after --")?;
    Ok(crate::launch::replace_with(
        program,
        arguments,
        password_env,
        set,
    )?)
}

/// One `--env VAR=REFERENCE[#FIELD]` of `sefy run`.
struct Mapping<'a> {
    variable: &'a str,
    reference: &'a str,
    field: Option<&'a str>,
}

impl<'a> Mapping<'a> {
    fn parse(assignment: &'a str) -> Result<Self> {
        let malformed = || format!("--env takes VAR=REFERENCE[#FIELD], not {assignment:?}");
        let (variable, target) = assignment
            .split_once('=')
            .filter(|(variable, target)| !variable.is_empty() && !target.is_empty())
            .with_context(malformed)?;
        // The last `#` is the one that splits: no field of a template has one
        // in its name, and a title that does is still reachable by its id.
        let (reference, field) = match target.rsplit_once('#') {
            Some((reference, field)) if !reference.is_empty() && !field.is_empty() => {
                (reference, Some(field))
            }
            Some(_) => bail!(
                "{}\n\
                 a # starts a field name; an item whose title has one is taken by its id",
                malformed()
            ),
            None => (target, None),
        };
        Ok(Self {
            variable,
            reference,
            field,
        })
    }

    fn value(&self, vault: &Vault) -> Result<String> {
        let summary = vault.resolve(self.reference).map_err(output::explain)?;
        let item = vault.get(summary.id)?;
        let (value, name) = value_of(&item, self.field, "#FIELD")?;
        warn_if_due(&item);
        // Refused here rather than left to the system: it would surface as the
        // command failing to start, which points at the command.
        if value.contains('\0') {
            bail!(
                "the {name} of {:?} holds a NUL character, which a variable cannot carry",
                item.summary.title
            );
        }
        Ok(value)
    }
}

/// Seconds since the epoch, for making a one-time code.
///
/// An error rather than a zero when the clock is set before 1970: a code made
/// for the wrong time is not a code, and failing to sign in with it would say
/// nothing about why.
fn unix_now() -> Result<u64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .context("the system clock is set before 1970; a one-time code needs the real time")
}

/// The field `sefy open` looks for.
///
/// Named here rather than inline so the templates and this command cannot
/// drift apart silently — a gate checks that every kind which could be opened
/// declares it.
const URL_FIELD: &str = "url";

/// Reports what and where this vault is, without revealing any of it.
///
/// The question it answers is the one asked after a new machine, a restore or a
/// week away: is this the right file, is everything in it, and has it reached
/// the other side lately. Every line is about shape — counts, versions, the
/// last transfer — and never about contents: a status that named an item would
/// put a secret's title on a screen that was asked only whether the vault is
/// there.
///
/// It never asks for the password. With the vault locked and no password given
/// it says what can be said without one: that is the answer to "is it locked",
/// and a command that held that answer back behind a prompt would be asking for
/// the master password of someone who might have asked because they were about
/// to walk away.
pub fn status(path: &Path, password_env: Option<&str>) -> Result<()> {
    let opened = match password_env {
        Some(_) => Some(session::typed(path, password_env)?),
        None => session::looking_through_agent(path)?,
    };
    let Some((vault, master)) = opened else {
        let file =
            std::fs::metadata(path).with_context(|| format!("cannot read {}", path.display()))?;
        println!("vault    {}", path.display());
        println!("size     {}", size(file.len()));
        println!("lock     {}", session::lock_line(path, None)?);
        println!("the rest takes the password: `sefy agent` unlocks the vault for a while");
        return Ok(());
    };

    let status = vault.status()?;
    let stats = &status.stats;

    println!("vault    {}", status.path.display());
    if let Some(bytes) = status.size {
        println!("size     {}", size(bytes));
    }
    println!("lock     {}", session::lock_line(path, Some(&master))?);
    println!(
        "items    {}{}",
        output::count(stats.items, "item"),
        if stats.by_kind.is_empty() {
            String::new()
        } else {
            let breakdown: Vec<String> = stats
                .by_kind
                .iter()
                .map(|(kind, count)| format!("{count} {kind}"))
                .collect();
            format!("  ({})", breakdown.join(", "))
        }
    );
    println!("tags     {}", output::count(stats.tags, "tag"));

    // The schema the file carries, with a word about what it means, because
    // "schema 4" alone tells a user nothing they can act on.
    let schema = if stats.written_by_newer() {
        format!("{} (written by a newer sefy)", stats.schema)
    } else {
        format!("{}", stats.schema)
    };
    println!("schema   {schema}");
    println!("sealed   {}", sealing(&status.sealing));

    match &stats.last_sync {
        Some(stamp) => println!(
            "synced   {} through {} ({})",
            crate::when::moment(stamp.at, now()),
            stamp.transport,
            stamp.operation
        ),
        None => println!("synced   never"),
    }

    println!("copies   {}", copies_line(&status.copies));

    let plugins = sefy_core::plugin::discover_in(&sefy_core::plugin::search_paths());
    if plugins.is_empty() {
        println!("plugins  none installed");
    } else {
        let names: Vec<String> = plugins
            .iter()
            .map(|plugin| {
                if plugin.usable {
                    plugin.name().to_owned()
                } else {
                    format!("{} (unusable)", plugin.name())
                }
            })
            .collect();
        println!("plugins  {}", names.join(", "));
    }

    Ok(())
}

/// How the vault is sealed, in one line: the key derivation and its cost, the
/// cipher, the format.
fn sealing(sealing: &sefy_core::Sealing) -> String {
    format!(
        "{} ({} MiB, {} passes, {} lanes), {}, format v{}",
        sealing.kdf,
        sealing.memory_kib / 1024,
        sealing.passes,
        sealing.lanes,
        sealing.cipher,
        sealing.format
    )
}

/// The copies kept beside a vault, in one phrase: how many, and how old the
/// most recent is.
pub(crate) fn copies_line(copies: &[sefy_core::copies::Copy]) -> String {
    let Some(newest) = copies.first() else {
        return "none yet; one is kept before a merge or an import changes the vault".to_owned();
    };
    let taken = newest
        .taken
        .and_then(|taken| taken.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|elapsed| {
            format!(
                ", newest {}",
                crate::when::moment(elapsed.as_secs() as i64, now())
            )
        })
        .unwrap_or_default();
    format!(
        "{} beside the vault{taken}",
        output::count(copies.len(), "copy")
    )
}

/// A number of bytes, in units a person reads.
pub(crate) fn size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    if bytes < KB {
        format!("{bytes} B")
    } else if bytes < MB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    }
}

/// Unix seconds, for rendering how long ago something happened.
pub(crate) fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs() as i64)
        .unwrap_or(0)
}

/// Sends the vault file to the remote.
pub fn push(vault: &mut Vault, args: RemoteArgs) -> Result<()> {
    let plugin = transport(args.transport.as_deref())?;
    let report = sefy_core::push(vault, &plugin, &args.name)?;

    println!("pushed {:?} through {}", args.name, plugin.name());
    if let Some(message) = report.message {
        println!("{message}");
    }
    Ok(())
}

/// Fetches the remote copy and folds it in, or says what that would change.
pub fn pull(vault: &mut Vault, args: PullArgs, master: &Master) -> Result<()> {
    let plugin = transport(args.remote.transport.as_deref())?;
    let remote_password = remote_password(&args)?;
    let opener = opener_of_remote(remote_password.as_ref(), master);
    let name = &args.remote.name;

    if args.dry_run {
        let report = sefy_core::sync::preview_pull(vault, &plugin, name, opener)?;
        println!("here, from {name:?} through {}:", plugin.name());
        print_lines(&preview_lines(&report.merged, true));
        println!("{NOTHING_DONE}");
        return Ok(());
    }

    let report = sefy_core::pull(vault, &plugin, name, opener)?;

    println!("pulled {name:?} through {}", plugin.name());
    if let Some(message) = &report.transport.message {
        println!("{message}");
    }
    print_lines(&merge_lines(&report.merged, NOTHING_CAME_BACK));
    Ok(())
}

/// Pulls, then pushes the result back; or says what each leg would change.
pub fn sync(vault: &mut Vault, args: PullArgs, master: &Master) -> Result<()> {
    let plugin = transport(args.remote.transport.as_deref())?;
    let remote_password = remote_password(&args)?;
    let opener = opener_of_remote(remote_password.as_ref(), master);
    let name = &args.remote.name;

    if args.dry_run {
        let preview = sefy_core::sync::preview_sync(vault, &plugin, name, opener)?;
        println!("here, from {name:?} through {}:", plugin.name());
        print_lines(&preview_lines(&preview.coming, true));
        println!("there, once the result is pushed:");
        print_lines(&preview_lines(&preview.going, false));
        println!("{NOTHING_DONE}");
        return Ok(());
    }

    let report = sefy_core::sync(vault, &plugin, name, opener)?;

    println!("synced {name:?} through {}", plugin.name());
    for message in [
        report.pulled.transport.message.as_deref(),
        report.pushed.message.as_deref(),
    ]
    .into_iter()
    .flatten()
    {
        println!("{message}");
    }
    print_lines(&merge_lines(&report.pulled.merged, NOTHING_CAME_BACK));
    Ok(())
}

/// What a pull or a sync says when the remote held nothing new.
pub(crate) const NOTHING_CAME_BACK: &str = "nothing came back that this vault did not already have";

/// The last line of every dry run.
const NOTHING_DONE: &str = "dry run: nothing was written here or sent anywhere";

/// The master password of the copy on the other side, if it was given.
///
/// A pull brings back a copy of *this* vault, so the same password is the
/// ordinary case and the default. Both ways of saying otherwise are honoured.
fn remote_password(args: &PullArgs) -> Result<Option<Zeroizing<String>>> {
    if let Some(variable) = args.remote_password_env.as_deref() {
        return session::secret("", Some(variable))
            .map(Zeroizing::new)
            .map(Some);
    }
    if args.ask_remote_password {
        return session::secret("Password of the remote copy: ", None)
            .map(Zeroizing::new)
            .map(Some);
    }
    Ok(None)
}

/// What opens the copy on the other side: the password given for it, or what
/// opened this vault.
fn opener_of_remote<'a>(given: Option<&'a Zeroizing<String>>, master: &'a Master) -> Opener<'a> {
    match given {
        Some(password) => Opener::Password(password.as_bytes()),
        None => master.opener(),
    }
}

/// Picks the transport to use.
///
/// Named, or the only one installed. Guessing between several would mean
/// choosing where somebody's vault goes, and a wrong guess there is not a
/// mistake that announces itself.
pub(crate) fn transport(name: Option<&str>) -> Result<sefy_core::Plugin> {
    let installed = sefy_core::plugin::discover();

    if let Some(name) = name {
        let found = sefy_core::plugin::find(installed, name).ok_or_else(|| {
            anyhow::anyhow!(
                "no transport called {name:?}\n\
                     run `sefy plugin list` to see what is installed."
            )
        })?;
        return Ok(found);
    }

    let usable: Vec<sefy_core::Plugin> = installed
        .into_iter()
        .filter(|plugin| plugin.usable)
        .collect();

    match usable.len() {
        0 => bail!(
            "no usable transport installed\n\
             a transport is an executable named {}<name>; `sefy plugin list` \
             says where sefy looks and why anything found is unusable.",
            sefy_core::plugin::PREFIX
        ),
        1 => Ok(usable.into_iter().next().expect("just counted")),
        _ => {
            let names: Vec<&str> = usable.iter().map(sefy_core::Plugin::name).collect();
            bail!(
                "several transports are installed: {}\n\
                 say which one with --transport <NAME>.",
                names.join(", ")
            )
        }
    }
}

/// What a merge did, as lines to print.
///
/// Shared by `merge`, `pull`, `sync` and syncing after a write: the outcome is
/// the same thing in all of them, and a conflict has to read the same way
/// whichever brought it in. Only the line for "the two already agree" differs,
/// since what the user did differs.
///
/// Counts rather than names: a merge after every write would otherwise fill
/// the screen with titles nobody asked about. Naming each item is what
/// `--dry-run` is for. Conflicts are the exception and are always named —
/// they are the one outcome somebody has to look at.
pub(crate) fn merge_lines(report: &sefy_core::MergeReport, nothing_to_do: &str) -> Vec<String> {
    if report.is_empty() {
        return vec![nothing_to_do.to_owned()];
    }

    let mut lines = Vec::new();
    let brought = if report.versions > 0 {
        format!(
            "; {} brought across",
            output::count(report.versions, "earlier version")
        )
    } else {
        String::new()
    };
    lines.push(format!(
        "merged: {} added, {} updated, {} unchanged{brought}",
        report.added.len(),
        report.updated.len(),
        report.unchanged
    ));

    if report.unsupported > 0 {
        lines.push(format!(
            "{} left where it was: a kind this version of sefy does not know.\n\
             Nothing was lost — merge again from a build that knows it.",
            output::count(report.unsupported, "item")
        ));
    }

    if !report.conflicts.is_empty() {
        // Loud on purpose: a conflict means two versions of one secret, and
        // only the person who made them can say which is right. The one that
        // was not chosen is not gone, and this is where they learn where it is.
        lines.push(format!(
            "\n{} changed on both sides.",
            output::count(report.conflicts.len(), "item")
        ));
        lines.push(
            "The copy changed more recently is current; the other is kept in the item's history:"
                .to_owned(),
        );
        for conflict in &report.conflicts {
            let whose = match conflict.current {
                sefy_core::Side::Here => "this vault's is current",
                sefy_core::Side::There => "the other copy's is current",
            };
            lines.push(format!(
                "  {:?} ({whose}): sefy history {}",
                conflict.title, conflict.id
            ));
        }
        lines.push(
            "Compare with sefy history ID VERSION; bring one back with sefy restore ID VERSION."
                .to_owned(),
        );
    }

    if let Some(kept) = &report.kept_copy {
        lines.push(kept_line(kept));
    }
    lines
}

/// What a merge would do, item by item, as indented lines.
///
/// A preview names everything: deciding whether to go ahead is exactly when
/// "3 added" is not enough, and "which three" is the question.
///
/// `here` says whether the report is about this vault. Ids are shown only
/// then: an id in the remote copy names nothing on this machine.
pub(crate) fn preview_lines(report: &sefy_core::MergeReport, here: bool) -> Vec<String> {
    let id = |id: i64| {
        if here {
            format!(" ({id})")
        } else {
            String::new()
        }
    };
    if report.is_empty() {
        return vec!["  nothing would change".to_owned()];
    }

    let mut lines = Vec::new();
    for item in &report.added {
        lines.push(format!("  add       {:?}", item.title));
    }
    for item in &report.updated {
        lines.push(format!("  update    {:?}{}", item.title, id(item.id)));
    }
    for conflict in &report.conflicts {
        let outcome = match conflict.current {
            sefy_core::Side::Here => "keeps its contents; the other side's go to its history",
            sefy_core::Side::There => "takes the other side's contents; its own go to its history",
        };
        lines.push(format!(
            "  conflict  {:?}{} {outcome}",
            conflict.title,
            id(conflict.id)
        ));
    }

    let mut also = Vec::new();
    if report.versions > 0 {
        also.push(format!(
            "{} brought across",
            output::count(report.versions, "earlier version")
        ));
    }
    if report.unsupported > 0 {
        also.push(format!(
            "{} of a kind this sefy does not know left where it is",
            output::count(report.unsupported, "item")
        ));
    }
    also.push(format!("{} unchanged", report.unchanged));
    lines.push(format!("  {}", also.join("; ")));
    lines
}

/// The line naming where a vault was kept before a change.
fn kept_line(kept: &Path) -> String {
    format!("the vault as it was is kept as {}", kept.display())
}

fn print_lines(lines: &[String]) {
    for line in lines {
        println!("{line}");
    }
}

/// Lists the transports installed on this machine.
///
/// Everything found is shown, usable or not. A plugin that is present but
/// broken looks exactly like one that was never installed if it is left out —
/// and the two call for opposite fixes.
pub fn plugin_list(show_paths: bool) -> Result<()> {
    let paths = sefy_core::plugin::search_paths();
    let plugins = sefy_core::plugin::discover_in(&paths);

    if show_paths {
        println!("looked in:");
        for path in &paths {
            println!("  {}", path.display());
        }
        println!();
    }

    if plugins.is_empty() {
        println!("no plugins installed");
        println!(
            "a plugin is an executable named {}<name>, on PATH or in {}",
            sefy_core::plugin::PREFIX,
            match sefy_core::plugin::plugin_directory() {
                Some(directory) => directory.display().to_string(),
                None => "sefy's data directory".to_owned(),
            }
        );
        return Ok(());
    }

    let name_width = plugins
        .iter()
        .map(|plugin| plugin.name().chars().count())
        .max()
        .unwrap_or(4);

    for plugin in &plugins {
        let version = plugin
            .manifest
            .as_ref()
            .map_or("?", |manifest| manifest.version.as_str());

        let state = if plugin.usable {
            let mut operations: Vec<&str> = plugin
                .manifest
                .iter()
                .flat_map(|manifest| &manifest.operations)
                .map(|operation| operation.as_str())
                .collect();
            operations.sort_unstable();
            operations.join(", ")
        } else {
            format!(
                "unusable: {}",
                plugin.reason.as_deref().unwrap_or("no reason given")
            )
        };

        println!(
            "{:<name_width$}  {:<8}  {}",
            plugin.name(),
            version,
            state,
            name_width = name_width
        );
    }

    Ok(())
}

/// Reads everything from stdin as text.
fn read_stdin() -> Result<String> {
    let mut text = String::new();
    std::io::stdin().read_to_string(&mut text)?;
    Ok(text.trim_end_matches(['\n', '\r']).to_owned())
}

/// Asks a yes/no question on the terminal.
fn confirm(question: &str) -> Result<bool> {
    use std::io::{IsTerminal, Write};

    if !std::io::stdin().is_terminal() {
        bail!("cannot ask for confirmation: input is not a terminal; pass --yes");
    }

    print!("{question}");
    std::io::stdout().flush()?;

    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(matches!(
        answer.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}