defter 0.7.0

Self-hosted Zotero sync and file storage server, with metadata in SQLite and attachments in S3.
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
//! defter: a self-hosted Zotero sync and file storage server.
//!
//! Library metadata lives in SQLite, attachment files in S3-compatible object
//! storage. Stock Zotero clients sync against it, and commonmeta sync can
//! enrich the library through the same API.

use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use clap::{Args, Parser, Subcommand};

#[cfg(test)]
mod api_tests;
mod app;
mod auth;
mod backup;
mod control;
mod countries;
mod db;
mod error;
mod i18n;
mod migrate;
mod oidc;
mod profile;
mod query;
mod registry;
mod serve;
mod storage;
mod store;
mod sync;
mod ui;
mod vocab;
mod zotero;
mod zotero_org;

#[derive(Parser)]
#[command(
    name = "defter",
    version,
    about = "Self-hosted Zotero sync and file storage server"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Start the server (runs in the foreground).
    Start(Box<StartArgs>),
    /// Print the read/write API key the login session hands out, generating
    /// one in the data directory when none is configured.
    Key(KeyCommandArgs),
    /// Back up the databases to object storage now, or list backups. Safe
    /// while the server runs.
    Backup(Box<BackupCommandArgs>),
    /// Restore a library's database, or the control database, from a backup.
    /// The server must be stopped.
    Restore(Box<RestoreCommandArgs>),
    /// Move the library database of an earlier defter (0.5.0 and before) to the
    /// layout of this one: backs up, then creates the control database and
    /// moves the library to libraries/, unchanged. The server must be stopped.
    Migrate(Box<MigrateCommandArgs>),
    /// Run the commonmeta sync of everyone who opted in on their dashboard,
    /// beside the running server, and exit: 0 when every library ran, 1 when
    /// it could not start, 2 when a library's run failed. commonmeta's crontab
    /// runs it (`commonmeta jobs`).
    Sync(Box<SyncCommandArgs>),
}

#[derive(Args)]
struct DataArgs {
    /// Directory for the database, the generated API key and (without S3)
    /// attachment files. Defaults to $STATE_DIRECTORY under systemd; as root,
    /// /var/lib/defter (macOS: /Library/Application Support/defter);
    /// otherwise ~/.local/share/defter or $XDG_DATA_HOME/defter (macOS:
    /// ~/Library/Application Support/defter).
    #[arg(long, env = "DEFTER_DATA_DIR")]
    data_dir: Option<PathBuf>,
}

#[derive(Args)]
struct KeyArgs {
    /// API keys as a comma-separated list of `rw:<file>` / `ro:<file>`
    /// entries, each file holding one token. Read-only keys can read
    /// everything but change nothing.
    #[arg(long, env = "DEFTER_KEYS")]
    keys: Option<String>,

    /// A file holding a single read/write API key.
    #[arg(long, env = "DEFTER_API_KEY_FILE")]
    api_key_file: Option<PathBuf>,

    /// A single read/write API key, e.g. from an environment file only root
    /// and the defter group can read. Approves Zotero logins on the login
    /// page. Generate it with `openssl rand -hex 32`.
    #[arg(long, env = "DEFTER_API_KEY", hide_env_values = true)]
    api_key: Option<String>,
}

#[derive(Args)]
struct KeyCommandArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    keys: KeyArgs,
}

/// Where attachment files are, which backups also use.
#[derive(Args)]
struct StorageArgs {
    /// S3 bucket for attachment files. Without it files are kept in
    /// --files-dir, which is meant for development.
    #[arg(long, env = "DEFTER_S3_BUCKET")]
    s3_bucket: Option<String>,

    /// S3 endpoint, e.g. https://fsn1.your-objectstorage.com (Hetzner),
    /// https://<account>.r2.cloudflarestorage.com (Cloudflare R2) or
    /// http://127.0.0.1:9000 (RustFS); defaults to AWS. Clients download from
    /// pre-signed URLs on it, so they must be able to reach it.
    #[arg(long, env = "DEFTER_S3_ENDPOINT")]
    s3_endpoint: Option<String>,

    /// S3 region: the location for Hetzner (fsn1, nbg1, hel1), `auto` for R2.
    /// Falls back to AWS_REGION.
    #[arg(long, env = "DEFTER_S3_REGION")]
    s3_region: Option<String>,

    /// S3 access key ID. Falls back to AWS_ACCESS_KEY_ID.
    #[arg(long, env = "DEFTER_S3_ACCESS_KEY_ID")]
    s3_access_key_id: Option<String>,

    /// File holding the S3 access key ID.
    #[arg(long, env = "DEFTER_S3_ACCESS_KEY_ID_FILE")]
    s3_access_key_id_file: Option<PathBuf>,

    /// S3 secret access key (prefer the _FILE variant). Falls back to
    /// AWS_SECRET_ACCESS_KEY.
    #[arg(long, env = "DEFTER_S3_SECRET_ACCESS_KEY", hide_env_values = true)]
    s3_secret_access_key: Option<String>,

    /// File holding the S3 secret access key.
    #[arg(long, env = "DEFTER_S3_SECRET_ACCESS_KEY_FILE")]
    s3_secret_access_key_file: Option<PathBuf>,

    /// Address the bucket as <bucket>.<endpoint> instead of <endpoint>/<bucket>.
    /// Always on for Hetzner Object Storage.
    #[arg(long, env = "DEFTER_S3_VIRTUAL_HOSTED_STYLE")]
    s3_virtual_hosted_style: bool,

    /// Key prefix for every object, so a bucket can be shared.
    #[arg(long, env = "DEFTER_S3_PREFIX", default_value = "")]
    s3_prefix: String,

    /// Seconds a pre-signed download URL stays valid.
    #[arg(long, env = "DEFTER_PRESIGN_TTL", default_value_t = 300)]
    presign_ttl: u64,

    /// Stream downloads through the server instead of redirecting clients
    /// to the bucket (for a bucket clients cannot reach).
    #[arg(long, env = "DEFTER_PROXY_DOWNLOADS")]
    proxy_downloads: bool,

    /// Directory for attachment files when no S3 bucket is configured.
    /// Defaults to <data-dir>/files.
    #[arg(long, env = "DEFTER_FILES_DIR")]
    files_dir: Option<PathBuf>,
}

