geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
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
//! The deployment settings of `geolith dataset`: one file, one struct.
//!
//! Everything that names an operator's own deployment lives here and nowhere
//! else: the object store (endpoint, region, bucket, key prefix, account),
//! the URLs the live check reads, the public source hosts, the alerts, the
//! data root and the repo. Every value has an environment name; the values
//! come from the process environment, then the mode-600 `.env` file (path
//! from `GEOLITH_ENV_FILE`, else `.env` in the current directory), then the
//! optional `geolith.json` (only when `--config` or `GEOLITH_CONFIG` names
//! it), parsed once into [`Deployment`]; the precedence is flag, process
//! environment, `.env`, JSON file, neutral default. No path under `$HOME` is
//! read by default. The binary holds no operator value: a missing one is a
//! named error that points at `.env.example` and `geolith.example.json`.
//!
//! This module is the only one of `src/dataset` that reads the process
//! environment; `no_other_module_reads_the_environment` fails when another
//! one does.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use anyhow::{Context, Result, bail};
use serde::Deserialize;

use crate::s3::sigv4::Credentials;

/// The key prefix when `storage.prefix` is not set.
pub const DEFAULT_KEY_PREFIX: &str = "datasets/";

/// The signing region when `storage.region` is not set.
pub const DEFAULT_REGION: &str = "us-east-1";

/// The file an operator copies and fills in.
pub const EXAMPLE_FILE: &str = "geolith.example.json";

/// The env file an operator copies and fills in.
pub const ENV_EXAMPLE_FILE: &str = ".env.example";

/// The env file in the current directory when `GEOLITH_ENV_FILE` names none.
pub const DEFAULT_ENV_FILE: &str = ".env";

/// The placeholders a publish URL may hold.
const PLACEHOLDERS: [&str; 3] = ["dataset", "country", "build_id"];

/// Env names of the storage key id, then of the secret; the first set wins.
const KEY_ID_NAMES: [&str; 4] = [
    "GEOLITH_STORAGE_ACCESS_KEY_ID",
    "GEOLITH_R2_ACCESS_KEY_ID",
    "DATASETS_R2_ACCESS_KEY_ID",
    "AWS_ACCESS_KEY_ID",
];

/// Env names of the storage secret.
const SECRET_NAMES: [&str; 4] = [
    "GEOLITH_STORAGE_SECRET_ACCESS_KEY",
    "GEOLITH_R2_SECRET_ACCESS_KEY",
    "DATASETS_R2_SECRET_ACCESS_KEY",
    "AWS_SECRET_ACCESS_KEY",
];

/// A source of environment values: `None` when the variable is not set.
type Env<'a> = &'a dyn Fn(&str) -> Option<String>;

/// The process environment, the one read of it.
fn process_env(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// The value of `name`, when set and not empty.
fn get(env: Env<'_>, name: &str) -> Option<String> {
    env(name).filter(|value| !value.is_empty())
}

/// The first value among `names` that is set and not empty.
fn first(env: Env<'_>, names: &[&str]) -> Option<String> {
    names.iter().find_map(|name| get(env, name))
}

/// `$HOME`-relative `~/` expanded; any other text is the path as written.
fn path_of(home: Option<&Path>, text: &str) -> PathBuf {
    match (text.strip_prefix("~/"), home) {
        (Some(rest), Some(home)) => home.join(rest),
        _ => PathBuf::from(text),
    }
}

/// The JSON file, field by field. Unknown fields are refused so a typo is
/// named instead of silently ignored.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileSettings {
    data_root: Option<String>,
    repo: Option<String>,
    storage: FileStorage,
    publish: FilePublish,
    sources: FileSources,
    alerts: FileAlerts,
}

/// The `storage` section of the file.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileStorage {
    endpoint: Option<String>,
    region: Option<String>,
    bucket: Option<String>,
    prefix: Option<String>,
    account_id: Option<String>,
    credentials_file: Option<String>,
}

/// The `publish` section of the file.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FilePublish {
    pointer_url: Option<String>,
    page_url: Option<String>,
    credentials_file: Option<String>,
}

/// The `sources` section of the file.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileSources {
    chirps_hosts: Option<Vec<String>>,
    cdse_stac: Option<String>,
    cdse_endpoint: Option<String>,
    cdse_credentials_file: Option<String>,
    boundaries_url_base: Option<String>,
}

/// The `alerts` section of the file.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileAlerts {
    macos_notification: Option<bool>,
}

/// The object store of the datasets, as configured: every part is optional
/// until a command that talks to the store needs it ([`Deployment::target`]).
#[derive(Debug, Clone, Default)]
pub struct StorageSettings {
    /// S3-compatible endpoint URL, `https://host` or `http://host:port`.
    pub endpoint: Option<String>,
    /// Signing region.
    pub region: Option<String>,
    /// The one bucket the datasets may be written to.
    pub bucket: Option<String>,
    /// Key prefix with a trailing `/`, already checked.
    pub prefix: Option<String>,
    /// The account the endpoint's first host label must name, when set.
    pub account_id: Option<String>,
    /// Mode-600 env file of the access key id and secret.
    pub credentials_file: Option<PathBuf>,
    /// The access key pair the environment names.
    pub env_credentials: Option<Credentials>,
}

/// What the live check reads after a publish; both parts are optional.
#[derive(Debug, Clone, Default)]
pub struct PublishSettings {
    /// URL template of the API's pointer, sent the bearer key when there is
    /// one.
    pub pointer_url: Option<String>,
    /// URL template of the page that names the build.
    pub page_url: Option<String>,
    /// Mode-600 env file holding `DATASETS_API_KEY`.
    pub credentials_file: Option<PathBuf>,
    /// The bearer key the environment names.
    pub api_key: Option<String>,
}

/// Where the public sources are read from.
#[derive(Debug, Clone, Default)]
pub struct SourceSettings {
    /// Hosts of the CHIRPS rasters, in order; empty means the public hosts.
    pub chirps_hosts: Vec<String>,
    /// STAC root of the Copernicus NDVI catalogue.
    pub cdse_stac: Option<String>,
    /// S3 endpoint of the Copernicus data space.
    pub cdse_endpoint: Option<String>,
    /// Mode-600 env file of the Copernicus S3 keys.
    pub cdse_credentials_file: Option<PathBuf>,
    /// The Copernicus keys the environment names.
    pub cdse_env_credentials: Option<Credentials>,
    /// Base URL the boundary archives are fetched from instead of their own.
    pub boundaries_url_base: Option<String>,
}

