mobux 0.30.0

A touch-friendly tmux web UI for unhinged people who run terminal sessions from their phone while walking the dog
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
//! The typed configuration tree, its defaults, its JSON schema and the loader
//! that reads `config.json` out of the config directory.
//!
//! Nothing wires this into the server yet — the module lands first so the
//! schema, the defaults and the error messages can be reviewed on their own.
#![allow(dead_code)]

use std::fmt;
use std::path::{Path, PathBuf};

use garde::Validate;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

pub const CONFIG_FILE_NAME: &str = "config.json";
pub const SCHEMA_PATH: &str = "docs/mobux.schema.json";

const DEFAULT_PORT: u16 = 8080;
const DEFAULT_ACME_DIRECTORY: &str = "https://acme-v02.api.letsencrypt.org/directory";
const DEFAULT_ACME_HTTP_PORT: u16 = 80;
const DEFAULT_SERVICE_NAME: &str = "mobux";
const DEFAULT_VAPID_CONTACT: &str = "mailto:admin@example.com";
const DEFAULT_UPDATE_CHECK_URL: &str = "https://index.crates.io/mo/bu/mobux";

// ---------------------------------------------------------------------------
// The tree
// ---------------------------------------------------------------------------

/// Every setting mobux reads from a file. Absent state is a sentinel — an empty
/// string or an empty list — never a missing attribute, so a merged config is
/// always fully populated.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    #[garde(dive)]
    pub server: ServerConfig,
    #[serde(default)]
    #[garde(dive)]
    pub auth: AuthConfig,
    #[serde(default)]
    #[garde(dive)]
    pub tls: TlsConfig,
    #[serde(default)]
    #[garde(dive)]
    pub paths: PathsConfig,
    #[serde(default)]
    #[garde(dive)]
    pub session: SessionConfig,
    #[serde(default)]
    #[garde(dive)]
    pub app: AppConfig,
    #[serde(default)]
    #[garde(dive)]
    pub push: PushConfig,
    #[serde(default)]
    #[garde(dive)]
    pub update: UpdateConfig,
}

/// Where the server listens.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
    /// TCP port to listen on. Env: `MOBUX_PORT`. Flag: `--port`.
    #[serde(default = "default_port")]
    #[garde(range(min = 1))]
    pub port: u16,
}

/// The credentials that unlock the web UI.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct AuthConfig {
    /// Username. Empty means unset. Env: `MOBUX_AUTH_USER`. Flag: `--user`.
    #[serde(default)]
    #[garde(custom(plain_value))]
    pub user: String,
    /// Password. Empty means unset; `pin` is the usual way to set it.
    /// Env: `MOBUX_AUTH_PASS`.
    #[serde(default)]
    #[garde(custom(plain_value))]
    pub pass: String,
    /// Numeric PIN, 4-64 characters. Empty means unset. Env: `MOBUX_PIN`.
    /// Flag: `--pin`.
    #[serde(default)]
    #[garde(custom(pin_value))]
    pub pin: String,
}

/// HTTPS: the built-in CA, a supplied key pair, or ACME.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct TlsConfig {
    /// Serve HTTPS. Env: `MOBUX_TLS`.
    #[serde(default = "default_tls_enabled")]
    #[garde(skip)]
    pub enabled: bool,
    /// Extra hostnames to add to the generated certificate.
    /// Env: `MOBUX_TLS_HOSTS` (comma separated).
    #[serde(default)]
    #[garde(inner(custom(host_value)))]
    pub hosts: Vec<String>,
    /// Path to a certificate PEM. Set both this and `key_file` to skip
    /// certificate generation. Env: `MOBUX_CERT_FILE`.
    #[serde(default)]
    #[garde(skip)]
    pub cert_file: String,
    /// Path to the private key PEM matching `cert_file`. Env: `MOBUX_KEY_FILE`.
    #[serde(default)]
    #[garde(skip)]
    pub key_file: String,
    /// Domains to obtain an ACME certificate for. A non-empty list switches
    /// TLS into ACME mode. Env: `MOBUX_ACME_DOMAINS` (comma separated).
    #[serde(default)]
    #[garde(inner(custom(host_value)))]
    pub acme_domains: Vec<String>,
    /// Account contact for the ACME directory. Required in ACME mode.
    /// Env: `MOBUX_ACME_EMAIL`.
    #[serde(default)]
    #[garde(custom(email_value))]
    pub acme_email: String,
    /// ACME directory URL. Env: `MOBUX_ACME_DIRECTORY`.
    #[serde(default = "default_acme_directory")]
    #[garde(custom(https_url_value))]
    pub acme_directory: String,
    /// Port the HTTP-01 challenge responder binds. Env: `MOBUX_ACME_HTTP_PORT`.
    #[serde(default = "default_acme_http_port")]
    #[garde(range(min = 1))]
    pub acme_http_port: u16,
}