/// The owner's library.
#[derive(Args)]
struct LibraryArgs {
    /// The library database of an earlier defter, which `defter migrate`
    /// moves. Defaults to <data-dir>/defter.sqlite3. Since 0.5.1, the databases
    /// are <data-dir>/control.sqlite3 and <data-dir>/libraries/.
    #[arg(long, env = "DEFTER_DB")]
    db: Option<PathBuf>,

    /// The owner's user ID, which must be their zotero.org user ID: every API
    /// key configured here is theirs. Required, as no default could be theirs.
    #[arg(
        long,
        env = "DEFTER_USER_ID",
        value_parser = clap::value_parser!(u64).range(1..=i64::MAX as u64)
    )]
    user_id: u64,
}

#[derive(Args)]
struct BackupArgs {
    /// Hours between backups of the library database to object storage, under
    /// backup/. 0 turns scheduled backups off.
    #[arg(long, env = "DEFTER_BACKUP_INTERVAL_HOURS", default_value_t = 6)]
    backup_interval_hours: u64,

    /// Days backups are kept. Deleted attachment files are kept as long, so a
    /// restored library finds them.
    #[arg(long, env = "DEFTER_BACKUP_KEEP_DAYS", default_value_t = 30)]
    backup_keep_days: u64,

    /// A separate S3 bucket for backups, with the same endpoint and
    /// credentials, so losing the files bucket does not lose them too.
    /// Defaults to the files bucket.
    #[arg(long, env = "DEFTER_BACKUP_S3_BUCKET")]
    backup_s3_bucket: Option<String>,
}

#[derive(Args)]
struct BackupCommandArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    library: LibraryArgs,
    #[command(flatten)]
    storage: StorageArgs,
    #[command(flatten)]
    backup: BackupArgs,

    /// List the backups instead of making one.
    #[arg(long)]
    list: bool,
}

#[derive(Args)]
struct RestoreCommandArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    library: LibraryArgs,
    #[command(flatten)]
    storage: StorageArgs,
    #[command(flatten)]
    backup: BackupArgs,

    /// The backup to restore, by its time as `defter backup --list` shows it.
    /// Defaults to the newest.
    #[arg(long)]
    manifest: Option<String>,

    /// The library to restore, by its name in backups: u<user id>, or
    /// g<group id> for a group's. Defaults to the owner's.
    #[arg(long = "library", conflicts_with = "control")]
    restore_library: Option<String>,

    /// Restore the control database (users and what is known about each
    /// library) instead of a library.
    #[arg(long)]
    control: bool,

    /// Restore. Without it, only show what would be done.
    #[arg(long)]
    yes: bool,

    /// The highest library version Zotero clients may have seen, needed only
    /// when the live database cannot be read. Versions are set above it.
    #[arg(long)]
    min_version: Option<i64>,
}

#[derive(Args)]
struct MigrateCommandArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    library: LibraryArgs,
    #[command(flatten)]
    storage: StorageArgs,
    #[command(flatten)]
    backup: BackupArgs,

    /// The owner's user name.
    #[arg(long, env = "DEFTER_USERNAME", default_value = "defter")]
    username: String,

    /// The owner's ORCID iD, if --orcid is set for the server.
    #[arg(long, env = "DEFTER_ORCID")]
    orcid: Option<String>,

    /// Only show what would be done.
    #[arg(long)]
    dry_run: bool,

    /// Do not back up first (when a backup was just taken).
    #[arg(long)]
    no_backup: bool,
}

#[derive(Args)]
struct StartArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    keys: KeyArgs,
    #[command(flatten)]
    library: LibraryArgs,
    #[command(flatten)]
    storage: StorageArgs,
    #[command(flatten)]
    backup: BackupArgs,
    #[command(flatten)]
    app: AppArgs,

    /// Address to listen on. Keep the default behind a reverse proxy.
    #[arg(long, env = "DEFTER_HOST", default_value = "127.0.0.1")]
    host: String,

    /// TCP port to listen on.
    #[arg(short, long, env = "DEFTER_PORT", default_value_t = 8189)]
    port: u16,

    /// PEM certificate (chain) to serve HTTPS with, e.g. a Cloudflare origin
    /// certificate when a TLS pass-through such as dragoman's --sni-route
    /// forwards connections. Requires --tls-key. Without it, plain HTTP.
    #[arg(long, env = "DEFTER_TLS_CERT", requires = "tls_key")]
    tls_cert: Option<PathBuf>,

    /// PEM private key for --tls-cert.
    #[arg(long, env = "DEFTER_TLS_KEY", requires = "tls_cert")]
    tls_key: Option<PathBuf>,

    /// Public hostname to get an HTTPS certificate for from Let's Encrypt, when
    /// no CDN is in front. Connections for it on port 443 must reach this
    /// server, such as through dragoman's --sni-route. Requires --email.
    #[arg(
        long,
        env = "DEFTER_DOMAIN",
        requires = "email",
        conflicts_with = "tls_cert"
    )]
    domain: Option<String>,

    /// Contact email for the Let's Encrypt account, with --domain.
    #[arg(long, env = "DEFTER_EMAIL")]
    email: Option<String>,

    /// Directory keeping the Let's Encrypt account and certificates between
    /// restarts. Defaults to <data-dir>/acme.
    #[arg(long, env = "DEFTER_ACME_CACHE")]
    acme_cache: Option<PathBuf>,

    /// Use Let's Encrypt's staging environment, whose certificates browsers do
    /// not trust: for trying the setup out without its rate limits.
    #[arg(long, env = "DEFTER_ACME_STAGING")]
    acme_staging: bool,

    /// URL clients reach the server at (the reverse proxy's or CDN's), used in
    /// login, upload and download links. Defaults to https://<domain> with
    /// --domain, otherwise http(s)://<host>:<port>.
    #[arg(long, env = "DEFTER_PUBLIC_URL")]
    public_url: Option<String>,

    /// Require the SSO proxy in front of /login to forward this identity
    /// (X-Forwarded-Email/-User or X-Auth-Request-Email/-User) to approve a
    /// login. Leave unset on a private network.
    #[arg(long, env = "DEFTER_LOGIN_AUTHORIZED_USER")]
    login_authorized_user: Option<String>,

    /// Your ORCID iD (or ORCID URL): publishes a profile at /<orcid> with
    /// your ORCID record and every work in My Publications. It can be hidden
    /// on the dashboard.
    #[arg(long, env = "DEFTER_ORCID")]
    orcid: Option<String>,

    /// Issuer URL of an OpenID Connect provider to also sign in through, such
    /// as https://auth.example.org/realms/<realm>. Requires --oidc-client-id.
    /// API keys keep working.
    #[arg(long, env = "DEFTER_OIDC_ISSUER")]
    oidc_issuer: Option<String>,

    /// The client this server is at the provider. Its redirect URI is
    /// <public-url>/ui/oidc/callback.
    #[arg(long, env = "DEFTER_OIDC_CLIENT_ID")]
    oidc_client_id: Option<String>,

    /// The client's secret. Prefer --oidc-client-secret-file: the environment
    /// is visible in /proc. Leave out for a public client.
    #[arg(long, env = "DEFTER_OIDC_CLIENT_SECRET", hide_env_values = true)]
    oidc_client_secret: Option<String>,

    /// File holding the client's secret.
    #[arg(long, env = "DEFTER_OIDC_CLIENT_SECRET_FILE")]
    oidc_client_secret_file: Option<String>,

    /// The ORCID iDs of the admins, comma-separated: they sign in without an
    /// invitation, invite people and manage users. Without any, the owner is
    /// the admin.
    #[arg(long, env = "DEFTER_ADMIN_ORCIDS")]
    admin_orcids: Option<String>,

    /// The claim holding an account's ORCID iD, in the ID token or userinfo.
    #[arg(long, env = "DEFTER_OIDC_ORCID_CLAIM", default_value = "orcid")]
    oidc_orcid_claim: String,

    /// What the sign-in button calls the provider.
    #[arg(long, env = "DEFTER_OIDC_NAME", default_value = "Keycloak")]
    oidc_name: String,

    /// zotero.org's Web API, which tells whose a zotero.org API key is: a new
    /// user's ID is their zotero.org user ID.
    #[arg(
        long,
        env = "DEFTER_ZOTERO_API_URL",
        default_value = zotero_org::DEFAULT_API_URL
    )]
    zotero_api_url: String,

    /// The commonmeta store (commonmeta.sqlite3) on this server: turns on the
    /// commonmeta sync of the libraries whose users opt in on their dashboard,
    /// with its previews and syncs started there; `defter sync` runs it for
    /// everyone. It is only read; defter needs read access to the file and its
    /// directory, as dragoman has.
    #[arg(long, env = "DEFTER_COMMONMETA_DB")]
    commonmeta_db: Option<PathBuf>,

    #[command(flatten)]
    sync: SyncArgs,
}