/// Per-run overrides only the environment carries, read once.
#[derive(Debug, Clone, Default)]
pub struct RunSettings {
    /// `DATASET`: the dataset when no flag names one.
    pub dataset: Option<String>,
    /// `COUNTRY`: the country when no flag names one.
    pub country: Option<String>,
    /// `COUNTRY_CONFIG`: the country config file.
    pub country_config: Option<PathBuf>,
    /// `BOUNDARY_RELEASE`, else `OVERTURE_RELEASE`.
    pub boundary_release: Option<String>,
    /// `BOUNDARY_TILES_REVISION`, as written.
    pub boundary_tiles_revision: Option<String>,
    /// `BASELINE`: the baseline years.
    pub baseline: Option<String>,
    /// `PUBLISHED_CSV`: the published list.
    pub published_csv: Option<PathBuf>,
    /// `GEOLITH_AREAS_DIR`: the areas of a debugging test.
    pub areas_dir: Option<PathBuf>,
    /// `CROSSWALK_CSV`: the crosswalk file; an empty value means none.
    pub crosswalk_csv: Option<PathBuf>,
    /// `LGD_DIR`: the folder of the official lists.
    pub lgd_dir: Option<PathBuf>,
    /// `CDSE_TODAY`: the day the NDVI series range is counted from.
    pub cdse_today: Option<String>,
    /// `DATASETS_PROBE_TIMEOUT_MS`: how long the live check waits.
    pub probe_timeout_ms: Option<u64>,
    /// `HOSTNAME`: the host name of the run lock.
    pub hostname: Option<String>,
    /// `DATASETS_MIN_FREE_GB`: the free space `baseline-pass` keeps.
    pub min_free_gb: Option<u64>,
}

/// The whole deployment of one run.
#[derive(Debug, Clone, Default)]
pub struct Deployment {
    /// The JSON config file that was read, when one was named.
    pub config_file: Option<PathBuf>,
    /// The `.env` file that was read, absolute, when there was one.
    pub env_file: Option<PathBuf>,
    /// `$HOME`.
    pub home: Option<PathBuf>,
    /// `$PATH`, handed on to the scheduled job.
    pub path: Option<String>,
    /// The data root: `DATA_ROOT`, else `data_root`.
    pub data_root: Option<PathBuf>,
    /// The repo root: `GEOLITH_REPO`, else `repo`.
    pub repo: Option<PathBuf>,
    /// The object store.
    pub storage: StorageSettings,
    /// The live check.
    pub publish: PublishSettings,
    /// The public sources.
    pub sources: SourceSettings,
    /// Whether a failure raises a macOS notification:
    /// `DATASETS_MACOS_NOTIFICATION`, else `alerts.macos_notification`;
    /// `DATASETS_REFRESH_NO_ALERT` silences it.
    pub macos_notification: bool,
    /// The per-run environment overrides.
    pub run: RunSettings,
}

/// A checked target of the object store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    /// Endpoint URL.
    pub endpoint: String,
    /// Signing region.
    pub region: String,
    /// The bucket.
    pub bucket: String,
    /// Key prefix with a trailing `/`.
    pub key_root: String,
}

impl Target {
    /// Why `name` is refused: only the configured bucket is ever written.
    ///
    /// # Errors
    ///
    /// Fails unless `name` is `storage.bucket`.
    pub fn check_bucket(&self, name: &str) -> Result<()> {
        if name.is_empty() {
            bail!("bucket \"\" refused: give a bucket name");
        }
        if name != self.bucket {
            bail!(
                "bucket \"{name}\" refused: it is not storage.bucket (\"{}\")",
                self.bucket
            );
        }
        Ok(())
    }
}

/// The error of a setting that must be there and is not.
fn missing(name: &str, env_name: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "{name} is not set; see {EXAMPLE_FILE} or {ENV_EXAMPLE_FILE} (or set {env_name})"
    )
}

/// `text` as a yes or no: `true`/`false`, `1`/`0`, `yes`/`no`, any case.
///
/// # Errors
///
/// Fails naming `name` for any other text.
fn parse_bool(name: &str, text: &str) -> Result<bool> {
    match text.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" => Ok(true),
        "false" | "0" | "no" => Ok(false),
        _ => bail!("{name} \"{text}\" is not true or false"),
    }
}

/// The host of `url` without a scheme or a path, port included.
#[must_use]
pub fn url_host(url: &str) -> &str {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    rest.split('/').next().unwrap_or_default()
}

/// Whether `url` is an `http(s)` URL with a host.
fn is_http_url(url: &str) -> bool {
    url.split_once("://")
        .is_some_and(|(scheme, _)| matches!(scheme, "http" | "https"))
        && !url_host(url).is_empty()
}

/// `text` as a key prefix with a trailing `/`.
///
/// # Errors
///
/// Fails when a segment is empty, `.`, `..`, or holds a character outside
/// letters, digits, `.`, `_` and `-`.
pub fn normalize_prefix(text: &str) -> Result<String> {
    let trimmed = text.trim_matches('/');
    let bad = trimmed.is_empty()
        || trimmed.split('/').any(|segment| {
            segment.is_empty()
                || segment == "."
                || segment == ".."
                || !segment
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
        });
    if bad {
        bail!(
            "storage.prefix \"{text}\" is not a key prefix: use segments of letters, digits, \
             '.', '_' and '-' split by '/'"
        );
    }
    Ok(format!("{trimmed}/"))
}

/// Checks the placeholders of the URL template `name`.
///
/// # Errors
///
/// Fails when the value is not an `http(s)` URL, a brace is not closed, or a
/// placeholder is not one of `{dataset}`, `{country}` and `{build_id}`.
fn check_template(name: &str, template: &str) -> Result<()> {
    if !is_http_url(template) {
        bail!("{name} \"{template}\" is not an http(s) URL");
    }
    let mut rest = template;
    while let Some(open) = rest.find('{') {
        let after = &rest[open + 1..];
        let Some(close) = after.find('}') else {
            bail!("{name} \"{template}\" has a '{{' that is never closed");
        };
        let word = &after[..close];
        if !PLACEHOLDERS.contains(&word) {
            bail!(
                "{name} has the unknown placeholder {{{word}}}: use {{dataset}}, {{country}} \
                 and {{build_id}}"
            );
        }
        rest = &after[close + 1..];
    }
    Ok(())
}

/// `template` with its placeholders replaced.
#[must_use]
pub fn fill_template(template: &str, dataset: &str, country: &str, build_id: &str) -> String {
    template
        .replace("{dataset}", dataset)
        .replace("{country}", country)
        .replace("{build_id}", build_id)
}