/// Where mobux keeps its state.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct PathsConfig {
    /// Directory for the database and other state. Empty means the platform
    /// data directory. Env: `MOBUX_DATA_DIR`.
    #[serde(default)]
    #[garde(skip)]
    pub data_dir: String,
}

/// How a terminal session starts.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct SessionConfig {
    /// Shell to launch inside tmux. Empty means `$SHELL`.
    /// Env: `MOBUX_SESSION_SHELL`.
    #[serde(default)]
    #[garde(skip)]
    pub shell: String,
}

/// Identity of this instance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct AppConfig {
    /// Public `host` or `host:port` the Android app is pinned to. Empty means
    /// unset. Env: `MOBUX_DOMAIN`.
    #[serde(default)]
    #[garde(custom(authority_value))]
    pub domain: String,
    /// Dev mode, reported through `/api/build-info`. Env: `MOBUX_DEV`.
    #[serde(default)]
    #[garde(skip)]
    pub dev: bool,
    /// systemd unit the self-updater restarts. Env: `MOBUX_SERVICE_NAME`.
    #[serde(default = "default_service_name")]
    #[garde(custom(service_name_value))]
    pub service_name: String,
}

/// Web push.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct PushConfig {
    /// VAPID contact, a `mailto:` or `https:` URL. Env: `MOBUX_VAPID_CONTACT`.
    #[serde(default = "default_vapid_contact")]
    #[garde(custom(vapid_contact_value))]
    pub vapid_contact: String,
}

/// The self-updater.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields)]
pub struct UpdateConfig {
    /// Where the version list is fetched from. Env: `MOBUX_UPDATE_CHECK_URL`.
    #[serde(default = "default_update_check_url")]
    #[garde(custom(https_url_value))]
    pub check_url: String,
}

fn default_port() -> u16 {
    DEFAULT_PORT
}

fn default_tls_enabled() -> bool {
    true
}

fn default_acme_directory() -> String {
    DEFAULT_ACME_DIRECTORY.to_string()
}

fn default_acme_http_port() -> u16 {
    DEFAULT_ACME_HTTP_PORT
}

fn default_service_name() -> String {
    DEFAULT_SERVICE_NAME.to_string()
}

fn default_vapid_contact() -> String {
    DEFAULT_VAPID_CONTACT.to_string()
}

fn default_update_check_url() -> String {
    DEFAULT_UPDATE_CHECK_URL.to_string()
}

impl Default for ServerConfig {
    fn default() -> Self {
        ServerConfig {
            port: default_port(),
        }
    }
}

impl Default for TlsConfig {
    fn default() -> Self {
        TlsConfig {
            enabled: default_tls_enabled(),
            hosts: Vec::new(),
            cert_file: String::new(),
            key_file: String::new(),
            acme_domains: Vec::new(),
            acme_email: String::new(),
            acme_directory: default_acme_directory(),
            acme_http_port: default_acme_http_port(),
        }
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        AppConfig {
            domain: String::new(),
            dev: false,
            service_name: default_service_name(),
        }
    }
}

impl Default for PushConfig {
    fn default() -> Self {
        PushConfig {
            vapid_contact: default_vapid_contact(),
        }
    }
}

impl Default for UpdateConfig {
    fn default() -> Self {
        UpdateConfig {
            check_url: default_update_check_url(),
        }
    }
}

// ---------------------------------------------------------------------------
// The partial mirror
// ---------------------------------------------------------------------------

