chrony-confile 0.1.0

A full-featured Rust library for parsing, editing, validating, and serializing chrony configuration files
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
//! Real-machine comprehensive test runner for chrony-confile.
//!
//! Compiles to a standalone binary, creates temp files for include/confdir testing,
//! and prints a detailed pass/fail report.

use chrony_confile::prelude::*;
use std::fs;
use std::process;

fn run() -> bool {
    let mut all_ok = true;

    // ============================================================
    // SECTION 1: Zero-argument flag directives
    // ============================================================
    println!("\n=== SECTION 1: Zero-argument flags ===");

    for (name, input) in [
        ("rtconutc", "rtconutc"),
        ("rtcsync", "rtcsync"),
        ("lock_all", "lock_all"),
        ("manual", "manual"),
        ("noclientlog", "noclientlog"),
        ("nosystemcert", "nosystemcert"),
        ("dumponexit", "dumponexit"),
    ] {
        let test_name = format!("parse {}", name);
        match ChronyConfig::parse(input) {
            Ok(c) => {
                if c.directives().count() == 1 {
                    println!("  PASS  {:<55}", test_name);
                } else {
                    println!("  FAIL  {:<55}  expected 1 directive, got {}", test_name, c.directives().count());
                    all_ok = false;
                }
            }
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", test_name);
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 2: Single-string directives
    // ============================================================
    println!("\n=== SECTION 2: Single-string directives ===");

    for (name, input, _expected_path) in [
        ("dumpdir", "dumpdir /var/lib/chrony", "/var/lib/chrony"),
        ("logdir", "logdir /var/log/chrony", "/var/log/chrony"),
        ("rtcdevice", "rtcdevice /dev/rtc0", "/dev/rtc0"),
        ("rtcfile", "rtcfile /var/lib/chrony/rtc", "/var/lib/chrony/rtc"),
        ("pidfile", "pidfile /run/chronyd.pid", "/run/chronyd.pid"),
        ("user", "user chrony", "chrony"),
        ("keyfile", "keyfile /etc/chrony/keys", "/etc/chrony/keys"),
        ("confdir", "confdir /etc/chrony.d", "/etc/chrony.d"),
        ("sourcedir", "sourcedir /var/lib/chrony", "/var/lib/chrony"),
        ("bindaddress", "bindaddress 0.0.0.0", "0.0.0.0"),
        ("ntsservercert", "ntsservercert /etc/chrony/cert.pem", "/etc/chrony/cert.pem"),
        ("ntsserverkey", "ntsserverkey /etc/chrony/key.pem", "/etc/chrony/key.pem"),
        ("ntsdumpdir", "ntsdumpdir /var/lib/chrony/nts", "/var/lib/chrony/nts"),
        ("ntpsigndsocket", "ntpsigndsocket /var/lib/samba/ntp_signd", "/var/lib/samba/ntp_signd"),
        ("ntsntpserver", "ntsntpserver nts.example.com", "nts.example.com"),
        ("leapsectz", "leapsectz right/UTC", "right/UTC"),
        ("leapseclist", "leapseclist /usr/share/zoneinfo/leap-seconds.list", "/usr/share/zoneinfo/leap-seconds.list"),
    ] {
        let test_name = format!("parse {}", name);
        match ChronyConfig::parse(input) {
            Ok(c) => {
                println!("  PASS  {:<55}", test_name);
                // Round-trip check
                let output = c.to_string().trim().to_string();
                let reparsed = ChronyConfig::parse(&format!("{output}\n"));
                if reparsed.is_err() {
                    println!("  WARN  {:<55}  round-trip failed", format!("{name} round-trip"));
                }
            }
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", test_name);
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 3: Integer directives
    // ============================================================
    println!("\n=== SECTION 3: Integer directives ===");

    for (name, input) in [
        ("port 123", "port 123"),
        ("port 0", "port 0"),
        ("cmdport 323", "cmdport 323"),
        ("dscp 46", "dscp 46"),
        ("minsources 2", "minsources 2"),
        ("maxsamples 32", "maxsamples 32"),
        ("minsamples 8", "minsamples 8"),
        ("logbanner 64", "logbanner 64"),
        ("maxntsconnections 200", "maxntsconnections 200"),
        ("ntsrotate 86400", "ntsrotate 86400"),
        ("ntsrefresh 1209600", "ntsrefresh 1209600"),
        ("refresh 604800", "refresh 604800"),
        ("sched_priority 50", "sched_priority 50"),
        ("ptpdomain 100", "ptpdomain 100"),
        ("ntsprocesses 4", "ntsprocesses 4"),
        ("maxtxbuffers 512", "maxtxbuffers 512"),
        ("ptpport 319", "ptpport 319"),
        ("acquisitionport 12345", "acquisitionport 12345"),
        ("ntsport 4460", "ntsport 4460"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // Out-of-range / invalid value tests
    for (name, input) in [
        ("port not a number", "port abc"),
        ("dscp out of range", "dscp 100"),
        ("sched_priority out of range", "sched_priority 200"),
    ] {
        match ChronyConfig::parse(input) {
            Err(_) => println!("  PASS  {:<55}", format!("{name} → error")),
            Ok(_) => {
                println!("  FAIL  {:<55}  expected error", format!("{name} → error"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 4: Double directives
    // ============================================================
    println!("\n=== SECTION 4: Double directives ===");

    for (name, input) in [
        ("clockprecision 1e-6", "clockprecision 1e-6"),
        ("corrtimeratio 2.5", "corrtimeratio 2.5"),
        ("maxdistance 5.0", "maxdistance 5.0"),
        ("maxjitter 0.5", "maxjitter 0.5"),
        ("combinelimit 5.0", "combinelimit 5.0"),
        ("reselectdist 1e-3", "reselectdist 1e-3"),
        ("stratumweight 0.01", "stratumweight 0.01"),
        ("maxclockerror 2.5", "maxclockerror 2.5"),
        ("maxdrift 100000.0", "maxdrift 100000.0"),
        ("maxupdateskew 500.0", "maxupdateskew 500.0"),
        ("maxslewrate 50000.0", "maxslewrate 50000.0"),
        ("logchange 0.5", "logchange 0.5"),
        ("rtcautotrim 1.0", "rtcautotrim 1.0"),
        ("hwtstimeout 0.002", "hwtstimeout 0.002"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 5: Keyword enum directives
    // ============================================================
    println!("\n=== SECTION 5: Keyword enums ===");

    for mode in ["require", "prefer", "mix", "ignore"] {
        match ChronyConfig::parse(&format!("authselectmode {mode}")) {
            Ok(_) => println!("  PASS  {:<55}", format!("authselectmode {mode}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("authselectmode {mode}"));
                all_ok = false;
            }
        }
    }
    for mode in ["system", "step", "slew", "ignore"] {
        match ChronyConfig::parse(&format!("leapsecmode {mode}")) {
            Ok(_) => println!("  PASS  {:<55}", format!("leapsecmode {mode}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("leapsecmode {mode}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 6: Multi-argument fixed directives
    // ============================================================
    println!("\n=== SECTION 6: Multi-argument directives ===");

    for (name, input) in [
        ("fallbackdrift", "fallbackdrift 16 19"),
        ("makestep", "makestep 1.0 3"),
        ("maxchange", "maxchange 1.0 10 -1"),
        ("mailonchange", "mailonchange root@localhost 0.5"),
        ("clientloglimit", "clientloglimit 1048576"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 7: DriftFile with interval
    // ============================================================
    println!("\n=== SECTION 7: DriftFile ===");

    match ChronyConfig::parse("driftfile /var/lib/chrony/drift") {
        Ok(c) => {
            if let Some(DirectiveKind::DriftFile(df)) =
                c.find("driftfile").next().map(|d| &d.kind)
            {
                if df.path == "/var/lib/chrony/drift" && df.interval.is_none() {
                    println!("  PASS  {:<55}", "driftfile basic");
                } else {
                    println!("  FAIL  {:<55}  path or interval mismatch", "driftfile basic");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "driftfile basic");
            all_ok = false;
        }
    }

    match ChronyConfig::parse("driftfile /var/lib/chrony/drift interval 1800") {
        Ok(c) => {
            if let Some(DirectiveKind::DriftFile(df)) =
                c.find("driftfile").next().map(|d| &d.kind)
            {
                if df.interval == Some(1800) {
                    println!("  PASS  {:<55}", "driftfile with interval");
                } else {
                    println!("  FAIL  {:<55}  interval mismatch", "driftfile with interval");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "driftfile with interval");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 8: Server directive (all options)
    // ============================================================
    println!("\n=== SECTION 8: Server directive ===");

    let server_input = "server ntp.example.com iburst prefer minpoll 4 maxpoll 8 port 123 ntsport 4460 key 42 certset 1 maxdelay 2.5 polltarget 16 minstratum 2 version 4 filter 8 offset 0.001";
    match ChronyConfig::parse(server_input) {
        Ok(c) => {
            if let Some(DirectiveKind::Server(s)) = c.find("server").next().map(|d| &d.kind) {
                let checks = [
                    ("hostname", s.hostname == "ntp.example.com"),
                    ("iburst", s.iburst),
                    ("prefer", s.prefer()),
                    ("minpoll", s.minpoll.get() == 4),
                    ("maxpoll", s.maxpoll.get() == 8),
                    ("port", s.port.get() == 123),
                    ("authkey", s.authkey == 42),
                    ("cert_set", s.cert_set == 1),
                    ("max_delay", (s.max_delay - 2.5).abs() < 1e-10),
                    ("poll_target", s.poll_target.get() == 16),
                    ("min_stratum", s.min_stratum.get() == 2),
                    ("version", s.version.map(|v| v.get()) == Some(4)),
                    ("filter", s.filter == Some(8)),
                    ("offset", (s.offset - 0.001).abs() < 1e-10),
                ];
                for (field, ok) in &checks {
                    if *ok {
                        println!("  PASS  {:<55}", format!("server {field}"));
                    } else {
                        println!("  FAIL  {:<55}", format!("server {field}"));
                        all_ok = false;
                    }
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "server all options");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 9: Pool directive
    // ============================================================
    println!("\n=== SECTION 9: Pool directive ===");

    match ChronyConfig::parse("pool pool.ntp.org iburst maxsources 6") {
        Ok(c) => {
            if let Some(DirectiveKind::Pool(p)) = c.find("pool").next().map(|d| &d.kind) {
                let checks = [
                    ("hostname", p.source.hostname == "pool.ntp.org"),
                    ("iburst", p.source.iburst),
                    ("max_sources", p.max_sources == 6),
                ];
                for (field, ok) in &checks {
                    println!("  {}  {:<55}", if *ok { "PASS" } else { "FAIL" }, format!("pool {field}"));
                    if !ok { all_ok = false; }
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "pool directive");
            all_ok = false;
        }
    }

    // maxsources rejected on server
    match ChronyConfig::parse("server ntp.example.com maxsources 6") {
        Err(_) => println!("  PASS  {:<55}", "server rejects maxsources"),
        Ok(_) => {
            println!("  FAIL  {:<55}", "server rejects maxsources");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 10: Refclock directive
    // ============================================================
    println!("\n=== SECTION 10: Refclock ===");

    for (name, input) in [
        ("PPS", "refclock PPS /dev/pps0 poll 4 dpoll -4 rate 6 width 0.001"),
        ("SHM", "refclock SHM 0 poll 4 refid SHM0"),
        ("SOCK", "refclock SOCK /var/run/chrony.sock"),
        ("PHC", "refclock PHC /dev/ptp0 dpoll 4 poll 6 noselect"),
        ("PPS with prefer", "refclock PPS /dev/pps0 prefer trust offset 0.001 delay 1e-8 stratum 1 tai"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("refclock {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("refclock {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 11: Allow/Deny
    // ============================================================
    println!("\n=== SECTION 11: Allow/Deny ===");

    for (name, input) in [
        ("allow all", "allow all"),
        ("allow subnet", "allow 192.168.0.0/16"),
        ("allow short subnet", "allow 192.168.123"),
        ("deny all", "deny all"),
        ("deny subnet", "deny 192.168.1.0/24"),
        ("cmdallow all", "cmdallow all 10.0.0.0/8"),
        ("cmddeny", "cmddeny"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 12: Ratelimit variants
    // ============================================================
    println!("\n=== SECTION 12: Ratelimit ===");

    for (name, input) in [
        ("ratelimit defaults", "ratelimit"),
        ("ratelimit all opts", "ratelimit interval 4 burst 16 leak 2 kod 1"),
        ("ntsratelimit", "ntsratelimit interval 8 burst 32 leak 3"),
        ("cmdratelimit", "cmdratelimit interval -10 burst 4 leak 1"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 13: TempComp (both forms)
    // ============================================================
    println!("\n=== SECTION 13: TempComp ===");

    match ChronyConfig::parse("tempcomp /sys/class/hwmon/temp 4.0 25.0 0.0 1.0 0.0") {
        Ok(c) => {
            if let Some(DirectiveKind::TempComp(tc)) = c.find("tempcomp").next().map(|d| &d.kind) {
                if matches!(tc, TempCompConfig::Coefficients { .. }) {
                    println!("  PASS  {:<55}", "tempcomp coefficients form");
                } else {
                    println!("  FAIL  {:<55}", "tempcomp coefficients form");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "tempcomp coefficients");
            all_ok = false;
        }
    }

    match ChronyConfig::parse("tempcomp /sys/class/hwmon/temp 4.0 /etc/points.txt") {
        Ok(c) => {
            if let Some(DirectiveKind::TempComp(tc)) = c.find("tempcomp").next().map(|d| &d.kind) {
                if matches!(tc, TempCompConfig::PointFile { .. }) {
                    println!("  PASS  {:<55}", "tempcomp pointfile form");
                } else {
                    println!("  FAIL  {:<55}", "tempcomp pointfile form");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  {e}", "tempcomp pointfile");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 14: Complex directives (local, smoothtime, broadcast, log, hwtimestamp)
    // ============================================================
    println!("\n=== SECTION 14: Complex directives ===");

    for (name, input) in [
        ("local defaults", "local"),
        ("local all opts", "local stratum 5 orphan waitsynced 60 waitunsynced 10"),
        ("smoothtime basic", "smoothtime 400 0.001"),
        ("smoothtime leaponly", "smoothtime 400 0.001 leaponly"),
        ("broadcast", "broadcast 64 192.168.123.255"),
        ("broadcast with port", "broadcast 32 10.0.0.255 123"),
        ("log multi", "log tracking measurements statistics rtc"),
        ("hwtimestamp basic", "hwtimestamp eth0 minpoll 4 maxpoll 6 rxfilter ntp"),
        ("hwtimestamp nocrossts", "hwtimestamp eth0 nocrossts rxfilter all"),
        ("ntsaeads", "ntsaeads 15 30 45"),
        ("opencommands", "opencommands activity sources tracking"),
        ("ntstrustedcerts", "ntstrustedcerts /etc/chrony/certs"),
        ("ntstrustedcerts with id", "ntstrustedcerts 5 /etc/chrony/certs"),
        ("initstepslew", "initstepslew 0.5 ntp1.example.com ntp2.example.com"),
        ("peer", "peer 192.168.1.1 minpoll 6 maxpoll 10"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", format!("parse {name}")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("parse {name}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 15: Round-trip fidelity
    // ============================================================
    println!("\n=== SECTION 15: Round-trip fidelity ===");

    let complex_config = "\
# NTP servers
server ntp1.example.com iburst prefer minpoll 4
server ntp2.example.com iburst

# Pool
pool pool.ntp.org maxsources 6

# Drift
driftfile /var/lib/chrony/drift interval 3600

# Access
allow 192.168.0.0/16
allow 10.0.0.0/8

# Clock
makestep 1.0 3
maxdistance 5.0
rtconutc
rtcsync
log tracking measurements statistics
";
    match ChronyConfig::parse(complex_config) {
        Ok(c1) => {
            let serialized = c1.to_string();
            match ChronyConfig::parse(&serialized) {
                Ok(c2) => {
                    // Compare serialized output (not full AST with spans, which differ due to reformatting)
                    let reserialized = c2.to_string();
                    if serialized == reserialized {
                        println!("  PASS  {:<55}", "full round-trip serialization stability");
                    } else {
                        println!("  FAIL  {:<55}  serialized outputs differ", "full round-trip serialization stability");
                        all_ok = false;
                    }
                }
                Err(e) => {
                    println!("  FAIL  {:<55}  reparse failed: {e}", "full round-trip serialization stability");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse failed: {e}", "full round-trip serialization stability");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 16: Case insensitivity
    // ============================================================
    println!("\n=== SECTION 16: Case insensitivity ===");

    for (name, input) in [
        ("SERVER upppercase", "SERVER ntp.example.com IBURST PREFER"),
        ("SeRvEr mixed", "SeRvEr ntp.example.com IbUrSt PrEfEr"),
        ("DRIFTFILE upper", "DRIFTFILE /var/lib/chrony/drift"),
        ("LeApSeCmOdE mixed", "LeApSeCmOdE SlEw"),
    ] {
        match ChronyConfig::parse(input) {
            Ok(_) => println!("  PASS  {:<55}", name),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", name);
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 17: Builder API
    // ============================================================
    println!("\n=== SECTION 17: Builder API ===");

    let mut config = ChronyConfig::new();
    let server = ServerBuilder::new("ntp.example.com")
        .iburst()
        .prefer()
        .minpoll(PollInterval::new(4).unwrap())
        .maxpoll(PollInterval::new(8).unwrap())
        .build();
    config.push_directive(*server);
    config.add_blank();
    config.push(DirectiveKind::RtcOnUtc);
    config.push(DirectiveKind::LockAll);

    if config.directives().count() == 3 {
        println!("  PASS  {:<55}", "builder + push API");
    } else {
        println!("  FAIL  {:<55}  expected 3 directives, got {}", "builder + push API", config.directives().count());
        all_ok = false;
    }

    // ============================================================
    // SECTION 18: Validation
    // ============================================================
    println!("\n=== SECTION 18: Validation ===");

    // Valid config
    match ChronyConfig::parse("server ntp.example.com minpoll 4 maxpoll 8") {
        Ok(c) => {
            let errors = c.validate();
            if errors.is_empty() {
                println!("  PASS  {:<55}", "valid config → no errors");
            } else {
                println!("  FAIL  {:<55}  got {:?}", "valid config → no errors", errors.len());
                all_ok = false;
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse error: {e}", "valid config → no errors");
            all_ok = false;
        }
    }

    // Invalid: minpoll > maxpoll
    match ChronyConfig::parse("server ntp.example.com minpoll 8 maxpoll 4") {
        Ok(c) => {
            let errors = c.validate();
            if !errors.is_empty() {
                println!("  PASS  {:<55}", "minpoll > maxpoll → error");
            } else {
                println!("  FAIL  {:<55}  expected validation error", "minpoll > maxpoll → error");
                all_ok = false;
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse error: {e}", "minpoll > maxpoll → error");
            all_ok = false;
        }
    }

    // NTS cert/key mismatch
    match ChronyConfig::parse("ntsservercert a.crt\nntsservercert b.crt\nntsserverkey a.key\n") {
        Ok(c) => {
            let errors = c.validate();
            if !errors.is_empty() {
                println!("  PASS  {:<55}", "NTS cert/key mismatch → error");
            } else {
                println!("  FAIL  {:<55}  expected validation error", "NTS cert/key mismatch → error");
                all_ok = false;
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse error: {e}", "NTS cert/key mismatch → error");
            all_ok = false;
        }
    }

    // ============================================================
    // SECTION 19: SourceFile (.sources) parsing
    // ============================================================
    println!("\n=== SECTION 19: SourceFile parsing ===");

    let sources_input = "\
server ntp1.example.com iburst
server ntp2.example.com prefer
# This is a comment
pool pool.ntp.org maxsources 6
badline this should be skipped
server ntp3.example.com
";
    let sf = SourceFile::parse(sources_input);
    let entry_count = sf.nodes.iter().filter(|n| matches!(n, SourceNode::Entry(_))).count();
    if entry_count == 4 {
        println!("  PASS  {:<55}", "source file parsing (4 entries, 1 bad line)");
    } else {
        println!("  FAIL  {:<55}  expected 4 entries, got {entry_count}", "source file parsing");
        all_ok = false;
    }

    // SourceFile FromStr
    let sf2: SourceFile = "server ntp1.example.com\npeer 192.168.1.1\n".parse().unwrap();
    if sf2.nodes.len() == 2 {
        println!("  PASS  {:<55}", "SourceFile FromStr");
    } else {
        println!("  FAIL  {:<55}  expected 2 entries", "SourceFile FromStr");
        all_ok = false;
    }

    // ============================================================
    // SECTION 20: Error handling — strict vs lenient
    // ============================================================
    println!("\n=== SECTION 20: Error handling ===");

    // Strict: invalid directive
    match ChronyConfig::parse("bogus_directive") {
        Err(_) => println!("  PASS  {:<55}", "strict: invalid directive → error"),
        Ok(_) => {
            println!("  FAIL  {:<55}", "strict: invalid directive → error");
            all_ok = false;
        }
    }

    // Strict: missing argument
    match ChronyConfig::parse("port") {
        Err(_) => println!("  PASS  {:<55}", "strict: missing argument → error"),
        Ok(_) => {
            println!("  FAIL  {:<55}", "strict: missing argument → error");
            all_ok = false;
        }
    }

    // Strict: too many arguments on zero-arg directive
    match ChronyConfig::parse("rtconutc extra") {
        Err(_) => println!("  PASS  {:<55}", "strict: too many args → error"),
        Ok(_) => {
            println!("  FAIL  {:<55}", "strict: too many args → error");
            all_ok = false;
        }
    }

    // Lenient mode
    let lenient_input = "\
server good1.example.com
bogus_line_should_be_skipped
server good2.example.com iburst
port
server good3.example.com
";
    let (config, warnings) = ChronyConfig::parse_lenient(lenient_input);
    let count = config.directives().count();
    if count == 3 && !warnings.is_empty() {
        println!("  PASS  {:<55}", "lenient: 3 valid, skipping 2 errors");
    } else {
        println!("  FAIL  {:<55}  expected 3 directives + warnings, got {count} + {w}", "lenient", w = warnings.len());
        all_ok = false;
    }

    // ============================================================
    // SECTION 21: Include/confdir expansion (with real files)
    // ============================================================
    println!("\n=== SECTION 21: Include expansion ===");

    let tmp = std::env::temp_dir().join("chrony_confile_test");
    let _ = fs::remove_dir_all(&tmp);
    fs::create_dir_all(&tmp).unwrap();

    // Create included file
    fs::write(tmp.join("included.conf"), "server include.example.com iburst\nrtconutc\n").unwrap();

    // Create confdir with .conf files
    let conf_d = tmp.join("conf.d");
    fs::create_dir_all(&conf_d).unwrap();
    fs::write(conf_d.join("01-server.conf"), "server confdir1.example.com\n").unwrap();
    fs::write(conf_d.join("02-server.conf"), "server confdir2.example.com\n").unwrap();

    // Create .sources files
    let sources_d = tmp.join("sources.d");
    fs::create_dir_all(&sources_d).unwrap();
    fs::write(sources_d.join("1.sources"), "server source1.example.com iburst\n").unwrap();

    // Main config with include and confdir
    let main_config = format!(
        "server main.example.com prefer\n\
         include {}/included.conf\n\
         confdir {}/conf.d\n",
        tmp.display(), tmp.display()
    );

    match ChronyConfig::parse(&main_config) {
        Ok(config) => {
            // Before expansion
            let server_count = config.find("server").count();
            let has_include = config.find("include").count() > 0;
            if server_count == 1 && has_include {
                println!("  PASS  {:<55}", "include preserved as AST node");
            } else {
                println!("  FAIL  {:<55}  expected 1 server + include node", "include preserved as AST node");
                all_ok = false;
            }

            // After expansion
            match config.expand(&tmp) {
                Ok(expanded) => {
                    let expanded_servers = expanded.find("server").count();
                    let has_rtconutc = expanded.find("rtconutc").count() > 0;
                    // main + include + confdir1 + confdir2 = 4 servers
                    if expanded_servers == 4 && has_rtconutc {
                        println!("  PASS  {:<55}", "expand: 4 servers + rtconutc resolved");
                    } else {
                        println!("  FAIL  {:<55}  expected 4 servers, got {expanded_servers}", "expand resolution");
                        all_ok = false;
                    }
                }
                Err(e) => {
                    println!("  FAIL  {:<55}  expand error: {e}", "expand resolution");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse error: {e}", "include/confdir config");
            all_ok = false;
        }
    }

    // Test include level exceeded
    let deep_include = tmp.join("deep.conf");
    fs::write(&deep_include, format!("include {deep}\n", deep = deep_include.display())).unwrap();
    match ChronyConfig::parse(&format!("include {deep}", deep = deep_include.display())) {
        Ok(config) => {
            match config.expand(&tmp) {
                Err(_) => println!("  PASS  {:<55}", "include level exceeded → error"),
                Ok(_) => {
                    println!("  FAIL  {:<55}  expected error for deep include", "include level exceeded → error");
                    all_ok = false;
                }
            }
        }
        Err(e) => {
            println!("  FAIL  {:<55}  parse error: {e}", "include level exceeded");
            all_ok = false;
        }
    }

    // Cleanup
    let _ = fs::remove_dir_all(&tmp);

    // ============================================================
    // SECTION 22: Deprecated directives
    // ============================================================
    println!("\n=== SECTION 22: Deprecated directives ===");

    for deprecated in ["commandkey", "generatecommandkey", "linux_freq_scale", "linux_hz"] {
        match ChronyConfig::parse(deprecated) {
            Ok(_) => println!("  PASS  {:<55}", format!("deprecated: {deprecated} accepted")),
            Err(e) => {
                println!("  FAIL  {:<55}  {e}", format!("deprecated: {deprecated}"));
                all_ok = false;
            }
        }
    }

    // ============================================================
    // SECTION 23: Send + Sync verification
    // ============================================================
    println!("\n=== SECTION 23: Send + Sync ===");

    #[allow(dead_code)]
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ChronyConfig>();
    assert_send_sync::<Directive>();
    assert_send_sync::<DirectiveKind>();
    assert_send_sync::<ConfigNode>();
    assert_send_sync::<SourceFile>();
    assert_send_sync::<Span>();
    assert_send_sync::<ParseError>();
    assert_send_sync::<PollInterval>();
    assert_send_sync::<UdpPort>();
    println!("  PASS  {:<55}", "all major types Send + Sync");

    println!();
    all_ok
}

fn main() {
    println!("╔══════════════════════════════════════════════════════════════╗");
    println!("║     chrony-confile v0.1.0 — Real Machine Test Suite         ║");
    println!("╚══════════════════════════════════════════════════════════════╝");

    // Print system info
    println!("\nEnvironment:");
    println!("  arch:     {}", std::env::consts::ARCH);
    println!("  os:       {}", std::env::consts::OS);
    println!("  target:   {}-{}", std::env::consts::ARCH, std::env::consts::OS);
    println!("  version:  {}", env!("CARGO_PKG_VERSION"));
    println!("  pid:      {}", std::process::id());

    let success = run();

    println!("\n╔══════════════════════════════════════════════════════════════╗");
    if success {
        println!("║                    ALL TESTS PASSED                          ║");
    } else {
        println!("║                    SOME TESTS FAILED                         ║");
    }
    println!("╚══════════════════════════════════════════════════════════════╝\n");

    if !success {
        process::exit(1);
    }
}