/// What both the server and `defter sync` open a library with.
#[derive(Args)]
struct AppArgs {
    /// The user name reported to clients.
    #[arg(long, env = "DEFTER_USERNAME", default_value = "defter")]
    username: String,

    /// How many libraries' databases stay open at most, beyond those in use.
    #[arg(long, env = "DEFTER_LIBRARY_CACHE", default_value_t = 150)]
    library_cache: usize,

    /// Largest attachment file accepted, in MiB.
    #[arg(long, env = "DEFTER_MAX_UPLOAD_MB", default_value_t = 1024)]
    max_upload_mb: u64,

    /// Each user's storage quota for attachment files, in MiB, unless an admin
    /// sets theirs. The owner has none unless set.
    #[arg(long, env = "DEFTER_DEFAULT_QUOTA_MB", default_value_t = 2048)]
    default_quota_mb: u64,

    /// Where to get Zotero's item schema for GET /schema.
    #[arg(
        long,
        env = "DEFTER_SCHEMA_URL",
        default_value = "https://api.zotero.org/schema"
    )]
    schema_url: String,
}

/// The limits of a commonmeta sync run.
#[derive(Args)]
struct SyncArgs {
    /// At most this many PDFs attached per library and run, for users who
    /// chose to attach PDFs.
    #[arg(long, env = "DEFTER_SYNC_MAX_PDFS", default_value_t = 1000)]
    sync_max_pdfs: usize,

    /// At most this many items changed or created per library and run (0 for
    /// no limit); the rest are left for the following runs.
    #[arg(long, env = "DEFTER_SYNC_LIMIT", default_value_t = 1000)]
    sync_limit: usize,
}

#[derive(Args)]
struct SyncCommandArgs {
    #[command(flatten)]
    data: DataArgs,
    #[command(flatten)]
    library: LibraryArgs,
    #[command(flatten)]
    storage: StorageArgs,
    #[command(flatten)]
    app: AppArgs,

    /// The commonmeta store (commonmeta.sqlite3) on this server. It is only
    /// read.
    #[arg(long, env = "DEFTER_COMMONMETA_DB")]
    commonmeta_db: PathBuf,

    #[command(flatten)]
    sync: SyncArgs,

    /// Only this user's library, as when rolling the sync out: they must have
    /// turned it on, unless with --dry-run.
    #[arg(long = "user")]
    only_user: Option<u64>,

    /// Preview: write nothing, and record each run as a preview the user sees
    /// on their dashboard, with what it would change.
    #[arg(long)]
    dry_run: bool,
}

/// The data directory of a system-wide installation (run as root).
#[cfg(target_os = "macos")]
const SYSTEM_DATA_DIR: &str = "/Library/Application Support/defter";
#[cfg(not(target_os = "macos"))]
const SYSTEM_DATA_DIR: &str = "/var/lib/defter";

/// What the default data directory depends on, read from the process.
struct DataDirEnv {
    /// systemd's `$STATE_DIRECTORY`, set by `StateDirectory=defter`.
    state_directory: Option<String>,
    root: bool,
    home: Option<String>,
    #[cfg_attr(target_os = "macos", allow(dead_code))]
    xdg_data_home: Option<String>,
}

impl DataDirEnv {
    fn current() -> Self {
        let var = |name| std::env::var(name).ok().filter(|v: &String| !v.is_empty());
        DataDirEnv {
            state_directory: var("STATE_DIRECTORY"),
            #[cfg(unix)]
            // SAFETY: geteuid has no preconditions and cannot fail.
            root: unsafe { libc::geteuid() } == 0,
            #[cfg(not(unix))]
            root: false,
            home: var("HOME"),
            xdg_data_home: var("XDG_DATA_HOME"),
        }
    }
}

