rigtop-core 0.30.0

Data collection core of rigtop: CPU, memory, GPU (NVML), sensors, storage health (SMART, btrfs, mdadm), network and processes as serializable snapshots
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
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! User configuration (`config.toml`).
//!
//! The file lives at `<config dir>/rigtop/config.toml`
//! (`~/.config/rigtop/config.toml` on Linux, `%APPDATA%\rigtop\config.toml`
//! on Windows). A missing file means "all defaults".
//!
//! ```toml
//! [sensors]
//! # Names for sensor channels, keyed by the stable channel key shown in the UI.
//! labels = { "nct6686:nct6683.2592/fan1" = "CPU fan", "nct6686:nct6683.2592/temp1" = "VRM" }
//! # Channels to hide (e.g. unconnected thermistors reading -40 °C).
//! hidden = ["nct6686:nct6683.2592/temp4"]
//!
//! [smart]
//! # Directory with smartctl JSON files written by the root timer.
//! dir = "/var/lib/rigtop/smart"
//!
//! [btrfs]
//! # Directory with btrfs scrub status files copied by the root timer.
//! scrub_dir = "/var/lib/rigtop/btrfs"
//!
//! [alerts]
//! # When readings become alerts (0 turns one off).
//! filesystem_warning_percent = 90
//! filesystem_critical_percent = 97
//! filesystem_full_warning_hours = 24  # full this soon at the last half hour's rate
//! cpu_warning_celsius = 96    # hottest CPU reading
//! gpu_warning_celsius = 85
//! drive_warning_celsius = 70  # SMART or NVMe sensor
//! memory_warning_percent = 90 # memory in use (without cache)
//! gpu_memory_warning_percent = 0  # VRAM; off: frameworks reserve most of it
//! memory_pressure_warning_percent = 10  # time tasks waited for memory (Linux)
//! io_pressure_warning_percent = 30      # time all tasks waited for I/O (Linux)
//! ignored_units = []          # failed systemd units not to warn about
//!
//! [notifications]
//! # rigtop-gui: desktop notifications for new alerts ("critical", "warning" or "off").
//! level = "critical"
//!
//! [updates]
//! # Look for new releases on github.com (at startup and every interval:
//! # "30m", "6h", "1d", "1h30m", ...; at least a minute).
//! check = true
//! interval = "1h"
//! notify = true   # rigtop-gui: desktop notification for a new release
//!
//! [watch]
//! # `rigtop --watch`: run a command when an alert appears or clears on any
//! # host, with RIGTOP_HOST, RIGTOP_SEVERITY, RIGTOP_CHANGE, RIGTOP_ALERT and
//! # RIGTOP_MESSAGE in its environment.
//! command = 'curl -s -d "$RIGTOP_MESSAGE" https://ntfy.sh/my-topic'
//! level = "critical"     # or "warning" ("off" runs nothing)
//! cleared = true         # also when an alert goes away
//! interval = "10s"       # time between samples
//! offline_after = "3m"   # a host unreachable this long is a critical alert
//! processes = ["train.py"]  # also tell when these exit, on any host
//!
//! [lhm]
//! # Windows: LibreHardwareMonitor's web server ("" to disable).
//! url = "http://127.0.0.1:8085/data.json"
//!
//! [tui]
//! # Boxes of the host view not to draw (also toggled with `v`).
//! hidden_panels = ["gpu"]
//! show_widgets = true   # the widget column (`w`)
//!
//! [overview]
//! # Sections of each host card, most important first.
//! sections = ["cpu", "gpu", "memory", "processes", "network", "storage"]
//! include_local = true
//! processes = 10
//! alerts_first = false  # true: hosts that need attention first
//!
//! [[hosts]]
//! name = "zefat"
//!
//! [[hosts]]
//! name = "nas"
//! ssh = "admin@nas.local"
//! command = "/usr/local/bin/rigtop --agent"
//! sections = ["storage", "cpu", "network"]
//! [hosts.alerts]       # this host's thresholds, over those of [alerts]
//! filesystem_warning_percent = 95
//!
//! [[widgets]]
//! name = "Clock"
//! builtin = "clock"
//!
//! [[widgets]]
//! name = "Rates"
//! command = "~/bin/rates.sh"   # prints text or JSON rows, see `widget`
//! interval_secs = 60
//!
//! ```
//!
//! Labels are applied by front-ends rather than by data sources, so that a
//! client monitoring remote hosts uses its own local configuration.

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};

use serde::{Deserialize, Serialize};

use crate::snapshot::{Fan, Temperature};

/// What a new configuration file starts with: every setting, commented out
/// at its default, with short explanations.
pub const CONFIG_TEMPLATE: &str = include_str!("config_template.toml");

/// Default location of the SMART result files.
pub const DEFAULT_SMART_DIR: &str = "/var/lib/rigtop/smart";
/// Default location of the copied btrfs scrub status files.
pub const DEFAULT_SCRUB_DIR: &str = "/var/lib/rigtop/btrfs";
/// Default address of LibreHardwareMonitor's web server (Windows sensors).
pub const DEFAULT_LHM_URL: &str = "http://127.0.0.1:8085/data.json";

/// Default address of Network UPS Tools' upsd.
pub const DEFAULT_UPS_ADDRESS: &str = "127.0.0.1:3493";

/// Errors while loading or saving the configuration.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// The file could not be read or written.
    #[error("cannot access {path}: {source}")]
    Io {
        /// File that failed.
        path: PathBuf,
        /// Underlying error.
        source: io::Error,
    },
    /// The file is not valid TOML or has unexpected fields.
    #[error("invalid config {path}: {source}")]
    Parse {
        /// File that failed.
        path: PathBuf,
        /// Underlying error.
        source: toml::de::Error,
    },
    /// The configuration could not be serialized.
    #[error("cannot serialize config: {0}")]
    Serialize(#[from] toml::ser::Error),
    /// A host's `alerts` table has a key `[alerts]` does not, or a value of
    /// the wrong type.
    #[error("invalid alerts of host {host} in {path}: {source}")]
    HostAlerts {
        /// File that failed.
        path: PathBuf,
        /// Name of the host.
        host: String,
        /// Underlying error (boxed: it would make every result large).
        source: Box<toml::de::Error>,
    },
    /// The file is not valid TOML, so it cannot be edited in place.
    #[error("cannot edit {path}: {source}")]
    Edit {
        /// File that failed.
        path: PathBuf,
        /// Underlying error.
        source: toml_edit::TomlError,
    },
}