/// The same tree with every leaf optional. A config file only states what it
/// overrides, so this is what the loader deserializes before merging onto the
/// defaults.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialConfig {
    #[serde(default)]
    pub server: Option<PartialServerConfig>,
    #[serde(default)]
    pub auth: Option<PartialAuthConfig>,
    #[serde(default)]
    pub tls: Option<PartialTlsConfig>,
    #[serde(default)]
    pub paths: Option<PartialPathsConfig>,
    #[serde(default)]
    pub session: Option<PartialSessionConfig>,
    #[serde(default)]
    pub app: Option<PartialAppConfig>,
    #[serde(default)]
    pub push: Option<PartialPushConfig>,
    #[serde(default)]
    pub update: Option<PartialUpdateConfig>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialServerConfig {
    #[serde(default)]
    pub port: Option<u16>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialAuthConfig {
    #[serde(default)]
    pub user: Option<String>,
    #[serde(default)]
    pub pass: Option<String>,
    #[serde(default)]
    pub pin: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialTlsConfig {
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub hosts: Option<Vec<String>>,
    #[serde(default)]
    pub cert_file: Option<String>,
    #[serde(default)]
    pub key_file: Option<String>,
    #[serde(default)]
    pub acme_domains: Option<Vec<String>>,
    #[serde(default)]
    pub acme_email: Option<String>,
    #[serde(default)]
    pub acme_directory: Option<String>,
    #[serde(default)]
    pub acme_http_port: Option<u16>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialPathsConfig {
    #[serde(default)]
    pub data_dir: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialSessionConfig {
    #[serde(default)]
    pub shell: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialAppConfig {
    #[serde(default)]
    pub domain: Option<String>,
    #[serde(default)]
    pub dev: Option<bool>,
    #[serde(default)]
    pub service_name: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialPushConfig {
    #[serde(default)]
    pub vapid_contact: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialUpdateConfig {
    #[serde(default)]
    pub check_url: Option<String>,
}

impl Config {
    /// Overlay a partial onto this config. A stated leaf wins; anything absent
    /// keeps the value it already had.
    pub fn merged(mut self, partial: PartialConfig) -> Config {
        if let Some(server) = partial.server {
            overlay(&mut self.server.port, server.port);
        }
        if let Some(auth) = partial.auth {
            overlay(&mut self.auth.user, auth.user);
            overlay(&mut self.auth.pass, auth.pass);
            overlay(&mut self.auth.pin, auth.pin);
        }
        if let Some(tls) = partial.tls {
            overlay(&mut self.tls.enabled, tls.enabled);
            overlay(&mut self.tls.hosts, tls.hosts);
            overlay(&mut self.tls.cert_file, tls.cert_file);
            overlay(&mut self.tls.key_file, tls.key_file);
            overlay(&mut self.tls.acme_domains, tls.acme_domains);
            overlay(&mut self.tls.acme_email, tls.acme_email);
            overlay(&mut self.tls.acme_directory, tls.acme_directory);
            overlay(&mut self.tls.acme_http_port, tls.acme_http_port);
        }
        if let Some(paths) = partial.paths {
            overlay(&mut self.paths.data_dir, paths.data_dir);
        }
        if let Some(session) = partial.session {
            overlay(&mut self.session.shell, session.shell);
        }
        if let Some(app) = partial.app {
            overlay(&mut self.app.domain, app.domain);
            overlay(&mut self.app.dev, app.dev);
            overlay(&mut self.app.service_name, app.service_name);
        }
        if let Some(push) = partial.push {
            overlay(&mut self.push.vapid_contact, push.vapid_contact);
        }
        if let Some(update) = partial.update {
            overlay(&mut self.update.check_url, update.check_url);
        }
        self
    }
}

fn overlay<T>(target: &mut T, value: Option<T>) {
    if let Some(value) = value {
        *target = value;
    }
}

// ---------------------------------------------------------------------------
// Field metadata
// ---------------------------------------------------------------------------

/// A file key and the environment variable and flag that override it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldSpec {
    /// Dotted path into the config tree, e.g. `server.port`.
    pub key: &'static str,
    pub env: &'static str,
    pub flag: Option<&'static str>,
}

/// Every settable field, with the environment variable and flag beside it.
pub const FIELDS: &[FieldSpec] = &[
    FieldSpec {
        key: "server.port",
        env: "MOBUX_PORT",
        flag: Some("--port"),
    },
    FieldSpec {
        key: "auth.user",
        env: "MOBUX_AUTH_USER",
        flag: Some("--user"),
    },
    FieldSpec {
        key: "auth.pass",
        env: "MOBUX_AUTH_PASS",
        flag: None,
    },
    FieldSpec {
        key: "auth.pin",
        env: "MOBUX_PIN",
        flag: Some("--pin"),
    },
    FieldSpec {
        key: "tls.enabled",
        env: "MOBUX_TLS",
        flag: None,
    },
    FieldSpec {
        key: "tls.hosts",
        env: "MOBUX_TLS_HOSTS",
        flag: None,
    },
    FieldSpec {
        key: "tls.cert_file",
        env: "MOBUX_CERT_FILE",
        flag: None,
    },
    FieldSpec {
        key: "tls.key_file",
        env: "MOBUX_KEY_FILE",
        flag: None,
    },
    FieldSpec {
        key: "tls.acme_domains",
        env: "MOBUX_ACME_DOMAINS",
        flag: None,
    },
    FieldSpec {
        key: "tls.acme_email",
        env: "MOBUX_ACME_EMAIL",
        flag: None,
    },
    FieldSpec {
        key: "tls.acme_directory",
        env: "MOBUX_ACME_DIRECTORY",
        flag: None,
    },
    FieldSpec {
        key: "tls.acme_http_port",
        env: "MOBUX_ACME_HTTP_PORT",
        flag: None,
    },
    FieldSpec {
        key: "paths.data_dir",
        env: "MOBUX_DATA_DIR",
        flag: None,
    },
    FieldSpec {
        key: "session.shell",
        env: "MOBUX_SESSION_SHELL",
        flag: None,
    },
    FieldSpec {
        key: "app.domain",
        env: "MOBUX_DOMAIN",
        flag: None,
    },
    FieldSpec {
        key: "app.dev",
        env: "MOBUX_DEV",
        flag: None,
    },
    FieldSpec {
        key: "app.service_name",
        env: "MOBUX_SERVICE_NAME",
        flag: None,
    },
    FieldSpec {
        key: "push.vapid_contact",
        env: "MOBUX_VAPID_CONTACT",
        flag: None,
    },
    FieldSpec {
        key: "update.check_url",
        env: "MOBUX_UPDATE_CHECK_URL",
        flag: None,
    },
];

/// Environment variables that deliberately have no file key: they locate the
/// file itself, name a deprecated alias, or exist only for tests and the
/// installer.
pub const ENV_ONLY: &[&str] = &[
    "PORT",
    "MOBUX_CONFIG_DIR",
    "MOBUX_TMUX_SOCKET",
    "MOBUX_UPDATE_TEST_INDEX",
    "MOBUX_UPDATE_DISABLE_RUN",
    "MOBUX_DEV_CERT",
    "MOBUX_DEV_KEY",
];

// ---------------------------------------------------------------------------
// Config directory
// ---------------------------------------------------------------------------

/// The environment the config directory is resolved from — passed in so the
/// resolution is a pure function the tests can drive.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DirEnv {
    pub mobux_config_dir: Option<String>,
    pub xdg_config_home: Option<String>,
    pub home: Option<String>,
}

impl DirEnv {
    pub fn from_env() -> Self {
        let read = |key: &str| std::env::var(key).ok();
        DirEnv {
            mobux_config_dir: read("MOBUX_CONFIG_DIR"),
            xdg_config_home: read("XDG_CONFIG_HOME"),
            home: read("HOME"),
        }
    }
}

/// `MOBUX_CONFIG_DIR`, then `$XDG_CONFIG_HOME/mobux`, then `~/.config/mobux`.
/// The single answer for every caller that used to resolve this itself.
pub fn resolve_config_dir(env: &DirEnv) -> PathBuf {
    if let Some(dir) = non_empty(&env.mobux_config_dir) {
        return PathBuf::from(dir);
    }
    if let Some(dir) = non_empty(&env.xdg_config_home) {
        return PathBuf::from(dir).join("mobux");
    }
    let home = non_empty(&env.home).unwrap_or(".");
    PathBuf::from(home).join(".config").join("mobux")
}

pub fn config_dir() -> PathBuf {
    resolve_config_dir(&DirEnv::from_env())
}

pub fn config_file_path() -> PathBuf {
    config_dir().join(CONFIG_FILE_NAME)
}

fn non_empty(value: &Option<String>) -> Option<&str> {
    value.as_deref().map(str::trim).filter(|v| !v.is_empty())
}

// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub enum LoadError {
    /// The file could not be read.
    Read { path: PathBuf, message: String },
    /// The bytes are not JSON.
    Syntax { path: PathBuf, message: String },
    /// The JSON is not this shape: an unknown key, or a value of the wrong type.
    Shape {
        path: PathBuf,
        key: String,
        message: String,
        suggestion: Option<String>,
    },
    /// The shape is right but a value is out of range.
    Invalid { path: PathBuf, message: String },
}

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LoadError::Read { path, message } => {
                write!(f, "{}: {message}", path.display())
            }
            LoadError::Syntax { path, message } => {
                write!(f, "{}: not valid JSON: {message}", path.display())
            }
            LoadError::Shape {
                path,
                key,
                message,
                suggestion,
            } => {
                write!(f, "{}: at `{key}`: {message}", path.display())?;
                match suggestion {
                    Some(word) => write!(f, " — did you mean `{word}`?"),
                    None => Ok(()),
                }
            }
            LoadError::Invalid { path, message } => {
                write!(f, "{}: {message}", path.display())
            }
        }
    }
}

impl std::error::Error for LoadError {}

/// Read, merge and validate the config file. A missing file is the default
/// config — mobux runs without one.
pub fn load_from(path: &Path) -> Result<Config, LoadError> {
    let raw = match std::fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Config::default()),
        Err(err) => {
            return Err(LoadError::Read {
                path: path.to_path_buf(),
                message: err.to_string(),
            })
        }
    };
    parse(path, &raw)
}