/// The data directory when none is given:
///
/// 1. `$STATE_DIRECTORY`, under a systemd unit with `StateDirectory=defter`
///    (`/var/lib/defter`); its first entry when it lists several;
/// 2. as root, the system directory: `/var/lib/defter` on Linux,
///    `/Library/Application Support/defter` on macOS;
/// 3. otherwise the user's: `~/Library/Application Support/defter` on macOS,
///    `$XDG_DATA_HOME/defter` or `~/.local/share/defter` elsewhere.
fn default_data_dir(env: &DataDirEnv) -> PathBuf {
    if let Some(dir) = env
        .state_directory
        .as_deref()
        .and_then(|dirs| dirs.split(':').next())
        .filter(|dir| !dir.is_empty())
    {
        return PathBuf::from(dir);
    }
    if env.root {
        return PathBuf::from(SYSTEM_DATA_DIR);
    }
    let home = || env.home.as_deref().map(PathBuf::from);
    #[cfg(target_os = "macos")]
    let user = home().map(|h| h.join("Library/Application Support"));
    #[cfg(not(target_os = "macos"))]
    let user = env
        .xdg_data_home
        .as_deref()
        .map(PathBuf::from)
        // The XDG spec ignores a relative XDG_DATA_HOME.
        .filter(|p| p.is_absolute())
        .or_else(|| home().map(|h| h.join(".local/share")));
    user.map(|dir| dir.join("defter"))
        .unwrap_or_else(|| PathBuf::from(SYSTEM_DATA_DIR))
}

impl DataArgs {
    fn dir(&self) -> PathBuf {
        self.data_dir
            .clone()
            .unwrap_or_else(|| default_data_dir(&DataDirEnv::current()))
    }
}

impl KeyArgs {
    fn source(&self, data_dir: &std::path::Path) -> auth::KeySource {
        auth::KeySource {
            manifest: self.keys.clone(),
            file: self.api_key_file.clone(),
            key: self.api_key.clone(),
            generated: data_dir.join("api-key"),
        }
    }
}

fn fail(message: impl std::fmt::Display) -> ! {
    eprintln!("defter: {message}");
    std::process::exit(1);
}

/// A secret from a file (preferred) or a value.
fn secret(file: &Option<PathBuf>, value: &Option<String>) -> Option<String> {
    match file {
        Some(path) => Some(
            std::fs::read_to_string(path)
                .unwrap_or_else(|e| fail(format!("read {}: {e}", path.display())))
                .trim()
                .to_string(),
        ),
        None => value.clone(),
    }
}

impl StorageArgs {
    fn backend(&self, data_dir: &std::path::Path) -> storage::Backend {
        match &self.s3_bucket {
            Some(bucket) => storage::Backend::S3(storage::S3Config {
                bucket: bucket.clone(),
                endpoint: self.s3_endpoint.clone(),
                region: self.s3_region.clone(),
                access_key_id: secret(&self.s3_access_key_id_file, &self.s3_access_key_id),
                secret_access_key: secret(
                    &self.s3_secret_access_key_file,
                    &self.s3_secret_access_key,
                ),
                virtual_hosted_style: self.s3_virtual_hosted_style,
                prefix: self.s3_prefix.clone(),
            }),
            None => storage::Backend::Local(
                self.files_dir
                    .clone()
                    .unwrap_or_else(|| data_dir.join("files")),
            ),
        }
    }

    fn storage(&self, data_dir: &std::path::Path) -> storage::Storage {
        storage::Storage::new(
            &self.backend(data_dir),
            Duration::from_secs(self.presign_ttl),
            self.proxy_downloads,
        )
        .unwrap_or_else(|e| fail(format!("object storage: {e}")))
    }

    /// Where backups go: the files bucket, or `bucket` with its settings.
    fn backup_storage(&self, data_dir: &std::path::Path, bucket: Option<&str>) -> storage::Storage {
        let backend = match (
            self.backend(data_dir),
            bucket.filter(|b| !b.trim().is_empty()),
        ) {
            (storage::Backend::S3(mut cfg), Some(bucket)) => {
                cfg.bucket = bucket.to_string();
                storage::Backend::S3(cfg)
            }
            (_, Some(_)) => fail(
                "DEFTER_BACKUP_S3_BUCKET needs DEFTER_S3_BUCKET, whose settings it shares"
                    .to_string(),
            ),
            (backend, None) => backend,
        };
        storage::Storage::new(&backend, Duration::from_secs(self.presign_ttl), true)
            .unwrap_or_else(|e| fail(format!("backup storage: {e}")))
    }
}

impl LibraryArgs {
    fn path(&self, data_dir: &std::path::Path) -> PathBuf {
        self.db
            .clone()
            .unwrap_or_else(|| data_dir.join("defter.sqlite3"))
    }

    fn layout(&self, data_dir: &std::path::Path) -> migrate::Layout {
        migrate::Layout::new(data_dir, self.path(data_dir))
    }
}

/// The databases in `layout`: the control database and every library it
/// lists, or the one library of an earlier defter.
fn sources(layout: &migrate::Layout, user_id: u64) -> Result<Vec<backup::Source>, String> {
    match migrate::state(layout, user_id) {
        migrate::State::New => Ok(Vec::new()),
        migrate::State::Legacy => Ok(vec![backup::Source {
            name: control::LibraryRef::User(user_id).to_string(),
            path: layout.legacy.clone(),
            files: Some(storage::FileScope::Legacy),
        }]),
        _ => {
            let conn = rusqlite::Connection::open_with_flags(
                &layout.control,
                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
            )
            .map_err(|e| format!("opening {}: {e}", layout.control.display()))?;
            conn.busy_timeout(Duration::from_secs(30))
                .map_err(|e| e.to_string())?;
            let libraries = control::libraries(&conn)
                .map_err(|e| format!("reading {}: {e}", layout.control.display()))?;
            let mut sources = vec![backup::Source {
                name: "control".to_string(),
                path: layout.control.clone(),
                files: None,
            }];
            sources.extend(
                libraries
                    .into_iter()
                    .map(|(library, files)| backup::Source {
                        name: library.to_string(),
                        path: layout.library(library),
                        files: Some(files),
                    }),
            );
            Ok(sources)
        }
    }
}