/// Top-level configuration.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    /// Sensor naming and visibility.
    pub sensors: SensorConfig,
    /// SMART result files.
    pub smart: SmartConfig,
    /// btrfs scrub status files.
    pub btrfs: BtrfsConfig,
    /// LibreHardwareMonitor's web server, the source of temperatures, fans
    /// and CPU power on Windows.
    pub lhm: LhmConfig,
    /// Network UPS Tools' upsd, the source of UPS readings.
    pub ups: UpsConfig,
    /// The multi-host overview.
    pub overview: OverviewConfig,
    /// The terminal UI.
    pub tui: TuiConfig,
    /// GPU panels and overview cards.
    pub gpu: GpuConfig,
    /// The network panel.
    pub network: NetworkConfig,
    /// When a reading becomes an alert.
    pub alerts: AlertsConfig,
    /// Desktop notifications for new alerts (GUI).
    pub notifications: NotificationsConfig,
    /// Looking for new rigtop releases.
    pub updates: UpdatesConfig,
    /// Alerts sent by `rigtop --watch`.
    pub watch: WatchConfig,
    /// Remote hosts monitored over SSH (`[[hosts]]` tables).
    pub hosts: Vec<HostConfig>,
    /// Extra panels beside the monitor (`[[widgets]]` tables).
    pub widgets: Vec<WidgetConfig>,
}

/// Widgets drawn by rigtop itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BuiltinWidget {
    /// The date and a large clock.
    Clock,
}

/// One widget: a built-in one, or a command whose output is shown (see
/// [`crate::widget`] for the output format).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WidgetConfig {
    /// Title of the widget.
    pub name: String,
    /// Shell command printing the content.
    pub command: Option<String>,
    /// Or a built-in widget.
    pub builtin: Option<BuiltinWidget>,
    /// Seconds between runs of the command.
    pub interval_secs: u64,
    /// Seconds after which a run is killed.
    pub timeout_secs: u64,
}

impl Default for WidgetConfig {
    fn default() -> Self {
        Self {
            name: String::new(),
            command: None,
            builtin: None,
            interval_secs: 5,
            timeout_secs: 10,
        }
    }
}

/// A block of information on a host card in the overview.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OverviewSection {
    Cpu,
    Gpu,
    Memory,
    Processes,
    Network,
    Storage,
}

impl OverviewSection {
    /// All sections in the default priority order.
    pub const ALL: [OverviewSection; 6] = [
        OverviewSection::Cpu,
        OverviewSection::Gpu,
        OverviewSection::Memory,
        OverviewSection::Processes,
        OverviewSection::Network,
        OverviewSection::Storage,
    ];

    /// Name shown in menus.
    pub fn label(self) -> &'static str {
        match self {
            OverviewSection::Cpu => "CPU",
            OverviewSection::Gpu => "GPU",
            OverviewSection::Memory => "Memory",
            OverviewSection::Processes => "Processes",
            OverviewSection::Network => "Network",
            OverviewSection::Storage => "Storage",
        }
    }
}

/// Settings of the terminal UI.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TuiConfig {
    /// Boxes of the host view not to draw (`v` toggles them and saves the
    /// choice here). The CPU box is always drawn.
    pub hidden_panels: Vec<OverviewSection>,
    /// Whether the widget column is shown (`w`, or `v` then `w`).
    pub show_widgets: bool,
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            hidden_panels: Vec::new(),
            show_widgets: true,
        }
    }
}

/// Settings of the multi-host overview.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct OverviewConfig {
    /// Sections shown on each host card, most important first. Sections are
    /// dropped from the end when a card is too small; leaving one out of
    /// the list hides it.
    pub sections: Vec<OverviewSection>,
    /// Whether this machine also gets a card (it always has its own tab).
    pub include_local: bool,
    /// Processes listed per card. Hosts not shown in detail only send this
    /// many, to keep SSH traffic small.
    pub processes: usize,
    /// Put hosts that need attention first (unreachable or with critical
    /// alerts, then warnings); the others keep their order. Off by default,
    /// so that cards stay where they are.
    pub alerts_first: bool,
}

impl Default for OverviewConfig {
    fn default() -> Self {
        Self {
            sections: OverviewSection::ALL.to_vec(),
            include_local: true,
            processes: 10,
            alerts_first: false,
        }
    }
}

/// A remote host to monitor.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostConfig {
    /// Name shown in tabs and on the overview card.
    pub name: String,
    /// SSH destination (a `~/.ssh/config` host, `user@host`, ...);
    /// defaults to `name`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssh: Option<String>,
    /// Command that starts the agent; defaults to `rigtop --agent`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Overview sections for this host, overriding `[overview] sections`
    /// (e.g. storage first for a file server).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sections: Option<Vec<OverviewSection>>,
    /// Alert thresholds of this host: the keys given replace those of
    /// `[alerts]` (e.g. a higher CPU temperature for a laptop). Checked when
    /// the file is loaded; see [`Config::alerts_for`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alerts: Option<toml::Table>,
}

impl HostConfig {
    /// A host given only by its SSH destination (e.g. on the command line).
    pub fn from_destination(destination: &str) -> Self {
        Self {
            name: destination.to_owned(),
            ssh: None,
            command: None,
            sections: None,
            alerts: None,
        }
    }

    /// The SSH destination.
    pub fn destination(&self) -> &str {
        self.ssh.as_deref().unwrap_or(&self.name)
    }
}

/// Sensor naming and visibility.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SensorConfig {
    /// User-defined names keyed by channel key (`"<chip key>/fan1"`, `"<chip key>/temp3"`).
    /// A `BTreeMap` keeps the saved file in a stable order.
    pub labels: BTreeMap<String, String>,
    /// Channel keys to hide.
    pub hidden: Vec<String>,
}

/// Where to find SMART results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SmartConfig {
    /// Directory containing one smartctl JSON file per device.
    pub dir: PathBuf,
}