/// The `KEY=VALUE` pairs of an env file's text; `export NAME=value` is read
/// too.
fn parse_env_text(text: &str) -> BTreeMap<String, String> {
    let mut values = BTreeMap::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line
            .strip_prefix("export")
            .filter(|rest| rest.starts_with(char::is_whitespace))
            .map_or(line, str::trim_start);
        if let Some((key, value)) = line.split_once('=') {
            values.insert(
                key.trim().to_owned(),
                value.trim().trim_matches('"').trim_matches('\'').to_owned(),
            );
        }
    }
    values
}

/// Whether the permission bits `mode` give more than owner read and write.
const fn wider_than_600(mode: u32) -> bool {
    mode & 0o777 & !0o600 != 0
}

/// The pairs of the env file at `path`, mode 600 or narrower.
///
/// # Errors
///
/// Fails when the file cannot be read or its mode is wider than 600.
pub fn read_env_file(path: &Path) -> Result<BTreeMap<String, String>> {
    let metadata = fs::metadata(path).with_context(|| format!("reading {}", path.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let mode = metadata.permissions().mode() & 0o777;
        if wider_than_600(mode) {
            bail!(
                "{} is mode {mode:o}, not 600: run `chmod 600 {}`",
                path.display(),
                path.display()
            );
        }
    }
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    Ok(parse_env_text(&text))
}

/// The value of the first of `names` the pairs hold, else the first pair
/// whose name starts with `rclone_prefix` and ends with `suffix` (an rclone
/// remote's own variables).
fn pick_pair<'a>(
    values: &'a BTreeMap<String, String>,
    names: &[&str],
    suffix: &str,
) -> Option<&'a str> {
    names
        .iter()
        .find_map(|name| values.get(*name))
        .or_else(|| {
            values
                .iter()
                .find(|(name, _)| name.starts_with("RCLONE_CONFIG_") && name.ends_with(suffix))
                .map(|(_, value)| value)
        })
        .map(String::as_str)
        .filter(|value| !value.is_empty())
}

/// A key pair from `values`, when both halves are there.
fn pair_of(values: &BTreeMap<String, String>) -> Option<Credentials> {
    let key_id = pick_pair(values, &KEY_ID_NAMES, "_ACCESS_KEY_ID")?;
    let secret = pick_pair(values, &SECRET_NAMES, "_SECRET_ACCESS_KEY")?;
    Some(Credentials {
        key_id: key_id.to_owned(),
        secret: secret.to_owned(),
    })
}

/// `path` made absolute against `cwd`.
fn absolute_in(cwd: &Path, path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        path
    } else {
        cwd.join(path)
    }
}

/// The `.env` file of this run and its pairs: the file `GEOLITH_ENV_FILE`
/// names (it must exist), else `.env` in `cwd` when there is one.
///
/// # Errors
///
/// Fails when the named file is missing, either file cannot be read, or its
/// mode is wider than 600.
fn load_env_file(
    process: Env<'_>,
    cwd: &Path,
) -> Result<(Option<PathBuf>, BTreeMap<String, String>)> {
    let home = get(process, "HOME").map(PathBuf::from);
    let path = match get(process, "GEOLITH_ENV_FILE") {
        Some(text) => {
            let path = absolute_in(cwd, path_of(home.as_deref(), &text));
            if !path.is_file() {
                bail!(
                    "the env file {} does not exist (GEOLITH_ENV_FILE); see {ENV_EXAMPLE_FILE}",
                    path.display()
                );
            }
            path
        }
        None => {
            let path = cwd.join(DEFAULT_ENV_FILE);
            if !path.is_file() {
                return Ok((None, BTreeMap::new()));
            }
            path
        }
    };
    let values = read_env_file(&path)?;
    Ok((Some(path), values))
}

impl Deployment {
    /// The deployment of this process: the process environment, the `.env`
    /// file, and the JSON file named by `flag` or `GEOLITH_CONFIG`.
    ///
    /// # Errors
    ///
    /// Fails when a named file is missing, the `.env` file is wider than mode
    /// 600, the JSON file is not valid JSON of the schema, or a value is
    /// refused.
    pub fn load(flag: Option<&Path>) -> Result<Self> {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        Self::load_with(flag, &process_env, &cwd)
    }

    /// [`load`](Self::load) over any process environment, with `cwd` as the
    /// current directory.
    ///
    /// # Errors
    ///
    /// The errors of [`load`](Self::load).
    fn load_with(flag: Option<&Path>, process: Env<'_>, cwd: &Path) -> Result<Self> {
        let (env_file, dotenv) = load_env_file(process, cwd)?;
        // A value the process sets (even empty) wins over the file's.
        let layered = |name: &str| process(name).or_else(|| dotenv.get(name).cloned());
        let env: Env<'_> = &layered;
        let home = get(env, "HOME").map(PathBuf::from);
        let path = match flag {
            Some(path) => Some(path.to_path_buf()),
            None => get(env, "GEOLITH_CONFIG").map(|path| path_of(home.as_deref(), &path)),
        };
        // A scheduled job runs elsewhere: it needs the absolute path.
        let path = path.map(|path| absolute_in(cwd, path));
        let text = match &path {
            Some(path) if path.is_file() => Some(
                fs::read_to_string(path)
                    .with_context(|| format!("reading the config file {}", path.display()))?,
            ),
            Some(path) => bail!(
                "the config file {} does not exist (--config or GEOLITH_CONFIG); see {EXAMPLE_FILE}",
                path.display()
            ),
            None => None,
        };
        let mut deployment = Self::resolve(path.as_deref(), text.as_deref(), env)?;
        deployment.env_file = env_file;
        Ok(deployment)
    }