/// Backups of the databases in the data directory, with attachment files in
/// `files`.
fn backups(
    data_dir: &std::path::Path,
    library: &LibraryArgs,
    storage_args: &StorageArgs,
    backup_args: &BackupArgs,
    files: std::sync::Arc<storage::Storage>,
) -> backup::Backup {
    let layout = library.layout(data_dir);
    let user_id = library.user_id;
    backup::Backup::new(
        std::sync::Arc::new(
            storage_args.backup_storage(data_dir, backup_args.backup_s3_bucket.as_deref()),
        ),
        files,
        std::sync::Arc::new(move || sources(&layout, user_id)),
        data_dir.join("tmp"),
        backup_args.backup_keep_days,
    )
}

async fn backup_command(args: BackupCommandArgs) {
    let data_dir = args.data.dir();
    let files = std::sync::Arc::new(args.storage.storage(&data_dir));
    let backup = backups(&data_dir, &args.library, &args.storage, &args.backup, files);
    if args.list {
        let manifests = backup::list(&backup.store)
            .await
            .unwrap_or_else(|e| fail(e));
        if manifests.is_empty() {
            println!("no backups in {}", backup.store.description());
        }
        for manifest in manifests {
            let libraries = manifest
                .entries
                .iter()
                .map(|e| format!("{} v{} ({} bytes)", e.name, e.version, e.bytes))
                .collect::<Vec<_>>()
                .join(", ");
            println!(
                "{}  defter {}  {libraries}",
                manifest.created, manifest.defter
            );
        }
        return;
    }
    let report = backup.run().await;
    match report.error {
        Some(error) => fail(error),
        None => match report.manifest {
            Some(manifest) => println!(
                "backed up to {manifest}: {} snapshot(s), {} bytes",
                report.snapshots, report.bytes
            ),
            None => println!("nothing changed since the last backup"),
        },
    }
}

/// The commonmeta sync's lock, held so that `defter sync` does not run while
/// the databases are replaced; refused while it runs.
fn sync_lock(data_dir: &Path) -> std::fs::File {
    sync::try_lock(&sync::lock_path(data_dir))
        .unwrap_or_else(|e| fail(e))
        .unwrap_or_else(|| fail("`defter sync` is running: wait for it to finish"))
}

async fn restore_command(args: RestoreCommandArgs) {
    let data_dir = args.data.dir();
    let _lock = backup::lock(&data_dir).unwrap_or_else(|e| fail(e));
    let _sync = sync_lock(&data_dir);
    let files = std::sync::Arc::new(args.storage.storage(&data_dir));
    let backup = backups(&data_dir, &args.library, &args.storage, &args.backup, files);
    let layout = args.library.layout(&data_dir);
    let name = if args.control {
        "control".to_string()
    } else {
        args.restore_library
            .clone()
            .unwrap_or_else(|| control::LibraryRef::User(args.library.user_id).to_string())
    };
    let source = if args.control {
        backup::Source {
            name: name.clone(),
            path: layout.control.clone(),
            files: None,
        }
    } else {
        if matches!(
            migrate::state(&layout, args.library.user_id),
            migrate::State::New | migrate::State::ControlMissing
        ) {
            fail(
                "restore the control database first (`defter restore --control`): it knows \
                 where each library's attachment files are",
            );
        }
        backup
            .sources()
            .unwrap_or_else(|e| fail(e))
            .into_iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| fail(format!("the control database has no library {name}")))
    };
    // The highest version the server recorded serving, which clients may hold.
    let served = match source.files {
        Some(_) if layout.control.exists() => control::LibraryRef::parse(&name)
            .and_then(|library| {
                let conn = rusqlite::Connection::open_with_flags(
                    &layout.control,
                    rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
                )
                .ok()?;
                control::version_high(&conn, library).ok()
            })
            .filter(|v| *v > 0),
        _ => None,
    };
    let restored = backup::restore(
        &backup.store,
        &backup.files,
        &source,
        args.manifest.as_deref(),
        &data_dir.join("tmp"),
        args.yes,
        args.min_version,
        served,
    )
    .await
    .unwrap_or_else(|e| fail(e));
    let doing = if args.yes {
        "restored"
    } else {
        "would restore"
    };
    if source.files.is_none() {
        println!(
            "{doing} {} from {}",
            source.path.display(),
            restored.manifest
        );
    } else {
        println!(
            "{doing} {} from {} (library version {}), with every version set to {}",
            source.path.display(),
            restored.manifest,
            restored.snapshot_version,
            restored.version
        );
    }
    if let Some(previous) = &restored.previous {
        println!("the replaced database is kept as {}", previous.display());
    }
    if args.yes && source.files.is_none() {
        println!("users, keys and groups are back as they were then");
    } else if args.yes {
        println!(
            "attachment files brought back: {}, still missing: {}",
            restored.files_restored, restored.files_missing
        );
        println!(
            "Zotero clients now see a newer library. Follow \"Backups and restore\" in the \
             README to bring them in line."
        );
    } else {
        println!("run again with --yes to restore");
    }
}