impl Default for SmartConfig {
    fn default() -> Self {
        Self {
            dir: PathBuf::from(DEFAULT_SMART_DIR),
        }
    }
}

/// Which new alerts the GUI announces with a desktop notification.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyLevel {
    /// No notifications.
    Off,
    /// Warnings and critical alerts.
    Warning,
    /// Critical alerts only (data at risk).
    #[default]
    Critical,
}

/// Thresholds that turn readings into alerts (overview cards, status dots
/// and notifications). 0 turns an alert off. Applied by the front-end, so
/// remote hosts are judged by the viewer's settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AlertsConfig {
    /// Filesystem usage (%) for a warning.
    pub filesystem_warning_percent: f64,
    /// Filesystem usage (%) for a critical alert.
    pub filesystem_critical_percent: f64,
    /// A filesystem that will be full within this many hours, at the growth
    /// of the last half hour, is a warning.
    pub filesystem_full_warning_hours: f64,
    /// Hottest CPU reading (°C) for a warning. Desktop Ryzen CPUs run up to
    /// 95 °C under full load by design.
    pub cpu_warning_celsius: f32,
    /// GPU temperature (°C) for a warning.
    pub gpu_warning_celsius: f32,
    /// Drive temperature (°C, from SMART or the NVMe sensor) for a warning.
    pub drive_warning_celsius: f32,
    /// Memory in use (%, page cache not counted) for a warning.
    pub memory_warning_percent: f64,
    /// GPU memory in use (%) for a warning. Off by default: PyTorch, JAX
    /// and TensorFlow reserve most of the VRAM up front, so a busy GPU
    /// always looks full.
    pub gpu_memory_warning_percent: f64,
    /// Share of the last minute (%) in which some task waited for memory
    /// (Linux pressure stall information) for a warning: reclaim or swap
    /// is slowing work down.
    pub memory_pressure_warning_percent: f64,
    /// Share of the last minute (%) in which every runnable task waited for
    /// I/O for a warning. Not "some" task: that is near 100% during any
    /// large copy.
    pub io_pressure_warning_percent: f64,
    /// systemd units whose failure is not worth a warning (e.g. a
    /// `systemd-networkd-wait-online.service` that fails on every boot).
    pub ignored_units: Vec<String>,
}

impl Default for AlertsConfig {
    fn default() -> Self {
        Self {
            filesystem_warning_percent: 90.0,
            filesystem_critical_percent: 97.0,
            filesystem_full_warning_hours: 24.0,
            cpu_warning_celsius: 96.0,
            gpu_warning_celsius: 85.0,
            drive_warning_celsius: 70.0,
            memory_warning_percent: 90.0,
            gpu_memory_warning_percent: 0.0,
            memory_pressure_warning_percent: 10.0,
            io_pressure_warning_percent: 30.0,
            ignored_units: Vec::new(),
        }
    }
}

/// The network panel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NetworkConfig {
    /// Show the addresses of the interface shown (the TUI's `i` and the
    /// GUI's "IP" switch them for the moment).
    pub show_addresses: bool,
    /// Also look up each host's public IPv4 address with an outside
    /// service (`public_ip_url`); off by default, as it contacts a third
    /// party.
    pub public_ip: bool,
    /// Service answering with the caller's address as plain text.
    pub public_ip_url: String,
    /// Time between lookups, written like "30m" or "1h".
    #[serde(with = "duration_text")]
    pub public_ip_interval: Duration,
}

/// Default service for [`NetworkConfig::public_ip_url`].
pub const DEFAULT_PUBLIC_IP_URL: &str = "https://api.ipify.org";

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            show_addresses: true,
            public_ip: false,
            public_ip_url: DEFAULT_PUBLIC_IP_URL.to_owned(),
            public_ip_interval: Duration::from_secs(30 * 60),
        }
    }
}

impl NetworkConfig {
    /// The lookup to ask every host's data source for, if any.
    pub fn public_ip_lookup(&self) -> Option<crate::public_ip::PublicIpLookup> {
        (self.public_ip && !self.public_ip_url.is_empty()).then(|| {
            crate::public_ip::PublicIpLookup {
                url: self.public_ip_url.clone(),
                interval: self.public_ip_interval,
            }
        })
    }
}

/// GPU panels and overview cards.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct GpuConfig {
    /// How an integrated GPU is shown on a host that also has a discrete
    /// one.
    pub integrated: IntegratedGpu,
}

/// How an integrated GPU is shown next to a discrete GPU. A host with only
/// an integrated GPU (a laptop, say) always shows it in full.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IntegratedGpu {
    /// One line in the host view, none on overview cards.
    #[default]
    Compact,
    /// Not shown at all (its alerts still are).
    Hide,
    /// Like a discrete GPU.
    Full,
}

/// Desktop notification settings.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NotificationsConfig {
    pub level: NotifyLevel,
}

/// Looking for new rigtop releases on GitHub.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct UpdatesConfig {
    /// Look for new releases (contacts github.com); `false` never does.
    pub check: bool,
    /// Time between checks (also checked at startup), written like "1h",
    /// "30m", "1d" or "1h30m".
    #[serde(with = "duration_text")]
    pub interval: Duration,
    /// Announce a new release with a desktop notification (GUI), besides
    /// the note in the title.
    pub notify: bool,
}

impl Default for UpdatesConfig {
    fn default() -> Self {
        Self {
            check: true,
            interval: Duration::from_secs(3600),
            notify: true,
        }
    }
}

impl UpdatesConfig {
    /// Time between checks; at least a minute, whatever the file says.
    pub fn check_interval(&self) -> Duration {
        self.interval.max(Duration::from_secs(60))
    }
}

/// `rigtop --watch`: watching every host without a screen and running a
/// command when alerts appear or clear.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WatchConfig {
    /// Shell command run for each change ("" runs nothing; changes are
    /// still printed and kept in the alert history).
    pub command: String,
    /// The least severe alerts the command runs for.
    pub level: NotifyLevel,
    /// Also run the command when an alert clears.
    pub cleared: bool,
    /// Time between samples of each host.
    #[serde(with = "duration_text")]
    pub interval: Duration,
    /// A host that sends nothing this long becomes a critical alert.
    #[serde(with = "duration_text")]
    pub offline_after: Duration,
    /// Time a run of the command may take before it is killed.
    #[serde(with = "duration_text")]
    pub timeout: Duration,
    /// Processes to announce the exit of, on every host, by name or by a
    /// file in their command line (`"train.py"`, `"rsync"`); see
    /// [`crate::view::process_matches`].
    pub processes: Vec<String>,
}