    /// The deployment of the file text `text` (read from `source`) and `env`.
    ///
    /// # Errors
    ///
    /// Fails when the text is not valid JSON of the schema or a value is
    /// refused.
    pub fn resolve(source: Option<&Path>, text: Option<&str>, env: Env<'_>) -> Result<Self> {
        let file: FileSettings = match (text, source) {
            (Some(text), Some(path)) => serde_json::from_str(text)
                .with_context(|| format!("parsing the config file {}", path.display()))?,
            (Some(text), None) => serde_json::from_str(text).context("parsing the config file")?,
            (None, _) => FileSettings::default(),
        };
        let home = get(env, "HOME").map(PathBuf::from);
        let home_ref = home.as_deref();
        let path_in = |env_names: &[&str], file: Option<&String>| -> Option<PathBuf> {
            first(env, env_names)
                .or_else(|| file.filter(|text| !text.is_empty()).cloned())
                .map(|text| path_of(home_ref, &text))
        };
        let text_in = |env_names: &[&str], file: Option<&String>| -> Option<String> {
            first(env, env_names).or_else(|| file.filter(|text| !text.is_empty()).cloned())
        };

        let prefix = text_in(&["DATASETS_KEY_PREFIX"], file.storage.prefix.as_ref())
            .map(|text| normalize_prefix(&text))
            .transpose()?;
        let endpoint = text_in(&["DATASETS_R2_ENDPOINT"], file.storage.endpoint.as_ref());
        if let Some(endpoint) = &endpoint
            && !is_http_url(endpoint)
        {
            bail!("storage.endpoint \"{endpoint}\" is not an http(s) URL");
        }
        let bucket = text_in(&["DATASETS_BUCKET"], file.storage.bucket.as_ref());
        if let Some(bucket) = &bucket
            && (bucket.contains('/') || bucket.contains(char::is_whitespace))
        {
            bail!("storage.bucket \"{bucket}\" is not a bucket name");
        }
        let account_id = text_in(
            &["DATASETS_R2_ACCOUNT", "GEOLITH_R2_ACCOUNT"],
            file.storage.account_id.as_ref(),
        );
        if let Some(account) = &account_id
            && (account.contains('.') || account.contains('/'))
        {
            bail!("storage.account_id \"{account}\" is not an account id");
        }
        let storage = StorageSettings {
            endpoint,
            region: text_in(&["DATASETS_R2_REGION"], file.storage.region.as_ref()),
            bucket,
            prefix,
            account_id,
            credentials_file: path_in(
                &["DATASETS_R2_ENV_FILE"],
                file.storage.credentials_file.as_ref(),
            ),
            env_credentials: first(env, &KEY_ID_NAMES)
                .zip(first(env, &SECRET_NAMES))
                .map(|(key_id, secret)| Credentials { key_id, secret }),
        };

        let pointer_url = text_in(&["DATASETS_POINTER_URL"], file.publish.pointer_url.as_ref());
        if let Some(url) = &pointer_url {
            check_template("publish.pointer_url", url)?;
        }
        let page_url = text_in(&["DATASETS_PAGE_URL"], file.publish.page_url.as_ref());
        if let Some(url) = &page_url {
            check_template("publish.page_url", url)?;
        }
        let publish = PublishSettings {
            pointer_url,
            page_url,
            credentials_file: path_in(
                &["DATASETS_SITE_KEY_FILE"],
                file.publish.credentials_file.as_ref(),
            ),
            api_key: get(env, "DATASETS_API_KEY"),
        };

        let chirps_hosts = match get(env, "CHIRPS_HOSTS") {
            Some(hosts) => hosts.split_whitespace().map(str::to_owned).collect(),
            None => file.sources.chirps_hosts.clone().unwrap_or_default(),
        };
        let sources = SourceSettings {
            chirps_hosts,
            cdse_stac: text_in(&["CDSE_STAC"], file.sources.cdse_stac.as_ref()),
            cdse_endpoint: text_in(&["CDSE_S3_ENDPOINT"], file.sources.cdse_endpoint.as_ref()),
            cdse_credentials_file: path_in(
                &["CDSE_ENV_FILE"],
                file.sources.cdse_credentials_file.as_ref(),
            ),
            cdse_env_credentials: get(env, "CDSE_S3_ACCESS_KEY")
                .zip(get(env, "CDSE_S3_SECRET_KEY"))
                .map(|(key_id, secret)| Credentials { key_id, secret }),
            boundaries_url_base: text_in(
                &["BOUNDARIES_URL_BASE"],
                file.sources.boundaries_url_base.as_ref(),
            ),
        };

        let probe_timeout_ms = match get(env, "DATASETS_PROBE_TIMEOUT_MS") {
            Some(text) => Some(text.parse::<u64>().with_context(|| {
                format!("DATASETS_PROBE_TIMEOUT_MS \"{text}\" is not a number of milliseconds")
            })?),
            None => None,
        };
        let min_free_gb = match get(env, "DATASETS_MIN_FREE_GB") {
            Some(text) => Some(text.trim().parse::<u64>().with_context(|| {
                format!("DATASETS_MIN_FREE_GB \"{text}\" is not a number of gigabytes")
            })?),
            None => None,
        };
        let run = RunSettings {
            dataset: get(env, "DATASET"),
            country: get(env, "COUNTRY").map(|cc| cc.trim().to_owned()),
            country_config: get(env, "COUNTRY_CONFIG").map(PathBuf::from),
            boundary_release: first(env, &["BOUNDARY_RELEASE", "OVERTURE_RELEASE"]),
            boundary_tiles_revision: get(env, "BOUNDARY_TILES_REVISION"),
            baseline: get(env, "BASELINE"),
            published_csv: get(env, "PUBLISHED_CSV").map(PathBuf::from),
            areas_dir: get(env, "GEOLITH_AREAS_DIR").map(PathBuf::from),
            crosswalk_csv: env("CROSSWALK_CSV").map(PathBuf::from),
            lgd_dir: get(env, "LGD_DIR").map(PathBuf::from),
            cdse_today: get(env, "CDSE_TODAY"),
            probe_timeout_ms,
            hostname: get(env, "HOSTNAME"),
            min_free_gb,
        };

        let macos_notification = if env("DATASETS_REFRESH_NO_ALERT").is_some() {
            false
        } else {
            match get(env, "DATASETS_MACOS_NOTIFICATION") {
                Some(text) => parse_bool("DATASETS_MACOS_NOTIFICATION", &text)?,
                None => file.alerts.macos_notification.unwrap_or(true),
            }
        };

        Ok(Self {
            config_file: source.map(Path::to_path_buf),
            env_file: None,
            path: get(env, "PATH"),
            data_root: path_in(&["DATA_ROOT"], file.data_root.as_ref()),
            repo: path_in(&["GEOLITH_REPO"], file.repo.as_ref()),
            home,
            storage,
            publish,
            sources,
            macos_notification,
            run,
        })
    }

    /// The key prefix of every dataset key, with a trailing `/`.
    #[must_use]
    pub fn key_root(&self) -> &str {
        self.storage.prefix.as_deref().unwrap_or(DEFAULT_KEY_PREFIX)
    }