async fn migrate_command(args: MigrateCommandArgs) {
    let data_dir = args.data.dir();
    let _lock = backup::lock(&data_dir).unwrap_or_else(|e| fail(e));
    let _sync = sync_lock(&data_dir);
    let layout = args.library.layout(&data_dir);
    let orcid = |s: &str| {
        profile::normalize_orcid(s).unwrap_or_else(|| fail(format!("{s:?} is not an ORCID iD")))
    };
    let owner = migrate::Owner {
        user_id: args.library.user_id,
        username: args.username.clone(),
        orcid: args
            .orcid
            .as_deref()
            .filter(|s| !s.trim().is_empty())
            .map(orcid),
    };
    let plan = migrate::plan(&layout, &owner).unwrap_or_else(|e| fail(e));
    println!(
        "{} {} (library version {}) to {}",
        if args.dry_run { "would move" } else { "moving" },
        layout.legacy.display(),
        plan.version,
        layout
            .library(control::LibraryRef::User(owner.user_id))
            .display()
    );
    if plan.state == migrate::State::Legacy {
        println!(
            "and create {}: user {} ({}), profile {}{}, attachment files staying under files/",
            layout.control.display(),
            owner.user_id,
            owner.username,
            plan.orcid.as_deref().unwrap_or("none"),
            if plan.profile_hidden { ", hidden" } else { "" },
        );
    }
    if args.dry_run {
        println!("run again without --dry-run to migrate");
        return;
    }
    if plan.state == migrate::State::Legacy && !args.no_backup {
        let files = std::sync::Arc::new(args.storage.storage(&data_dir));
        let backup = backups(&data_dir, &args.library, &args.storage, &args.backup, files);
        let report = backup.run().await;
        if let Some(error) = report.error {
            fail(format!(
                "backing up first failed, so nothing was changed: {error}"
            ));
        }
        match report.manifest {
            Some(manifest) => println!("backed up to {manifest}"),
            None => println!("the last backup is current"),
        }
    }
    migrate::apply(&layout, &owner, &plan).unwrap_or_else(|e| fail(e));
    println!("migrated; start the server again");
}

impl SyncArgs {
    /// The sync over the store at `store`, its runs holding the lock file in
    /// `data_dir`.
    fn config(&self, store: PathBuf, data_dir: &Path) -> Result<sync::SyncConfig, String> {
        if !store.is_file() {
            return Err(format!(
                "--commonmeta-db: no commonmeta store at {}",
                store.display()
            ));
        }
        Ok(sync::SyncConfig {
            store,
            lock: sync::lock_path(data_dir),
            max_pdfs: self.sync_max_pdfs,
            limit: self.sync_limit,
        })
    }
}

/// The control database and the libraries in `data_dir`, as the server and
/// `defter sync` open them. Refused when the data directory needs `defter
/// migrate`, or the owner is not among its users; a new server's first start
/// makes them.
async fn open_libraries(
    data_dir: &Path,
    library: &LibraryArgs,
    app: &AppArgs,
) -> Result<(Arc<control::Control>, registry::Libraries), String> {
    let layout = library.layout(data_dir);
    if let Some(refused) = migrate::refuse_start(&layout, library.user_id) {
        return Err(refused);
    }
    let control = Arc::new(
        control::Control::open(&layout.control)
            .map_err(|e| format!("{}: {e}", layout.control.display()))?,
    );
    control
        .ensure_owner(registry::owner(library.user_id, &app.username, false))
        .await
        .map_err(|e| e.to_string())?;
    let libraries =
        registry::Libraries::new(layout.libraries.clone(), control.clone(), app.library_cache);
    Ok((control, libraries))
}

/// What the server and `defter sync` configure alike; the server adds how it
/// is reached and signed in to.
fn app_config(library: &LibraryArgs, app: &AppArgs, sync: Option<sync::SyncConfig>) -> app::Config {
    app::Config {
        user_id: library.user_id,
        username: app.username.clone(),
        public_url: String::new(),
        login_authorized_user: None,
        max_upload: app.max_upload_mb.saturating_mul(1024 * 1024),
        schema_url: app.schema_url.clone(),
        zotero_api_url: zotero_org::DEFAULT_API_URL.to_string(),
        orcid: None,
        oidc: None,
        key_login: false,
        admin_orcids: Vec::new(),
        default_quota: app.default_quota_mb.saturating_mul(1024 * 1024),
        sync,
    }
}

/// `defter sync`: the exit code, 0 when every library ran, 1 when the sync
/// could not start (as on a command line clap refuses, see
/// [`usage_exit_code`]), 2 when a library's run failed.
async fn sync_command(args: SyncCommandArgs) -> u8 {
    match sync_all(&args).await {
        Ok(ran) if ran.failed == 0 => 0,
        Ok(_) => 2,
        Err(error) => {
            tracing::error!(%error, "commonmeta sync could not start");
            1
        }
    }
}

async fn sync_all(args: &SyncCommandArgs) -> Result<sync::Ran, String> {
    let data_dir = args.data.dir();
    let layout = args.library.layout(&data_dir);
    if !data_dir.is_dir() {
        return Err(format!(
            "no data directory at {}: start the server first",
            data_dir.display()
        ));
    }
    // Before anything in the data directory is opened: `defter restore` and
    // `defter migrate` hold it while they replace the databases.
    let locked = sync::lock(&sync::lock_path(&data_dir)).await?;
    if migrate::state(&layout, args.library.user_id) == migrate::State::New {
        return Err(format!(
            "no control database at {}: start the server first",
            layout.control.display()
        ));
    }
    let cfg = args.sync.config(args.commonmeta_db.clone(), &data_dir)?;
    let (control, libraries) = open_libraries(&data_dir, &args.library, &args.app).await?;
    let storage = args.storage.storage(&data_dir);
    // It serves no requests: a key nobody knows.
    let keys = auth::Keys::new(std::collections::HashMap::from([(
        auth::random_hex(32),
        auth::Access { write: true },
    )]))?;
    let config = app_config(&args.library, &args.app, Some(cfg.clone()));
    let app = app::App::new(config, control, libraries, storage, keys)
        .await
        .map_err(|e| e.to_string())?;
    sync::run_all(&app, &cfg, &locked, args.only_user, args.dry_run)
        .await
        .map_err(|e| e.to_string())
}

/// The exit code of a command line clap refused: 0 for `--help` and
/// `--version`, otherwise 1, "could not start", as for every command. clap's
/// own 2 is `defter sync`'s "a library's run failed".
fn usage_exit_code(error: &clap::Error) -> i32 {
    if error.use_stderr() { 1 } else { 0 }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        // Plain lines for cron's mail and the journal.
        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "defter=info,tower_http=warn".into()),
        )
        .init();
    // object_store and reqwest bring rustls with aws-lc-rs, commonmeta with
    // ring; with both compiled in rustls cannot choose, so choose for it.
    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

    let cli = Cli::try_parse().unwrap_or_else(|e| {
        let _ = e.print(); // nowhere left to report a failed write to stderr
        std::process::exit(usage_exit_code(&e));
    });
    match cli.command {
        Command::Start(args) => start(*args).await,
        Command::Key(args) => {
            let (keys, generated) =
                auth::Keys::load(&args.keys.source(&args.data.dir())).unwrap_or_else(|e| fail(e));
            if let Some(path) = generated {
                eprintln!("defter: generated a key in {}", path.display());
            }
            println!("{}", keys.login_key());
        }
        Command::Backup(args) => backup_command(*args).await,
        Command::Restore(args) => restore_command(*args).await,
        Command::Migrate(args) => migrate_command(*args).await,
        Command::Sync(args) => {
            let code = sync_command(*args).await;
            if code != 0 {
                std::process::exit(code.into());
            }
        }
    }
}