impl Default for WatchConfig {
    fn default() -> Self {
        Self {
            command: String::new(),
            level: NotifyLevel::Critical,
            cleared: true,
            interval: Duration::from_secs(10),
            offline_after: Duration::from_secs(180),
            timeout: Duration::from_secs(30),
            processes: Vec::new(),
        }
    }
}

/// Durations written as text: a number and a unit (`s`, `m`, `h` or `d`),
/// possibly several, as in "1h30m".
mod duration_text {
    use std::time::Duration;

    use serde::de::Error;
    use serde::{Deserialize, Deserializer, Serializer};

    const UNITS: [(char, u64); 4] = [('d', 86_400), ('h', 3600), ('m', 60), ('s', 1)];

    pub fn serialize<S: Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&format(*duration))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
        let text = String::deserialize(deserializer)?;
        parse(&text).ok_or_else(|| {
            D::Error::custom(format!(
                "invalid duration {text:?}: write a number and s, m, h or d, \
                 e.g. \"30m\", \"6h\" or \"1h30m\""
            ))
        })
    }

    /// "1h30m" -> 90 minutes; `None` for anything else.
    pub fn parse(text: &str) -> Option<Duration> {
        let text: String = text.chars().filter(|c| !c.is_whitespace()).collect();
        if text.is_empty() {
            return None;
        }
        let mut total = 0u64;
        let mut number = String::new();
        for c in text.chars() {
            if c.is_ascii_digit() {
                number.push(c);
                continue;
            }
            let (_, secs) = UNITS
                .iter()
                .find(|(unit, _)| *unit == c.to_ascii_lowercase())?;
            let value: u64 = number.parse().ok()?;
            total = total.checked_add(value.checked_mul(*secs)?)?;
            number.clear();
        }
        // A number without a unit at the end is ambiguous.
        number.is_empty().then(|| Duration::from_secs(total))
    }

    /// 90 minutes -> "1h30m"; whole seconds only.
    pub fn format(duration: Duration) -> String {
        let mut secs = duration.as_secs();
        if secs == 0 {
            return "0s".to_owned();
        }
        let mut text = String::new();
        for (unit, size) in UNITS {
            if secs >= size {
                text.push_str(&format!("{}{unit}", secs / size));
                secs %= size;
            }
        }
        text
    }
}

/// Where to read Windows sensors from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LhmConfig {
    /// `data.json` of LibreHardwareMonitor's "Remote Web Server" (plain
    /// HTTP without authentication); empty to disable.
    pub url: String,
}

impl Default for LhmConfig {
    fn default() -> Self {
        Self {
            url: DEFAULT_LHM_URL.to_owned(),
        }
    }
}

/// Where to read UPSes from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct UpsConfig {
    /// Network UPS Tools' upsd (`host:port`, the port 3493 if left out);
    /// empty to disable. Nothing is shown when nothing listens there.
    pub address: String,
}

impl Default for UpsConfig {
    fn default() -> Self {
        Self {
            address: DEFAULT_UPS_ADDRESS.to_owned(),
        }
    }
}

/// Where to find btrfs scrub results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BtrfsConfig {
    /// Directory with world-readable copies of `scrub.status.<fsid>`.
    pub scrub_dir: PathBuf,
}

impl Default for BtrfsConfig {
    fn default() -> Self {
        Self {
            scrub_dir: PathBuf::from(DEFAULT_SCRUB_DIR),
        }
    }
}

/// Creates the configuration file at `path` from [`CONFIG_TEMPLATE`] if
/// there is none yet (with its directory). Returns true when it did.
pub fn create_if_missing(path: &Path) -> io::Result<bool> {
    if path.exists() {
        return Ok(false);
    }
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir)?;
    }
    fs::write(path, CONFIG_TEMPLATE)?;
    Ok(true)
}

impl Config {
    /// Default path of the configuration file, if the platform has a config directory.
    pub fn default_path() -> Option<PathBuf> {
        dirs::config_dir().map(|dir| dir.join("rigtop").join("config.toml"))
    }