    /// The object store, every required part present and every guard passed.
    ///
    /// # Errors
    ///
    /// Fails naming `storage.endpoint` or `storage.bucket` when it is not
    /// set, and when `storage.account_id` is set and the endpoint's host is
    /// not that account's.
    pub fn target(&self) -> Result<Target> {
        let endpoint = self
            .storage
            .endpoint
            .clone()
            .ok_or_else(|| missing("storage.endpoint", "DATASETS_R2_ENDPOINT"))?;
        let bucket = self
            .storage
            .bucket
            .clone()
            .ok_or_else(|| missing("storage.bucket", "DATASETS_BUCKET"))?;
        if let Some(account) = &self.storage.account_id {
            let host = url_host(&endpoint);
            if host.split('.').next() != Some(account.as_str()) {
                bail!("endpoint host {host} is not of storage.account_id");
            }
        }
        Ok(Target {
            endpoint,
            region: self
                .storage
                .region
                .clone()
                .unwrap_or_else(|| DEFAULT_REGION.to_owned()),
            bucket,
            key_root: self.key_root().to_owned(),
        })
    }

    /// The access key pair of the store: the environment first, then the
    /// mode-600 `storage.credentials_file`. Never an argument.
    ///
    /// # Errors
    ///
    /// Fails when neither names a key id and a secret, or the file is
    /// readable by others.
    pub fn storage_credentials(&self) -> Result<Credentials> {
        if let Some(pair) = &self.storage.env_credentials {
            return Ok(pair.clone());
        }
        let Some(path) = &self.storage.credentials_file else {
            bail!(
                "storage credentials are not set: name a storage.credentials_file or set \
                 GEOLITH_STORAGE_ACCESS_KEY_ID and GEOLITH_STORAGE_SECRET_ACCESS_KEY; see \
                 {EXAMPLE_FILE}"
            );
        };
        let values = read_env_file(path)?;
        pair_of(&values).with_context(|| {
            format!(
                "{} holds no access key id and secret (GEOLITH_STORAGE_ACCESS_KEY_ID and \
                 GEOLITH_STORAGE_SECRET_ACCESS_KEY)",
                path.display()
            )
        })
    }

    /// The bearer key of the live check, when one is set: the environment
    /// first, then `DATASETS_API_KEY` of the mode-600 `publish.credentials_file`.
    ///
    /// # Errors
    ///
    /// Fails when the file is set and unreadable, readable by others, or has
    /// no key.
    pub fn publish_key(&self) -> Result<Option<String>> {
        if let Some(key) = &self.publish.api_key {
            return Ok(Some(key.clone()));
        }
        let Some(path) = &self.publish.credentials_file else {
            return Ok(None);
        };
        let values = read_env_file(path)?;
        values
            .get("DATASETS_API_KEY")
            .filter(|key| !key.is_empty())
            .cloned()
            .map(Some)
            .with_context(|| format!("{} holds no DATASETS_API_KEY", path.display()))
    }

    /// The two live-check URLs of a pair and build, each `None` when its
    /// template is not set.
    #[must_use]
    pub fn publish_urls(
        &self,
        dataset: &str,
        country: &str,
        build_id: &str,
    ) -> (Option<String>, Option<String>) {
        let fill = |template: &Option<String>| {
            template
                .as_deref()
                .map(|template| fill_template(template, dataset, country, build_id))
        };
        (
            fill(&self.publish.pointer_url),
            fill(&self.publish.page_url),
        )
    }

    /// The Copernicus S3 key pair: the environment first, then the mode-600
    /// file, when it exists.
    ///
    /// # Errors
    ///
    /// Fails when the file is readable by others.
    pub fn cdse_credentials(&self) -> Result<Option<Credentials>> {
        if let Some(pair) = &self.sources.cdse_env_credentials {
            return Ok(Some(pair.clone()));
        }
        let Some(path) = self.sources.cdse_credentials_file.as_deref() else {
            return Ok(None);
        };
        if !path.is_file() {
            return Ok(None);
        }
        let values = read_env_file(path)?;
        Ok(values
            .get("CDSE_S3_ACCESS_KEY")
            .zip(values.get("CDSE_S3_SECRET_KEY"))
            .filter(|(key_id, secret)| !key_id.is_empty() && !secret.is_empty())
            .map(|(key_id, secret)| Credentials {
                key_id: key_id.clone(),
                secret: secret.clone(),
            }))
    }
}

/// The deployment of this run, set once by [`init`].
static CURRENT: OnceLock<Deployment> = OnceLock::new();

/// Fixes the deployment of this run; the first call wins.
pub fn init(deployment: Deployment) {
    let _ = CURRENT.set(deployment);
}