async fn start(args: StartArgs) {
    let data_dir = args.data.dir();
    let (keys, generated) =
        auth::Keys::load(&args.keys.source(&data_dir)).unwrap_or_else(|e| fail(e));
    if let Some(path) = generated {
        tracing::warn!(path = %path.display(), "no API key configured; generated one");
    }
    if keys.short_keys() > 0 {
        tracing::warn!(
            count = keys.short_keys(),
            min = auth::MIN_KEY_LENGTH,
            "API keys shorter than the minimum are easy to guess on the login page; \
             generate keys with `openssl rand -hex 32`"
        );
    }

    // Held while the server runs, so a restore cannot replace the database
    // under it.
    let _lock = backup::lock(&data_dir).unwrap_or_else(|e| fail(e));
    if args.storage.s3_bucket.is_none() {
        tracing::warn!("no S3 bucket configured; keeping attachment files on local disk");
    }
    let storage = args.storage.storage(&data_dir);

    let (control, libraries) = open_libraries(&data_dir, &args.library, &args.app)
        .await
        .unwrap_or_else(|e| fail(e));

    let addr: SocketAddr = format!("{}:{}", args.host, args.port)
        .parse()
        .unwrap_or_else(|e| fail(format!("listen address: {e}")));
    let tls = match (&args.domain, &args.email) {
        (Some(domain), Some(email)) => Some(serve::Tls::Acme {
            domain: domain.clone(),
            email: email.clone(),
            cache: args
                .acme_cache
                .clone()
                .unwrap_or_else(|| data_dir.join("acme")),
            staging: args.acme_staging,
        }),
        _ => args
            .tls_cert
            .clone()
            .zip(args.tls_key.clone())
            .map(|(cert, key)| serve::Tls::Files { cert, key }),
    };
    let scheme = if tls.is_some() { "https" } else { "http" };
    let public_url = args
        .public_url
        .clone()
        .or_else(|| args.domain.as_ref().map(|d| format!("https://{d}")))
        .unwrap_or_else(|| format!("{scheme}://{addr}"))
        .trim_end_matches('/')
        .to_string();
    let sync = args
        .commonmeta_db
        .clone()
        .filter(|path| !path.as_os_str().is_empty())
        .map(|store| {
            args.sync
                .config(store, &data_dir)
                .unwrap_or_else(|e| fail(e))
        });
    let cfg = app::Config {
        public_url: public_url.clone(),
        zotero_api_url: args.zotero_api_url.clone(),
        login_authorized_user: args.login_authorized_user.clone().filter(|s| !s.is_empty()),
        orcid: args
            .orcid
            .as_deref()
            .filter(|s| !s.trim().is_empty())
            .map(|s| {
                profile::normalize_orcid(s)
                    .unwrap_or_else(|| fail(format!("--orcid: {s:?} is not a valid ORCID iD")))
            }),
        oidc: args
            .oidc_issuer
            .as_deref()
            .filter(|issuer| !issuer.trim().is_empty())
            .map(|issuer| {
                oidc::OidcConfig::new(
                    issuer,
                    args.oidc_client_id.as_deref().unwrap_or(""),
                    secret(
                        &args
                            .oidc_client_secret_file
                            .as_deref()
                            .filter(|file| !file.trim().is_empty())
                            .map(PathBuf::from),
                        &args.oidc_client_secret,
                    ),
                    &args.oidc_orcid_claim,
                    &args.oidc_name,
                )
                .unwrap_or_else(|e| fail(e))
            }),
        admin_orcids: args
            .admin_orcids
            .as_deref()
            .unwrap_or("")
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(|s| {
                profile::normalize_orcid(s).unwrap_or_else(|| {
                    fail(format!("--admin-orcids: {s:?} is not a valid ORCID iD"))
                })
            })
            .collect(),
        // With a provider to sign in through, typing a key is opt-in. Without
        // one it is the only way in, so it stays.
        key_login: args
            .oidc_issuer
            .as_deref()
            .is_none_or(|i| i.trim().is_empty())
            || args
                .keys
                .api_key
                .as_deref()
                .is_some_and(|key| !key.trim().is_empty()),
        ..app_config(&args.library, &args.app, sync)
    };
    let app = app::App::new(cfg, control, libraries, storage, keys)
        .await
        .unwrap_or_else(|e| fail(e));
    // Opened now, so a missing or unreadable library stops the start.
    app.libraries
        .get(control::LibraryRef::User(args.library.user_id))
        .await
        .unwrap_or_else(|e| fail(e));

    if args.backup.backup_interval_hours > 0 {
        let backup = std::sync::Arc::new(backups(
            &data_dir,
            &args.library,
            &args.storage,
            &args.backup,
            app.storage.clone(),
        ));
        app.storage.keep_deleted(true);
        let _ = app.backup.set(backup.clone());
        let every = Duration::from_secs(args.backup.backup_interval_hours * 3600);
        tokio::spawn(async move {
            // A minute in, so a deploy is backed up soon, then on schedule.
            let mut ticks = tokio::time::interval_at(
                tokio::time::Instant::now() + Duration::from_secs(60),
                every,
            );
            ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            loop {
                ticks.tick().await;
                backup.run().await;
            }
        });
    } else {
        tracing::warn!("scheduled backups are off (--backup-interval-hours 0)");
    }

    match &app.cfg.sync {
        Some(cfg) => tracing::info!(
            store = %cfg.store.display(),
            "commonmeta sync on: previews and syncs from the dashboard; `defter sync` for everyone"
        ),
        None => tracing::info!("commonmeta sync is off (no --commonmeta-db)"),
    }

    let storage = app.storage.description().to_string();
    let cert = match &tls {
        Some(serve::Tls::Files { cert, .. }) => Some(cert.display().to_string()),
        Some(serve::Tls::Acme { domain, .. }) => Some(format!("Let's Encrypt: {domain}")),
        None => None,
    };
    serve::serve(addr, app::router(app), tls, shutdown(), move |addr| {
        tracing::info!(
            %addr,
            scheme,
            cert,
            public_url,
            data = %data_dir.display(),
            storage,
            "defter listening"
        );
    })
    .await
    .unwrap_or_else(|e| fail(e));
}