    /// Loads the configuration from `path`. A missing file yields the defaults.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
            Err(source) => {
                return Err(ConfigError::Io {
                    path: path.to_owned(),
                    source,
                });
            }
        };
        let config: Self = toml::from_str(&text).map_err(|source| ConfigError::Parse {
            path: path.to_owned(),
            source,
        })?;
        // A typo in a host's thresholds fails now, like one in [alerts].
        for host in &config.hosts {
            config
                .alerts_for(host)
                .map_err(|source| ConfigError::HostAlerts {
                    path: path.to_owned(),
                    host: host.name.clone(),
                    source: Box::new(source),
                })?;
        }
        Ok(config)
    }

    /// The alert thresholds of `host`: `[alerts]` with the keys of the
    /// host's own `alerts` table in place of its own.
    pub fn alerts_for(&self, host: &HostConfig) -> Result<AlertsConfig, toml::de::Error> {
        let Some(overrides) = &host.alerts else {
            return Ok(self.alerts.clone());
        };
        // Serializing plain numbers and strings cannot fail.
        let mut merged = toml::Table::try_from(&self.alerts).unwrap_or_default();
        merged.extend(overrides.clone());
        merged.try_into()
    }

    /// Loads from [`Config::default_path`], or returns the defaults when the
    /// platform has no config directory.
    pub fn load_default() -> Result<Self, ConfigError> {
        match Self::default_path() {
            Some(path) => Self::load(&path),
            None => Ok(Self::default()),
        }
    }

    /// Writes the configuration to `path`, creating parent directories.
    ///
    /// The file is written to a temporary sibling and renamed into place, so
    /// a crash never leaves a truncated config behind.
    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
        let text = toml::to_string_pretty(self)?;
        let io_err = |source| ConfigError::Io {
            path: path.to_owned(),
            source,
        };
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(io_err)?;
        }
        let tmp = path.with_extension("toml.tmp");
        fs::write(&tmp, text).map_err(io_err)?;
        fs::rename(&tmp, path).map_err(io_err)
    }

    /// Replaces the `[[hosts]]` of the configuration file at `path` with
    /// `hosts`, keeping everything else in the file (other settings,
    /// comments, formatting) untouched. Creates the file if needed.
    ///
    /// Used by the GUI's host editor. The edited file is checked to load as
    /// a valid configuration before it replaces the old one.
    pub fn save_hosts(path: &Path, hosts: &[HostConfig]) -> Result<(), ConfigError> {
        edit_file(path, |document| {
            if hosts.is_empty() {
                document.remove("hosts");
                return Ok(());
            }
            let mut tables = toml_edit::ArrayOfTables::new();
            for host in hosts {
                let mut table = toml_edit::Table::new();
                table["name"] = toml_edit::value(host.name.as_str());
                if let Some(ssh) = &host.ssh {
                    table["ssh"] = toml_edit::value(ssh.as_str());
                }
                if let Some(command) = &host.command {
                    table["command"] = toml_edit::value(command.as_str());
                }
                if let Some(sections) = &host.sections {
                    let mut array = toml_edit::Array::new();
                    for section in sections {
                        // Serialized names match the serde representation.
                        let name = toml::Value::try_from(section)?;
                        if let Some(name) = name.as_str() {
                            array.push(name);
                        }
                    }
                    table["sections"] = toml_edit::value(array);
                }
                if let Some(alerts) = &host.alerts {
                    // Written as [hosts.alerts] under the host's keys.
                    let mut sub = toml_edit::Table::new();
                    for (key, value) in alerts {
                        if let Ok(value) = value.to_string().parse::<toml_edit::Value>() {
                            sub[key.as_str()] = toml_edit::value(value);
                        }
                    }
                    table["alerts"] = toml_edit::Item::Table(sub);
                }
                tables.push(table);
            }
            document["hosts"] = toml_edit::Item::ArrayOfTables(tables);
            Ok(())
        })
    }

    /// Replaces the sensor names and hidden sensors (`[sensors]`) of the
    /// configuration file at `path`, keeping the rest of the file as it is,
    /// like [`Config::save_hosts`]. Names stay an inline table if they were
    /// one.
    ///
    /// Used by the GUI's sensor editor.
    /// Writes `[tui]` (keys left at their defaults are removed), leaving
    /// the rest of the file as it is.
    pub fn save_tui(path: &Path, tui: &TuiConfig) -> Result<(), ConfigError> {
        edit_file(path, |document| {
            if !document.contains_key("tui") {
                if *tui == TuiConfig::default() {
                    return Ok(());
                }
                document["tui"] = toml_edit::table();
            }
            let Some(table) = document["tui"].as_table_like_mut() else {
                // Not a table: loading would have failed already.
                return Ok(());
            };
            if tui.hidden_panels.is_empty() {
                table.remove("hidden_panels");
            } else {
                let names: toml_edit::Array = tui
                    .hidden_panels
                    .iter()
                    .filter_map(|section| {
                        serde_json::to_value(section)
                            .ok()
                            .and_then(|v| v.as_str().map(str::to_owned))
                    })
                    .collect();
                table.insert("hidden_panels", toml_edit::value(names));
            }
            if tui.show_widgets {
                table.remove("show_widgets");
            } else {
                table.insert("show_widgets", toml_edit::value(false));
            }
            Ok(())
        })
    }

    pub fn save_sensors(path: &Path, sensors: &SensorConfig) -> Result<(), ConfigError> {
        edit_file(path, |document| {
            if !document.contains_key("sensors") {
                if sensors.labels.is_empty() && sensors.hidden.is_empty() {
                    return Ok(());
                }
                document["sensors"] = toml_edit::table();
            }
            let Some(table) = document["sensors"].as_table_like_mut() else {
                // Not a table: loading would have failed already.
                return Ok(());
            };
            if sensors.hidden.is_empty() {
                table.remove("hidden");
            } else {
                let hidden: toml_edit::Array = sensors.hidden.iter().map(String::as_str).collect();
                table.insert("hidden", toml_edit::value(hidden));
            }
            let inline = table.get("labels").is_some_and(|l| l.is_inline_table());
            if sensors.labels.is_empty() {
                table.remove("labels");
            } else if inline {
                let labels: toml_edit::InlineTable = sensors
                    .labels
                    .iter()
                    .map(|(k, v)| (k.as_str(), toml_edit::Value::from(v.as_str())))
                    .collect();
                table.insert("labels", toml_edit::value(labels));
            } else {
                let mut labels = toml_edit::Table::new();
                for (key, name) in &sensors.labels {
                    labels[key.as_str()] = toml_edit::value(name.as_str());
                }
                table.insert("labels", toml_edit::Item::Table(labels));
            }
            if table.is_empty() {
                document.remove("sensors");
            }
            Ok(())
        })
    }

    /// Display name of a fan: the user-defined label, or the driver/generic label.
    pub fn fan_label<'a>(&'a self, fan: &'a Fan) -> &'a str {
        self.label_for(&fan.key).unwrap_or(&fan.label)
    }

    /// Display name of a temperature channel.
    pub fn temperature_label<'a>(&'a self, temperature: &'a Temperature) -> &'a str {
        self.label_for(&temperature.key)
            .unwrap_or(&temperature.label)
    }

    /// User-defined label for a channel key, if any.
    pub fn label_for(&self, key: &str) -> Option<&str> {
        self.sensors.labels.get(key).map(String::as_str)
    }

    /// Sets (or, with an empty name, removes) the label of a channel.
    pub fn set_label(&mut self, key: &str, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.sensors.labels.remove(key);
        } else {
            self.sensors.labels.insert(key.to_owned(), name.to_owned());
        }
    }

    /// Whether the user chose to hide a channel.
    pub fn is_hidden(&self, key: &str) -> bool {
        self.sensors.hidden.iter().any(|k| k == key)
    }
}