pub fn load() -> Result<Config, LoadError> {
    load_from(&config_file_path())
}

/// Parse one config document. `path` only names the source in error messages.
pub fn parse(path: &Path, raw: &str) -> Result<Config, LoadError> {
    let partial = parse_partial(path, raw)?;
    let config = Config::default().merged(partial);
    validate(path, &config)?;
    Ok(config)
}

fn parse_partial(path: &Path, raw: &str) -> Result<PartialConfig, LoadError> {
    let mut deserializer = serde_json::Deserializer::from_str(raw);
    serde_path_to_error::deserialize(&mut deserializer).map_err(|err| shape_error(path, err))
}

fn shape_error(path: &Path, err: serde_path_to_error::Error<serde_json::Error>) -> LoadError {
    let key = pointer_of(&err);
    let inner = err.into_inner();
    if matches!(
        inner.classify(),
        serde_json::error::Category::Syntax | serde_json::error::Category::Eof
    ) {
        return LoadError::Syntax {
            path: path.to_path_buf(),
            message: inner.to_string(),
        };
    }
    let message = inner.to_string();
    let suggestion = unknown_field_suggestion(&message);
    LoadError::Shape {
        path: path.to_path_buf(),
        key,
        message,
        suggestion,
    }
}

fn pointer_of(err: &serde_path_to_error::Error<serde_json::Error>) -> String {
    let path = err.path().to_string();
    if path.is_empty() || path == "." {
        return "(root)".to_string();
    }
    path
}