async fn shutdown() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
        {
            s.recv().await;
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
    tracing::info!("shutting down");
}

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

    #[test]
    fn oidc_settings_set_to_nothing_mean_off() {
        let start = |args: &[&str]| {
            let all = ["defter", "start", "--user-id", "4711"].iter().chain(args);
            Cli::try_parse_from(all.copied()).map(|_| ())
        };
        // The same goes for the variables, which clap treats like these.
        assert!(start(&["--oidc-issuer", ""]).is_ok());
        assert!(start(&["--oidc-client-secret-file", ""]).is_ok());
    }

    #[test]
    fn lets_encrypt_needs_an_email_and_excludes_certificate_files() {
        let parse = |args: &[&str]| {
            let all = ["defter", "start", "--user-id", "4711"].iter().chain(args);
            Cli::try_parse_from(all.copied()).map(|_| ())
        };
        const DOMAIN: &str = "defter.example.org";
        assert!(parse(&["--domain", DOMAIN, "--email", "me@example.org"]).is_ok());
        assert!(parse(&["--domain", DOMAIN]).is_err());
        assert!(
            parse(&[
                "--domain",
                DOMAIN,
                "--email",
                "me@example.org",
                "--tls-cert",
                "c.pem",
                "--tls-key",
                "k.pem",
            ])
            .is_err()
        );
    }

    #[test]
    fn sync_needs_a_store_and_the_server_no_time() {
        let parse = |args: &[&str]| Cli::try_parse_from(["defter"].iter().chain(args).copied());
        let Ok(Cli {
            command: Command::Sync(sync),
        }) = parse(&[
            "sync",
            "--user-id",
            "4711",
            "--commonmeta-db",
            "cm.sqlite3",
            "--user",
            "7",
        ])
        else {
            panic!("sync parses");
        };
        assert_eq!(sync.only_user, Some(7));
        assert!(!sync.dry_run);
        assert_eq!(
            (sync.sync.sync_limit, sync.sync.sync_max_pdfs),
            (1000, 1000)
        );
        if std::env::var_os("DEFTER_COMMONMETA_DB").is_none() {
            assert!(parse(&["sync"]).is_err());
        }
        assert!(parse(&["start", "--user-id", "4711", "--sync-at", "05:00"]).is_err());
        assert!(parse(&["start", "--user-id", "4711", "--sync-limit", "10"]).is_ok());
    }

    /// No default could be the owner's zotero.org user ID, and zotero.org has
    /// no user 0.
    #[test]
    fn the_owners_user_id_is_required() {
        let parse = |args: &[&str]| Cli::try_parse_from(["defter"].iter().chain(args).copied());
        if std::env::var_os("DEFTER_USER_ID").is_none() {
            for command in ["start", "backup", "restore", "migrate"] {
                let refused = parse(&[command]).err().expect(command);
                assert_eq!(
                    refused.kind(),
                    clap::error::ErrorKind::MissingRequiredArgument,
                    "{command}"
                );
                assert!(refused.to_string().contains("--user-id"), "{command}");
            }
        }
        assert!(parse(&["start", "--user-id", "0"]).is_err());
        assert!(parse(&["start", "--user-id", "9223372036854775808"]).is_err());
        let Ok(Cli {
            command: Command::Start(start),
        }) = parse(&["start", "--user-id", "4711"])
        else {
            panic!("start parses");
        };
        assert_eq!(start.library.user_id, 4711);
    }

    /// A command line clap refuses, such as cron's without the store, is "could
    /// not start", not `defter sync`'s 2; help and the version are no failure.
    #[test]
    fn a_refused_command_line_exits_1() {
        let code = |args: &[&str]| {
            let all = ["defter"].iter().chain(args).copied();
            usage_exit_code(&Cli::try_parse_from(all).err().expect("refused"))
        };
        assert_eq!(code(&["sync", "--user", "seven"]), 1);
        assert_eq!(code(&["synk"]), 1);
        if std::env::var_os("DEFTER_COMMONMETA_DB").is_none() {
            assert_eq!(code(&["sync"]), 1);
        }
        assert_eq!(code(&["sync", "--help"]), 0);
        assert_eq!(code(&["--version"]), 0);
    }

    fn env(state: Option<&str>, root: bool, home: Option<&str>, xdg: Option<&str>) -> DataDirEnv {
        DataDirEnv {
            state_directory: state.map(String::from),
            root,
            home: home.map(String::from),
            xdg_data_home: xdg.map(String::from),
        }
    }

    #[test]
    fn systemd_state_directory_wins() {
        let dir = default_data_dir(&env(
            Some("/var/lib/defter:/var/lib/other"),
            true,
            None,
            None,
        ));
        assert_eq!(dir, PathBuf::from("/var/lib/defter"));
    }

    #[test]
    fn root_uses_the_system_directory() {
        let dir = default_data_dir(&env(None, true, Some("/root"), None));
        assert_eq!(dir, PathBuf::from(SYSTEM_DATA_DIR));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_mac_user_gets_application_support() {
        let dir = default_data_dir(&env(None, false, Some("/Users/me"), Some("/ignored")));
        assert_eq!(
            dir,
            PathBuf::from("/Users/me/Library/Application Support/defter")
        );
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn a_linux_user_gets_xdg_data_home() {
        let xdg = default_data_dir(&env(None, false, Some("/home/me"), Some("/data")));
        assert_eq!(xdg, PathBuf::from("/data/defter"));
        let local = default_data_dir(&env(None, false, Some("/home/me"), Some("relative")));
        assert_eq!(local, PathBuf::from("/home/me/.local/share/defter"));
    }

    #[test]
    fn no_home_falls_back_to_the_system_directory() {
        assert_eq!(
            default_data_dir(&env(None, false, None, None)),
            PathBuf::from(SYSTEM_DATA_DIR)
        );
    }
}