/// Reads the configuration file at `path` (or an empty one), lets `edit`
/// change it with comments and formatting kept, and writes it back if it
/// still loads as a configuration (through a temporary file, so a crash
/// never leaves a truncated file behind).
fn edit_file(
    path: &Path,
    edit: impl FnOnce(&mut toml_edit::DocumentMut) -> Result<(), ConfigError>,
) -> Result<(), ConfigError> {
    let io_err = |source| ConfigError::Io {
        path: path.to_owned(),
        source,
    };
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) if err.kind() == io::ErrorKind::NotFound => String::new(),
        Err(err) => return Err(io_err(err)),
    };
    let mut document: toml_edit::DocumentMut =
        text.parse().map_err(|source| ConfigError::Edit {
            path: path.to_owned(),
            source,
        })?;
    edit(&mut document)?;
    let edited = document.to_string();
    // Never write a file that rigtop itself could not load afterwards.
    toml::from_str::<Config>(&edited).map_err(|source| ConfigError::Parse {
        path: path.to_owned(),
        source,
    })?;
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(io_err)?;
    }
    let tmp = path.with_extension("toml.tmp");
    fs::write(&tmp, edited).map_err(io_err)?;
    fs::rename(&tmp, path).map_err(io_err)
}

/// How often [`ConfigWatcher::poll`] looks at the file.
const WATCH_INTERVAL: Duration = Duration::from_secs(1);

/// Notices when the configuration file changes, so a running rigtop can
/// apply the edits without a restart.
pub struct ConfigWatcher {
    path: PathBuf,
    /// Modification time and size when last seen (`None`: no file).
    stamp: Option<(Option<SystemTime>, u64)>,
    last_check: Instant,
    interval: Duration,
}

impl ConfigWatcher {
    /// Watches `path`, taking its current state as already loaded.
    pub fn new(path: PathBuf) -> Self {
        Self {
            stamp: file_stamp(&path),
            path,
            last_check: Instant::now(),
            interval: WATCH_INTERVAL,
        }
    }

    /// The file being watched.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Takes the file as it is now as already loaded, e.g. after rigtop
    /// itself wrote to it.
    pub fn mark_seen(&mut self) {
        self.stamp = file_stamp(&self.path);
    }

    /// When the file changed since the previous call, its new contents (or
    /// why they cannot be used, e.g. a file saved half-way). `None` when
    /// unchanged, checked less than a second ago, or removed: a missing
    /// file keeps the configuration in use rather than resetting it.
    pub fn poll(&mut self) -> Option<Result<Config, ConfigError>> {
        if self.last_check.elapsed() < self.interval {
            return None;
        }
        self.last_check = Instant::now();
        let stamp = file_stamp(&self.path);
        if stamp == self.stamp {
            return None;
        }
        self.stamp = stamp;
        stamp?;
        Some(Config::load(&self.path))
    }
}