/// The deployment of this run. Without an [`init`] (a library caller, a unit
/// test) it is the environment alone: no file is read.
#[must_use]
pub fn current() -> &'static Deployment {
    CURRENT.get_or_init(|| Deployment::resolve(None, None, &process_env).unwrap_or_default())
}

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

    /// An environment of `pairs`.
    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
        let map: BTreeMap<String, String> = pairs
            .iter()
            .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
            .collect();
        move |name| map.get(name).cloned()
    }

    const FILE: &str = r#"{
        "data_root": "/srv/data",
        "storage": {
            "endpoint": "http://127.0.0.1:9000",
            "region": "eu-test-1",
            "bucket": "made-up-bucket",
            "prefix": "mirror/ds",
            "credentials_file": "~/keys/store.env"
        },
        "publish": {
            "pointer_url": "https://api.example.test/v1/{dataset}/{country}/current.json",
            "page_url": "https://example.test/data/{country}/{dataset}"
        },
        "sources": {"chirps_hosts": ["https://a.example.test", "https://b.example.test"]},
        "alerts": {"macos_notification": false}
    }"#;

    #[test]
    fn the_file_fills_every_section() {
        let env = env_of(&[("HOME", "/home/op")]);
        let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
        assert_eq!(d.data_root, Some(PathBuf::from("/srv/data")));
        assert_eq!(d.key_root(), "mirror/ds/");
        assert_eq!(
            d.storage.credentials_file,
            Some(PathBuf::from("/home/op/keys/store.env"))
        );
        assert_eq!(d.sources.chirps_hosts.len(), 2);
        assert!(!d.macos_notification);
        let target = d.target().expect("a full storage section");
        assert_eq!(
            target,
            Target {
                endpoint: "http://127.0.0.1:9000".to_owned(),
                region: "eu-test-1".to_owned(),
                bucket: "made-up-bucket".to_owned(),
                key_root: "mirror/ds/".to_owned(),
            }
        );
    }

    #[test]
    fn an_environment_value_beats_the_file() {
        let env = env_of(&[
            ("DATASETS_BUCKET", "env-bucket"),
            ("DATA_ROOT", "/env/root"),
            ("DATASETS_KEY_PREFIX", "env-prefix/"),
        ]);
        let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
        let target = d.target().expect("target");
        assert_eq!(target.bucket, "env-bucket");
        assert_eq!(target.key_root, "env-prefix/");
        assert_eq!(d.data_root, Some(PathBuf::from("/env/root")));
        assert_eq!(target.endpoint, "http://127.0.0.1:9000");
    }

    #[test]
    fn an_empty_deployment_has_neutral_defaults_and_names_what_is_missing() {
        let d = Deployment::resolve(None, None, &env_of(&[])).expect("resolves");
        assert_eq!(d.key_root(), "datasets/");
        assert!(d.macos_notification);
        let error = d.target().unwrap_err().to_string();
        assert!(
            error.contains("storage.endpoint is not set; see geolith.example.json"),
            "{error}"
        );
        let mut half = d.clone();
        half.storage.endpoint = Some("http://127.0.0.1:9000".to_owned());
        let error = half.target().unwrap_err().to_string();
        assert!(
            error.contains("storage.bucket is not set; see geolith.example.json"),
            "{error}"
        );
        assert!(d.storage_credentials().is_err());
        assert_eq!(d.publish_urls("rainfall", "in", "b"), (None, None));
    }

    #[test]
    fn a_bad_value_is_refused_by_name() {
        let refused = |json: &str| {
            format!(
                "{:#}",
                Deployment::resolve(None, Some(json), &env_of(&[])).unwrap_err()
            )
        };
        assert!(refused(r#"{"storage":{"endpoint":"ftp://x"}}"#).contains("storage.endpoint"));
        assert!(refused(r#"{"storage":{"prefix":"a/../b"}}"#).contains("storage.prefix"));
        assert!(refused(r#"{"storage":{"bucket":"a/b"}}"#).contains("storage.bucket"));
        assert!(refused(r#"{"storage":{"account_id":"a.b"}}"#).contains("storage.account_id"));
        assert!(
            refused(r#"{"publish":{"pointer_url":"https://x/{nope}"}}"#)
                .contains("unknown placeholder {nope}")
        );
        assert!(refused(r#"{"publish":{"page_url":"x"}}"#).contains("publish.page_url"));
        assert!(refused(r#"{"storage":{"bucket_name":"x"}}"#).contains("bucket_name"));
        let error = Deployment::resolve(
            None,
            None,
            &env_of(&[("DATASETS_PROBE_TIMEOUT_MS", "soon")]),
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("DATASETS_PROBE_TIMEOUT_MS"), "{error}");
    }

    #[test]
    fn the_account_guard_refuses_a_host_of_another_account() {
        let json = r#"{"storage":{"endpoint":"https://acct1.store.example.test",
            "bucket":"b","account_id":"acct1"}}"#;
        let d = Deployment::resolve(None, Some(json), &env_of(&[])).expect("resolves");
        assert!(d.target().is_ok());
        let other = r#"{"storage":{"endpoint":"https://acct2.store.example.test",
            "bucket":"b","account_id":"acct1"}}"#;
        let d = Deployment::resolve(None, Some(other), &env_of(&[])).expect("resolves");
        let error = d.target().unwrap_err().to_string();
        assert!(error.contains("acct2.store.example.test"), "{error}");
        assert!(error.contains("storage.account_id"), "{error}");
    }

    #[test]
    fn only_the_configured_bucket_passes_the_guard() {
        let d = Deployment::resolve(None, Some(FILE), &env_of(&[])).expect("resolves");
        let target = d.target().expect("target");
        assert!(target.check_bucket("made-up-bucket").is_ok());
        let error = target.check_bucket("other-bucket").unwrap_err().to_string();
        assert!(error.contains("not storage.bucket"), "{error}");
        assert!(target.check_bucket("").is_err());
    }

    #[test]
    fn publish_urls_fill_their_placeholders() {
        let d = Deployment::resolve(None, Some(FILE), &env_of(&[])).expect("resolves");
        let (pointer, page) = d.publish_urls("ndvi", "us", "2026-11-20.20261120T0000Z");
        assert_eq!(
            pointer.as_deref(),
            Some("https://api.example.test/v1/ndvi/us/current.json")
        );
        assert_eq!(page.as_deref(), Some("https://example.test/data/us/ndvi"));
    }

    #[test]
    fn a_prefix_is_normalised_with_a_trailing_slash() {
        assert_eq!(normalize_prefix("a/b").expect("ok"), "a/b/");
        assert_eq!(normalize_prefix("/a/b/").expect("ok"), "a/b/");
        assert!(normalize_prefix("").is_err());
        assert!(normalize_prefix("/").is_err());
        assert!(normalize_prefix("a b").is_err());
        assert!(normalize_prefix("a//b").is_err());
    }

    /// A mode-600 file of `text` in `dir`.
    fn secret_file(dir: &Path, name: &str, text: &str) -> PathBuf {
        let path = dir.join(name);
        fs::write(&path, text).expect("write");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
        }
        path
    }

    #[test]
    fn credentials_come_from_a_600_file_and_a_0644_one_is_refused() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = secret_file(
            dir.path(),
            "store.env",
            "# keys\nexport GEOLITH_STORAGE_ACCESS_KEY_ID=\"kid\"\nGEOLITH_STORAGE_SECRET_ACCESS_KEY=sec\n",
        );
        let json = format!(
            r#"{{"storage":{{"credentials_file":"{}"}}}}"#,
            path.display()
        );
        let d = Deployment::resolve(None, Some(&json), &env_of(&[])).expect("resolves");
        let pair = d.storage_credentials().expect("pair");
        assert_eq!((pair.key_id.as_str(), pair.secret.as_str()), ("kid", "sec"));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("chmod");
            let error = d.storage_credentials().unwrap_err().to_string();
            assert!(error.contains("chmod 600"), "{error}");
        }
    }

    #[test]
    fn an_rclone_remote_file_supplies_the_pair_whatever_the_remote_is_called() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = secret_file(
            dir.path(),
            "rclone.env",
            "RCLONE_CONFIG_MYSTORE_ENDPOINT=https://elsewhere.test\n\
             RCLONE_CONFIG_MYSTORE_ACCESS_KEY_ID=rid\n\
             RCLONE_CONFIG_MYSTORE_SECRET_ACCESS_KEY=rsecret\n",
        );
        let values = read_env_file(&path).expect("pairs");
        let pair = pair_of(&values).expect("pair");
        assert_eq!(
            (pair.key_id.as_str(), pair.secret.as_str()),
            ("rid", "rsecret")
        );
    }

    #[test]
    fn environment_credentials_win_over_the_file() {
        let env = env_of(&[
            ("GEOLITH_STORAGE_ACCESS_KEY_ID", "envid"),
            ("GEOLITH_STORAGE_SECRET_ACCESS_KEY", "envsecret"),
        ]);
        let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
        assert_eq!(d.storage_credentials().expect("pair").key_id, "envid");
    }

    #[test]
    fn the_publish_key_is_read_from_its_file_and_absent_without_one() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = secret_file(dir.path(), "site.env", "OTHER=1\nDATASETS_API_KEY=abc\n");
        let json = format!(
            r#"{{"publish":{{"credentials_file":"{}"}}}}"#,
            path.display()
        );
        let d = Deployment::resolve(None, Some(&json), &env_of(&[])).expect("resolves");
        assert_eq!(d.publish_key().expect("key").as_deref(), Some("abc"));
        let none = Deployment::resolve(None, None, &env_of(&[])).expect("resolves");
        assert_eq!(none.publish_key().expect("no key"), None);
    }

    #[test]
    fn a_named_config_file_must_exist_and_nothing_under_home_is_read_by_default() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let cwd = tempfile::tempdir().expect("an empty working dir");
        let home = dir.path().display().to_string();
        let env = env_of(&[("HOME", &home)]);
        let missing = dir.path().join("nope.json");
        let error = Deployment::load_with(Some(&missing), &env, cwd.path())
            .unwrap_err()
            .to_string();
        assert!(error.contains("nope.json"), "{error}");
        // The old per-user location is never read, even when a file is there.
        let old = dir.path().join(".config").join("geolith");
        fs::create_dir_all(&old).expect("mkdir");
        fs::write(
            old.join("geolith.json"),
            r#"{"storage":{"bucket":"from-home"}}"#,
        )
        .expect("write");
        secret_file(
            &old,
            "cdse.env",
            "CDSE_S3_ACCESS_KEY=a\nCDSE_S3_SECRET_KEY=b\n",
        );
        let d = Deployment::load_with(None, &env, cwd.path()).expect("no file is fine");
        assert!(d.config_file.is_none());
        assert!(d.env_file.is_none());
        assert_eq!(d.storage.bucket, None);
        assert_eq!(d.sources.cdse_credentials_file, None);
        assert_eq!(d.cdse_credentials().expect("no keys"), None);
        let named = dir.path().join("named.json");
        fs::write(&named, r#"{"storage":{"bucket":"from-flag"}}"#).expect("write");
        let d = Deployment::load_with(Some(&named), &env, cwd.path()).expect("flag file");
        assert_eq!(d.storage.bucket.as_deref(), Some("from-flag"));
        assert_eq!(d.config_file.as_deref(), Some(named.as_path()));
        let env_named = named.display().to_string();
        let env = env_of(&[("HOME", &home), ("GEOLITH_CONFIG", &env_named)]);
        let d = Deployment::load_with(None, &env, cwd.path()).expect("env file");
        assert_eq!(d.storage.bucket.as_deref(), Some("from-flag"));
    }

    #[test]
    fn the_env_file_sits_between_the_process_and_the_json() {
        let cwd = tempfile::tempdir().expect("a working dir");
        secret_file(
            cwd.path(),
            ".env",
            "# operator values\nRELEASE_PAT=unrelated\nDATASETS_BUCKET=dotenv-bucket\n\
             DATA_ROOT=/dotenv/root\nexport GEOLITH_STORAGE_ACCESS_KEY_ID=\"dkid\"\n\
             GEOLITH_STORAGE_SECRET_ACCESS_KEY='dsecret'\nDATASETS_API_KEY=dkey\n",
        );
        let json = cwd.path().join("geolith.json");
        fs::write(
            &json,
            r#"{"storage":{"endpoint":"http://127.0.0.1:9000","bucket":"json-bucket"},
                "data_root":"/json/root","repo":"/json/repo"}"#,
        )
        .expect("write");
        let env = env_of(&[("DATA_ROOT", "/process/root")]);
        let d = Deployment::load_with(Some(&json), &env, cwd.path()).expect("resolves");
        assert_eq!(
            d.env_file.as_deref(),
            Some(cwd.path().join(".env").as_path())
        );
        // process > .env > json
        assert_eq!(d.data_root, Some(PathBuf::from("/process/root")));
        assert_eq!(d.storage.bucket.as_deref(), Some("dotenv-bucket"));
        assert_eq!(d.storage.endpoint.as_deref(), Some("http://127.0.0.1:9000"));
        assert_eq!(d.repo, Some(PathBuf::from("/json/repo")));
        let pair = d.storage_credentials().expect("pair from .env");
        assert_eq!(
            (pair.key_id.as_str(), pair.secret.as_str()),
            ("dkid", "dsecret")
        );
        assert_eq!(d.publish_key().expect("key").as_deref(), Some("dkey"));
        // A value the process sets, even empty, is not replaced by the file's.
        let env = env_of(&[("DATASETS_BUCKET", "")]);
        let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
        assert_eq!(d.storage.bucket, None);
    }

    #[test]
    fn geolith_env_file_names_the_file_and_must_exist() {
        let cwd = tempfile::tempdir().expect("a working dir");
        let other = tempfile::tempdir().expect("another dir");
        secret_file(cwd.path(), ".env", "DATASETS_BUCKET=cwd-bucket\n");
        let named = secret_file(other.path(), "ops.env", "DATASETS_BUCKET=named-bucket\n");
        let named_text = named.display().to_string();
        let env = env_of(&[("GEOLITH_ENV_FILE", &named_text)]);
        let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
        assert_eq!(d.storage.bucket.as_deref(), Some("named-bucket"));
        assert_eq!(d.env_file.as_deref(), Some(named.as_path()));
        // `~/` is the process home.
        let home = other.path().display().to_string();
        let env = env_of(&[("HOME", &home), ("GEOLITH_ENV_FILE", "~/ops.env")]);
        let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
        assert_eq!(d.storage.bucket.as_deref(), Some("named-bucket"));
        let gone = other.path().join("gone.env").display().to_string();
        let env = env_of(&[("GEOLITH_ENV_FILE", &gone)]);
        let error = Deployment::load_with(None, &env, cwd.path())
            .unwrap_err()
            .to_string();
        assert!(error.contains("gone.env"), "{error}");
        assert!(error.contains("GEOLITH_ENV_FILE"), "{error}");
    }

    #[cfg(unix)]
    #[test]
    fn an_env_file_wider_than_600_is_refused_and_a_narrower_one_read() {
        use std::os::unix::fs::PermissionsExt as _;
        let cwd = tempfile::tempdir().expect("a working dir");
        let path = secret_file(cwd.path(), ".env", "DATASETS_BUCKET=b\n");
        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).expect("chmod");
        let error = format!(
            "{:#}",
            Deployment::load_with(None, &env_of(&[]), cwd.path()).unwrap_err()
        );
        assert!(error.contains("mode 640"), "{error}");
        assert!(error.contains("chmod 600"), "{error}");
        assert!(!error.contains("DATASETS_BUCKET=b"), "{error}");
        fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).expect("chmod");
        let d = Deployment::load_with(None, &env_of(&[]), cwd.path()).expect("0400 is read");
        assert_eq!(d.storage.bucket.as_deref(), Some("b"));
    }

    #[test]
    fn only_owner_read_and_write_pass_the_mode_check() {
        for (mode, wide) in [
            (0o600, false),
            (0o400, false),
            (0o200, false),
            (0o000, false),
            (0o700, true),
            (0o640, true),
            (0o604, true),
            (0o644, true),
            (0o666, true),
        ] {
            assert_eq!(wider_than_600(mode), wide, "mode {mode:o}");
        }
    }

    #[test]
    fn every_json_field_has_an_environment_name() {
        let env = env_of(&[
            ("DATA_ROOT", "/e/data"),
            ("GEOLITH_REPO", "/e/repo"),
            ("DATASETS_R2_ENDPOINT", "https://acct9.store.example.test"),
            ("DATASETS_R2_REGION", "auto"),
            ("DATASETS_BUCKET", "e-bucket"),
            ("DATASETS_KEY_PREFIX", "e/p"),
            ("DATASETS_R2_ACCOUNT", "acct9"),
            ("DATASETS_R2_ENV_FILE", "/e/store.env"),
            (
                "DATASETS_POINTER_URL",
                "https://api.e.test/{dataset}/{country}",
            ),
            ("DATASETS_PAGE_URL", "https://e.test/{country}/{dataset}"),
            ("DATASETS_SITE_KEY_FILE", "/e/site.env"),
            ("CHIRPS_HOSTS", "https://c1.e.test https://c2.e.test"),
            ("CDSE_STAC", "https://stac.e.test"),
            ("CDSE_S3_ENDPOINT", "https://s3.e.test"),
            ("CDSE_ENV_FILE", "/e/cdse.env"),
            ("BOUNDARIES_URL_BASE", "https://b.e.test"),
            ("DATASETS_MACOS_NOTIFICATION", "false"),
        ]);
        let d = Deployment::resolve(None, None, &env).expect("resolves");
        assert_eq!(d.data_root, Some(PathBuf::from("/e/data")));
        assert_eq!(d.repo, Some(PathBuf::from("/e/repo")));
        assert_eq!(
            d.target().expect("target"),
            Target {
                endpoint: "https://acct9.store.example.test".to_owned(),
                region: "auto".to_owned(),
                bucket: "e-bucket".to_owned(),
                key_root: "e/p/".to_owned(),
            }
        );
        assert_eq!(d.storage.account_id.as_deref(), Some("acct9"));
        assert_eq!(
            d.storage.credentials_file,
            Some(PathBuf::from("/e/store.env"))
        );
        assert_eq!(
            d.publish_urls("rainfall", "in", "x"),
            (
                Some("https://api.e.test/rainfall/in".to_owned()),
                Some("https://e.test/in/rainfall".to_owned())
            )
        );
        assert_eq!(
            d.publish.credentials_file,
            Some(PathBuf::from("/e/site.env"))
        );
        assert_eq!(
            d.sources.chirps_hosts,
            vec!["https://c1.e.test", "https://c2.e.test"]
        );
        assert_eq!(d.sources.cdse_stac.as_deref(), Some("https://stac.e.test"));
        assert_eq!(
            d.sources.cdse_endpoint.as_deref(),
            Some("https://s3.e.test")
        );
        assert_eq!(
            d.sources.cdse_credentials_file,
            Some(PathBuf::from("/e/cdse.env"))
        );
        assert_eq!(
            d.sources.boundaries_url_base.as_deref(),
            Some("https://b.e.test")
        );
        assert!(!d.macos_notification);
    }

    #[test]
    fn the_notification_switch_reads_its_env_name_and_no_alert_wins() {
        let on = r#"{"alerts":{"macos_notification":true}}"#;
        let resolve = |pairs: &[(&str, &str)]| Deployment::resolve(None, Some(on), &env_of(pairs));
        assert!(resolve(&[]).expect("file").macos_notification);
        assert!(
            !resolve(&[("DATASETS_MACOS_NOTIFICATION", "No")])
                .expect("env")
                .macos_notification
        );
        let off = r#"{"alerts":{"macos_notification":false}}"#;
        let d = Deployment::resolve(
            None,
            Some(off),
            &env_of(&[("DATASETS_MACOS_NOTIFICATION", "1")]),
        )
        .expect("env over file");
        assert!(d.macos_notification);
        assert!(
            !resolve(&[
                ("DATASETS_MACOS_NOTIFICATION", "true"),
                ("DATASETS_REFRESH_NO_ALERT", "")
            ])
            .expect("silenced")
            .macos_notification
        );
        let error = resolve(&[("DATASETS_MACOS_NOTIFICATION", "maybe")])
            .unwrap_err()
            .to_string();
        assert!(error.contains("DATASETS_MACOS_NOTIFICATION"), "{error}");
    }

    #[test]
    fn no_other_module_reads_the_environment() {
        fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
            for entry in fs::read_dir(dir).expect("read_dir") {
                let path = entry.expect("entry").path();
                if path.is_dir() {
                    walk(&path, out);
                } else if path.extension().is_some_and(|ext| ext == "rs") {
                    out.push(path);
                }
            }
        }
        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let mut files = Vec::new();
        walk(&root, &mut files);
        assert!(files.len() > 30, "found only {} files", files.len());
        let needle = ["env", "::var"].concat();
        let offenders: Vec<String> = files
            .iter()
            .filter(|path| path.file_name().is_some_and(|name| name != "settings.rs"))
            .filter(|path| {
                fs::read_to_string(path)
                    .expect("read")
                    .contains(needle.as_str())
            })
            .map(|path| path.display().to_string())
            .collect();
        assert!(
            offenders.is_empty(),
            "read the environment through dataset::settings: {offenders:?}"
        );
    }
}