/// serde names the unknown key and lists the ones it expected. Pick the closest
/// expected key so a typo reads as a typo rather than a rejection.
fn unknown_field_suggestion(message: &str) -> Option<String> {
    let rest = message.strip_prefix("unknown field `")?;
    let (unknown, rest) = rest.split_once('`')?;
    let candidates = backticked(rest);
    let best = candidates
        .into_iter()
        .map(|candidate| (edit_distance(unknown, candidate), candidate))
        .min_by_key(|(distance, _)| *distance)?;
    let (distance, candidate) = best;
    if distance == 0 || distance > 3 || distance >= candidate.chars().count() {
        return None;
    }
    Some(candidate.to_string())
}

fn backticked(text: &str) -> Vec<&str> {
    text.split('`').skip(1).step_by(2).collect()
}

fn edit_distance(left: &str, right: &str) -> usize {
    let right_chars: Vec<char> = right.chars().collect();
    let mut previous: Vec<usize> = (0..=right_chars.len()).collect();
    let mut current = vec![0usize; right_chars.len() + 1];
    for (row, left_char) in left.chars().enumerate() {
        current[0] = row + 1;
        for (column, right_char) in right_chars.iter().enumerate() {
            let substitution = previous[column] + usize::from(left_char != *right_char);
            current[column + 1] = substitution
                .min(previous[column + 1] + 1)
                .min(current[column] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[right_chars.len()]
}

fn validate(path: &Path, config: &Config) -> Result<(), LoadError> {
    if let Err(report) = config.validate() {
        return Err(LoadError::Invalid {
            path: path.to_path_buf(),
            message: report.to_string().trim().to_string(),
        });
    }
    if !config.tls.acme_domains.is_empty() && config.tls.acme_email.trim().is_empty() {
        return Err(LoadError::Invalid {
            path: path.to_path_buf(),
            message: "tls.acme_email: required when tls.acme_domains is set".to_string(),
        });
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Value rules
// ---------------------------------------------------------------------------

/// systemd splits an unquoted `Environment=` value on whitespace and eats
/// quotes and backslashes, so a credential carrying any of those reaches the
/// server mangled. Same rule as `service::render_unit` writes against.
fn plain_value(value: &str, _: &()) -> garde::Result {
    let offender = value
        .chars()
        .find(|c| c.is_whitespace() || c.is_control() || matches!(c, '"' | '\'' | '\\' | '$'));
    match offender {
        None => Ok(()),
        Some(c) => Err(garde::Error::new(format!(
            "contains {c:?}; whitespace, quotes, backslashes and $ cannot survive a systemd unit"
        ))),
    }
}

fn pin_value(value: &str, ctx: &()) -> garde::Result {
    plain_value(value, ctx)?;
    if value.is_empty() {
        return Ok(());
    }
    let length = value.chars().count();
    if !(4..=64).contains(&length) {
        return Err(garde::Error::new(
            "must be between 4 and 64 characters, or empty to leave the PIN unset",
        ));
    }
    Ok(())
}

fn host_value(value: &str, _: &()) -> garde::Result {
    if value.trim().is_empty() {
        return Err(garde::Error::new("must not be blank"));
    }
    let ok = value
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '*' | '_'));
    if !ok {
        return Err(garde::Error::new(
            "must be a hostname: letters, digits, dots, dashes",
        ));
    }
    Ok(())
}

fn authority_value(value: &str, ctx: &()) -> garde::Result {
    if value.is_empty() {
        return Ok(());
    }
    let (host, port) = match value.split_once(':') {
        Some((host, port)) => (host, Some(port)),
        None => (value, None),
    };
    host_value(host, ctx)?;
    match port {
        None => Ok(()),
        Some(port) if port.parse::<u16>().is_ok_and(|p| p > 0) => Ok(()),
        Some(_) => Err(garde::Error::new(
            "port must be a number between 1 and 65535",
        )),
    }
}

fn email_value(value: &str, _: &()) -> garde::Result {
    if value.is_empty() {
        return Ok(());
    }
    let Some((local, domain)) = value.split_once('@') else {
        return Err(garde::Error::new("must be an email address"));
    };
    if local.is_empty() || !domain.contains('.') || domain.starts_with('.') {
        return Err(garde::Error::new("must be an email address"));
    }
    Ok(())
}

fn https_url_value(value: &str, _: &()) -> garde::Result {
    if value.starts_with("https://") && value.len() > "https://".len() {
        return Ok(());
    }
    Err(garde::Error::new("must be an https:// URL"))
}

fn service_name_value(value: &str, ctx: &()) -> garde::Result {
    if value.is_empty() {
        return Err(garde::Error::new("must name a systemd unit"));
    }
    plain_value(value, ctx)
}

fn vapid_contact_value(value: &str, _: &()) -> garde::Result {
    let mailto = value
        .strip_prefix("mailto:")
        .is_some_and(|rest| rest.contains('@'));
    if mailto || value.starts_with("https://") {
        return Ok(());
    }
    Err(garde::Error::new(
        "must be a mailto: address or an https:// URL",
    ))
}

// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------

/// The JSON schema for `config.json`, generated from the types.
pub fn schema() -> serde_json::Value {
    serde_json::to_value(schemars::schema_for!(Config)).expect("schema serializes")
}

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

    const SOURCE: &str = "config.json";

    fn parse_str(raw: &str) -> Result<Config, LoadError> {
        parse(Path::new(SOURCE), raw)
    }

    fn message(raw: &str) -> String {
        parse_str(raw)
            .expect_err("expected a load error")
            .to_string()
    }

    /// Set `MOBUX_WRITE_SCHEMA=1` and run this test to rewrite the committed
    /// schema after changing the types.
    #[test]
    fn schema_file_matches_the_types() {
        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(SCHEMA_PATH);
        let generated = format!("{}\n", serde_json::to_string_pretty(&schema()).unwrap());
        if std::env::var_os("MOBUX_WRITE_SCHEMA").is_some() {
            std::fs::write(&path, &generated).expect("writing the schema");
            return;
        }
        let committed = std::fs::read_to_string(&path).expect("docs/mobux.schema.json exists");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&committed).expect("valid JSON"),
            schema(),
            "docs/mobux.schema.json is stale — rerun this test with MOBUX_WRITE_SCHEMA=1"
        );
    }

    /// Sections are `$ref`s into `$defs`, so a dotted key is two hops.
    fn schema_node(schema: &serde_json::Value, key: &str) -> serde_json::Value {
        let (section, leaf) = key.split_once('.').expect("dotted key");
        let reference = schema["properties"][section]["$ref"]
            .as_str()
            .unwrap_or_else(|| panic!("no section `{section}` in the schema"))
            .rsplit('/')
            .next()
            .expect("a $defs pointer")
            .to_string();
        schema["$defs"][reference]["properties"][leaf].clone()
    }

    #[test]
    fn schema_marks_every_field_optional_and_rejects_unknown_keys() {
        let schema = schema();
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
        assert!(schema.get("required").is_none());
        assert_eq!(
            schema["$defs"]["ServerConfig"]["additionalProperties"],
            serde_json::json!(false)
        );
        assert_eq!(
            schema_node(&schema, "server.port")["default"],
            serde_json::json!(8080)
        );
    }

    #[test]
    fn an_empty_document_is_the_default_config() {
        assert_eq!(parse_str("{}").unwrap(), Config::default());
    }

    #[test]
    fn defaults_mirror_the_values_the_server_uses_today() {
        let config = Config::default();
        assert_eq!(config.server.port, 8080);
        assert!(config.tls.enabled);
        assert_eq!(config.tls.acme_http_port, 80);
        assert_eq!(config.app.service_name, "mobux");
        assert_eq!(config.push.vapid_contact, "mailto:admin@example.com");
        assert!(!config.app.dev);
    }

    #[test]
    fn a_stated_leaf_wins_and_the_rest_keeps_its_default() {
        let config = parse_str(r#"{"server": {"port": 5151}}"#).unwrap();
        assert_eq!(config.server.port, 5151);
        assert!(config.tls.enabled);
        assert_eq!(config.update.check_url, Config::default().update.check_url);
    }

    #[test]
    fn every_section_round_trips_through_the_partial_mirror() {
        let raw = serde_json::to_string(&Config::default()).unwrap();
        assert_eq!(parse_str(&raw).unwrap(), Config::default());
    }

    #[test]
    fn malformed_json_names_the_position() {
        let error = message(r#"{"server": }"#);
        assert!(error.starts_with("config.json: not valid JSON:"), "{error}");
        assert!(error.contains("line 1"), "{error}");
    }

    #[test]
    fn an_unknown_key_suggests_the_nearest_spelling() {
        let error = message(r#"{"server": {"prot": 8080}}"#);
        assert!(error.contains("at `server.prot`"), "{error}");
        assert!(error.contains("did you mean `port`?"), "{error}");
    }

    #[test]
    fn an_unknown_section_suggests_the_nearest_section() {
        let error = message(r#"{"serve": {}}"#);
        assert!(error.contains("did you mean `server`?"), "{error}");
    }

    #[test]
    fn an_unrecognisable_key_is_reported_without_a_guess() {
        let error = message(r#"{"telemetry": {}}"#);
        assert!(error.contains("unknown field `telemetry`"), "{error}");
        assert!(!error.contains("did you mean"), "{error}");
    }

    #[test]
    fn a_wrong_type_names_the_key_and_the_expected_type() {
        let error = message(r#"{"server": {"port": "8080"}}"#);
        assert!(error.contains("at `server.port`"), "{error}");
        assert!(error.contains("invalid type: string"), "{error}");
    }

    #[test]
    fn a_number_outside_the_port_range_is_rejected_by_serde() {
        let error = message(r#"{"server": {"port": 70000}}"#);
        assert!(error.contains("at `server.port`"), "{error}");
    }

    #[test]
    fn port_zero_is_rejected_by_the_range_rule() {
        let error = message(r#"{"server": {"port": 0}}"#);
        assert!(error.contains("server.port"), "{error}");
    }

    #[test]
    fn a_short_pin_is_rejected() {
        let error = message(r#"{"auth": {"pin": "12"}}"#);
        assert!(error.contains("auth.pin"), "{error}");
        assert!(error.contains("between 4 and 64"), "{error}");
    }

    #[test]
    fn an_empty_pin_leaves_the_pin_unset() {
        assert_eq!(parse_str(r#"{"auth": {"pin": ""}}"#).unwrap().auth.pin, "");
    }

    #[test]
    fn a_credential_systemd_would_mangle_is_rejected() {
        let error = message(r#"{"auth": {"pass": "hunter 2"}}"#);
        assert!(error.contains("auth.pass"), "{error}");
    }

    #[test]
    fn a_blank_tls_host_is_rejected() {
        let error = message(r#"{"tls": {"hosts": ["ok.example", "  "]}}"#);
        assert!(error.contains("tls.hosts[1]"), "{error}");
    }

    #[test]
    fn acme_domains_without_an_email_are_rejected() {
        let error = message(r#"{"tls": {"acme_domains": ["mobux.example"]}}"#);
        assert!(error.contains("tls.acme_email"), "{error}");
        assert!(error.contains("required"), "{error}");
    }

    #[test]
    fn acme_domains_with_an_email_are_accepted() {
        let config = parse_str(
            r#"{"tls": {"acme_domains": ["a.example"], "acme_email": "me@example.com"}}"#,
        )
        .unwrap();
        assert_eq!(config.tls.acme_domains, vec!["a.example".to_string()]);
    }

    #[test]
    fn a_plain_http_acme_directory_is_rejected() {
        let error = message(r#"{"tls": {"acme_directory": "http://acme.example/dir"}}"#);
        assert!(error.contains("tls.acme_directory"), "{error}");
        assert!(error.contains("https://"), "{error}");
    }

    #[test]
    fn a_domain_may_carry_a_port() {
        let config = parse_str(r#"{"app": {"domain": "mobux.example:5151"}}"#).unwrap();
        assert_eq!(config.app.domain, "mobux.example:5151");
    }

    #[test]
    fn a_domain_with_a_junk_port_is_rejected() {
        let error = message(r#"{"app": {"domain": "mobux.example:https"}}"#);
        assert!(error.contains("app.domain"), "{error}");
    }

    #[test]
    fn an_empty_service_name_is_rejected() {
        let error = message(r#"{"app": {"service_name": ""}}"#);
        assert!(error.contains("app.service_name"), "{error}");
    }

    #[test]
    fn a_vapid_contact_must_be_mailto_or_https() {
        let error = message(r#"{"push": {"vapid_contact": "admin@example.com"}}"#);
        assert!(error.contains("push.vapid_contact"), "{error}");
    }

    #[test]
    fn a_missing_file_is_the_default_config() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(CONFIG_FILE_NAME);
        assert_eq!(load_from(&path).unwrap(), Config::default());
    }

    #[test]
    fn a_file_on_disk_is_read_and_merged() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(CONFIG_FILE_NAME);
        std::fs::write(&path, r#"{"session": {"shell": "/bin/zsh"}}"#).unwrap();
        assert_eq!(load_from(&path).unwrap().session.shell, "/bin/zsh");
    }

    #[test]
    fn config_dir_prefers_the_explicit_override() {
        let env = DirEnv {
            mobux_config_dir: Some("/srv/mobux".to_string()),
            xdg_config_home: Some("/home/me/.xdg".to_string()),
            home: Some("/home/me".to_string()),
        };
        assert_eq!(resolve_config_dir(&env), PathBuf::from("/srv/mobux"));
    }

    #[test]
    fn config_dir_falls_back_to_xdg_config_home() {
        let env = DirEnv {
            mobux_config_dir: None,
            xdg_config_home: Some("/home/me/.xdg".to_string()),
            home: Some("/home/me".to_string()),
        };
        assert_eq!(
            resolve_config_dir(&env),
            PathBuf::from("/home/me/.xdg/mobux")
        );
    }

    #[test]
    fn config_dir_falls_back_to_home() {
        let env = DirEnv {
            mobux_config_dir: None,
            xdg_config_home: None,
            home: Some("/home/me".to_string()),
        };
        assert_eq!(
            resolve_config_dir(&env),
            PathBuf::from("/home/me/.config/mobux")
        );
    }

    #[test]
    fn an_empty_override_is_ignored() {
        let env = DirEnv {
            mobux_config_dir: Some("  ".to_string()),
            xdg_config_home: Some(String::new()),
            home: Some("/home/me".to_string()),
        };
        assert_eq!(
            resolve_config_dir(&env),
            PathBuf::from("/home/me/.config/mobux")
        );
    }

    #[test]
    fn config_dir_without_a_home_stays_relative() {
        assert_eq!(
            resolve_config_dir(&DirEnv::default()),
            PathBuf::from("./.config/mobux")
        );
    }

    #[test]
    fn every_field_spec_names_a_key_in_the_schema() {
        let schema = schema();
        for field in FIELDS {
            let node = schema_node(&schema, field.key);
            assert!(!node.is_null(), "{} is missing from the schema", field.key);
            let description = node["description"].as_str().unwrap_or_default();
            assert!(
                description.contains(field.env),
                "{} does not document {}",
                field.key,
                field.env
            );
        }
    }

    #[test]
    fn the_env_namespaces_do_not_overlap() {
        for field in FIELDS {
            assert!(
                !ENV_ONLY.contains(&field.env),
                "{} is listed both in the schema and as env-only",
                field.env
            );
        }
    }
}