/// Modification time and size of `path`, if it exists.
fn file_stamp(path: &Path) -> Option<(Option<SystemTime>, u64)> {
    let metadata = fs::metadata(path).ok()?;
    Some((metadata.modified().ok(), metadata.len()))
}

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

    #[test]
    fn template_parses_with_every_setting_uncommented() {
        // Settings are commented as "#key", explanations as "# text".
        let settings: String = CONFIG_TEMPLATE
            .lines()
            .filter_map(|line| line.strip_prefix('#'))
            .filter(|line| !line.starts_with(' ') && !line.is_empty())
            .map(|line| format!("{line}\n"))
            .collect();
        let config: Config = toml::from_str(&settings).unwrap();
        assert_eq!(config.hosts[0].name, "nas");
        // The defaults it shows are the real ones.
        assert_eq!(config.alerts, AlertsConfig::default());
        assert_eq!(config.watch, WatchConfig::default());
        assert_eq!(config.overview, OverviewConfig::default());
        assert_eq!(config.ups, UpsConfig::default());
        // As written, everything is commented out.
        let empty: Config = toml::from_str(CONFIG_TEMPLATE).unwrap();
        assert_eq!(empty, Config::default());

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("rigtop/config.toml");
        assert!(create_if_missing(&path).unwrap());
        assert!(!create_if_missing(&path).unwrap(), "left as it is");
        assert_eq!(Config::load(&path).unwrap(), Config::default());
    }

    #[test]
    fn hidden_panels_are_saved_and_loaded() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(&path, "# mine\n[alerts]\ncpu_warning_celsius = 90\n").unwrap();
        let tui = TuiConfig {
            hidden_panels: vec![OverviewSection::Gpu, OverviewSection::Network],
            show_widgets: false,
        };
        Config::save_tui(&path, &tui).unwrap();
        let text = fs::read_to_string(&path).unwrap();
        assert!(text.starts_with("# mine"), "{text}");
        let config = Config::load(&path).unwrap();
        assert_eq!(
            config.tui.hidden_panels,
            vec![OverviewSection::Gpu, OverviewSection::Network]
        );
        assert!(!config.tui.show_widgets);
        assert_eq!(config.alerts.cpu_warning_celsius, 90.0);
        Config::save_tui(&path, &TuiConfig::default()).unwrap();
        let config = Config::load(&path).unwrap();
        assert_eq!(config.tui, TuiConfig::default());
        assert!(!fs::read_to_string(&path).unwrap().contains("show_widgets"));
    }

    #[test]
    fn watch_settings() {
        let config: Config = toml::from_str(
            "[watch]\ncommand = \"notify-send x\"\nlevel = \"warning\"\ninterval = \"30s\"\n",
        )
        .unwrap();
        assert_eq!(config.watch.command, "notify-send x");
        assert_eq!(config.watch.level, NotifyLevel::Warning);
        assert!(config.watch.cleared);
        assert_eq!(config.watch.interval, Duration::from_secs(30));
        assert_eq!(config.watch.offline_after, Duration::from_secs(180));
        assert!(toml::from_str::<Config>("[watch]\ncomand = \"x\"\n").is_err());
    }

    #[test]
    fn update_checks_can_be_tuned_or_turned_off() {
        let config: Config =
            toml::from_str("[updates]\ninterval = \"6h\"\nnotify = false\n").unwrap();
        assert!(config.updates.check);
        assert_eq!(
            config.updates.check_interval(),
            Duration::from_secs(6 * 3600)
        );
        assert!(!config.updates.notify);
        let config: Config =
            toml::from_str("[updates]\ncheck = false\ninterval = \"10s\"\n").unwrap();
        assert!(!config.updates.check);
        assert_eq!(
            config.updates.check_interval(),
            Duration::from_secs(60),
            "at least a minute"
        );
        let error = toml::from_str::<Config>("[updates]\ninterval = \"6 hours\"\n").unwrap_err();
        assert!(error.to_string().contains("invalid duration"), "{error}");
    }

    #[test]
    fn durations_read_and_write_as_text() {
        let minutes = |m: u64| Some(Duration::from_secs(m * 60));
        assert_eq!(duration_text::parse("30m"), minutes(30));
        assert_eq!(duration_text::parse("1h30m"), minutes(90));
        assert_eq!(duration_text::parse("1h 30m"), minutes(90));
        assert_eq!(duration_text::parse("1d"), minutes(24 * 60));
        assert_eq!(duration_text::parse("2H"), minutes(120));
        for bad in ["", "6", "h", "1.5h", "1w", "-1h", "6 hours"] {
            assert_eq!(duration_text::parse(bad), None, "{bad:?}");
        }
        assert_eq!(duration_text::format(Duration::from_secs(5400)), "1h30m");
        assert_eq!(duration_text::format(Duration::from_secs(86_400)), "1d");
        // The defaults survive saving and loading.
        let text = toml::to_string(&Config::default()).unwrap();
        assert!(text.contains("interval = \"1h\""), "{text}");
        assert_eq!(toml::from_str::<Config>(&text).unwrap(), Config::default());
    }

    #[test]
    fn watcher_reports_edits_once() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(&path, "[alerts]\ncpu_warning_celsius = 90\n").unwrap();
        let mut watcher = ConfigWatcher::new(path.clone());
        watcher.interval = Duration::ZERO;
        assert!(
            watcher.poll().is_none(),
            "the initial file counts as loaded"
        );

        // A different size, so the change shows even where file times are coarse.
        fs::write(&path, "[alerts]\ncpu_warning_celsius = 100\n").unwrap();
        let config = watcher.poll().unwrap().unwrap();
        assert_eq!(config.alerts.cpu_warning_celsius, 100.0);
        assert!(watcher.poll().is_none(), "reported once");

        fs::write(&path, "[alerts\n").unwrap();
        assert!(
            watcher.poll().unwrap().is_err(),
            "a broken file is an error"
        );
        fs::remove_file(&path).unwrap();
        assert!(
            watcher.poll().is_none(),
            "removing the file changes nothing"
        );
    }

    #[test]
    fn missing_file_gives_defaults() {
        let tmp = tempfile::tempdir().unwrap();
        let config = Config::load(&tmp.path().join("none.toml")).unwrap();
        assert_eq!(config, Config::default());
        assert_eq!(config.smart.dir, PathBuf::from(DEFAULT_SMART_DIR));
    }

    #[test]
    fn parses_labels_hidden_and_smart_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(
            &path,
            r#"
[sensors]
labels = { "nct6686:nct6683.2592/fan1" = "CPU fan" }
hidden = ["nct6686:nct6683.2592/temp4"]

[smart]
dir = "/tmp/smart"

[lhm]
url = ""

[notifications]
level = "warning"

[alerts]
drive_warning_celsius = 65
cpu_warning_celsius = 0
gpu_memory_warning_percent = 98
"#,
        )
        .unwrap();
        let config = Config::load(&path).unwrap();
        let fan = Fan {
            key: "nct6686:nct6683.2592/fan1".to_owned(),
            label: "fan1".to_owned(),
            rpm: 900,
        };
        let other = Fan {
            key: "nct6686:nct6683.2592/fan2".to_owned(),
            label: "fan2".to_owned(),
            rpm: 0,
        };
        assert_eq!(config.fan_label(&fan), "CPU fan");
        // Unnamed channels fall back to the generic label.
        assert_eq!(config.fan_label(&other), "fan2");
        assert!(config.is_hidden("nct6686:nct6683.2592/temp4"));
        assert_eq!(config.smart.dir, PathBuf::from("/tmp/smart"));
        assert_eq!(config.lhm.url, "");
        assert_eq!(config.notifications.level, NotifyLevel::Warning);
        assert_eq!(Config::default().notifications.level, NotifyLevel::Critical);
        assert_eq!(Config::default().lhm.url, DEFAULT_LHM_URL);
        assert_eq!(config.alerts.drive_warning_celsius, 65.0);
        assert_eq!(config.alerts.cpu_warning_celsius, 0.0);
        // Unset thresholds keep their defaults.
        assert_eq!(config.alerts.gpu_warning_celsius, 85.0);
        assert_eq!(config.alerts.memory_warning_percent, 90.0);
        assert_eq!(config.alerts.gpu_memory_warning_percent, 98.0);
    }

    #[test]
    fn parses_hosts_and_overview() {
        let config: Config = toml::from_str(
            r#"
[overview]
sections = ["storage", "cpu"]
include_local = false

[[hosts]]
name = "zefat"

[[hosts]]
name = "nas"
ssh = "admin@nas.local"
sections = ["storage"]

[[widgets]]
name = "Clock"
builtin = "clock"

[[widgets]]
name = "Rates"
command = "rates.sh"
interval_secs = 60
"#,
        )
        .unwrap();
        assert_eq!(
            config.overview.sections,
            vec![OverviewSection::Storage, OverviewSection::Cpu]
        );
        assert!(!config.overview.include_local);
        assert_eq!(config.overview.processes, 10, "default kept");
        assert_eq!(config.hosts.len(), 2);
        assert_eq!(config.hosts[0].destination(), "zefat");
        assert_eq!(config.widgets[0].builtin, Some(BuiltinWidget::Clock));
        assert_eq!(config.widgets[1].command.as_deref(), Some("rates.sh"));
        assert_eq!(config.widgets[1].interval_secs, 60);
        assert_eq!(config.widgets[1].timeout_secs, 10, "default kept");
        assert_eq!(config.hosts[1].destination(), "admin@nas.local");
        assert_eq!(
            config.hosts[1].sections,
            Some(vec![OverviewSection::Storage])
        );
        // Defaults: every section in priority order, local included.
        let defaults = Config::default();
        assert_eq!(defaults.overview.sections, OverviewSection::ALL.to_vec());
        assert!(defaults.overview.include_local);
    }

    #[test]
    fn save_hosts_replaces_only_the_hosts() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(
            &path,
            "# my settings\n[sensors]\nlabels = { \"a/fan1\" = \"CPU fan\" } # keep me\n\n[[hosts]]\nname = \"old\"\n",
        )
        .unwrap();
        let hosts = vec![
            HostConfig::from_destination("zefat"),
            HostConfig {
                name: "nas".to_owned(),
                ssh: Some("admin@nas.local".to_owned()),
                command: Some("/opt/rigtop --agent".to_owned()),
                sections: Some(vec![OverviewSection::Storage, OverviewSection::Cpu]),
                alerts: Some(
                    toml::from_str("cpu_warning_celsius = 90.0\nignored_units = [\"a.service\"]")
                        .unwrap(),
                ),
            },
        ];
        Config::save_hosts(&path, &hosts).unwrap();

        let text = fs::read_to_string(&path).unwrap();
        assert!(
            text.contains("# my settings") && text.contains("# keep me"),
            "{text}"
        );
        assert!(!text.contains("\"old\""), "{text}");
        let config = Config::load(&path).unwrap();
        assert_eq!(config.hosts, hosts);
        assert_eq!(config.label_for("a/fan1"), Some("CPU fan"));

        // Removing every host drops the [[hosts]] tables.
        Config::save_hosts(&path, &[]).unwrap();
        assert!(Config::load(&path).unwrap().hosts.is_empty());
        assert!(fs::read_to_string(&path).unwrap().contains("# keep me"));
    }

    #[test]
    fn host_alerts_replace_the_keys_they_give() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(
            &path,
            "[alerts]\nmemory_warning_percent = 80\n\n\
             [[hosts]]\nname = \"laptop\"\n[hosts.alerts]\ncpu_warning_celsius = 100\n\n\
             [[hosts]]\nname = \"nas\"\n",
        )
        .unwrap();
        let config = Config::load(&path).unwrap();
        let laptop = config.alerts_for(&config.hosts[0]).unwrap();
        assert_eq!(laptop.cpu_warning_celsius, 100.0);
        // The others come from [alerts], set or default.
        assert_eq!(laptop.memory_warning_percent, 80.0);
        assert_eq!(laptop.gpu_warning_celsius, 85.0);
        assert_eq!(config.alerts_for(&config.hosts[1]).unwrap(), config.alerts);

        // A typo fails the load, naming the host.
        fs::write(
            &path,
            "[[hosts]]\nname = \"laptop\"\n[hosts.alerts]\ncpu_warning_celsus = 100\n",
        )
        .unwrap();
        let err = Config::load(&path).unwrap_err().to_string();
        assert!(
            err.contains("laptop") && err.contains("cpu_warning_celsus"),
            "{err}"
        );
    }

    #[test]
    fn save_sensors_replaces_only_names_and_hidden_sensors() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(
            &path,
            "# my settings\n[sensors]\nlabels = { \"a/fan1\" = \"CPU fan\" } # inline\n\n[[hosts]]\nname = \"zefat\"\n",
        )
        .unwrap();
        let mut sensors = SensorConfig::default();
        sensors
            .labels
            .insert("a/fan1".to_owned(), "CPU fan".to_owned());
        sensors
            .labels
            .insert("b:c.1/temp2".to_owned(), "VRM".to_owned());
        sensors.hidden.push("b:c.1/temp4".to_owned());
        Config::save_sensors(&path, &sensors).unwrap();

        let text = fs::read_to_string(&path).unwrap();
        assert!(text.contains("# my settings"), "{text}");
        // Inline names stay inline.
        assert!(text.contains("labels = {"), "{text}");
        let config = Config::load(&path).unwrap();
        assert_eq!(config.sensors, sensors);
        assert_eq!(config.hosts[0].name, "zefat");

        // Nothing left: the [sensors] table goes away.
        Config::save_sensors(&path, &SensorConfig::default()).unwrap();
        let text = fs::read_to_string(&path).unwrap();
        assert!(!text.contains("[sensors]"), "{text}");
        assert_eq!(Config::load(&path).unwrap().hosts.len(), 1);

        // A new file gets a [sensors.labels] table.
        let fresh = tmp.path().join("new.toml");
        Config::save_sensors(&fresh, &sensors).unwrap();
        let text = fs::read_to_string(&fresh).unwrap();
        assert!(text.contains("[sensors.labels]"), "{text}");
        assert_eq!(Config::load(&fresh).unwrap().sensors, sensors);
    }

    #[test]
    fn save_hosts_creates_a_missing_file() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("new/rigtop/config.toml");
        Config::save_hosts(&path, &[HostConfig::from_destination("zefat")]).unwrap();
        assert_eq!(Config::load(&path).unwrap().hosts[0].name, "zefat");
    }

    #[test]
    fn save_hosts_refuses_to_touch_a_broken_file() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        fs::write(&path, "[sensors\n").unwrap();
        let err = Config::save_hosts(&path, &[]).unwrap_err();
        assert!(matches!(err, ConfigError::Edit { .. }), "{err}");
        assert_eq!(fs::read_to_string(&path).unwrap(), "[sensors\n");
    }

    #[test]
    fn unknown_fields_are_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        // A typo such as "label" instead of "labels" must not be silently ignored.
        fs::write(&path, "[sensors]\nlabel = {}\n").unwrap();
        assert!(matches!(
            Config::load(&path),
            Err(ConfigError::Parse { .. })
        ));
    }

    #[test]
    fn save_and_reload_round_trip() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("nested/rigtop/config.toml");
        let mut config = Config::default();
        config.set_label("k10temp:0000:00:18.3/temp3", " CCD1 ");
        config.set_label("nct6686:nct6683.2592/fan1", "Rear fan");
        config.set_label("nct6686:nct6683.2592/fan1", "");
        config.save(&path).unwrap();

        let back = Config::load(&path).unwrap();
        assert_eq!(back.label_for("k10temp:0000:00:18.3/temp3"), Some("CCD1"));
        // An empty name removes the label.
        assert_eq!(back.label_for("nct6686:nct6683.2592/fan1"), None);
        assert!(!path.with_extension("toml.tmp").exists());
    }
}