hinoirisetr 1.6.2

A daemon to dim the screen at night
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
use std::env;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use hinoirisetr::backend::gamma::{GammaBackend, apply_gamma};
use hinoirisetr::backend::temp::{TempBackend, apply_temp};
use hinoirisetr::notify::InitializedNotificationSystem;
use hinoirisetr::{
    Config, ConfigError, compute_settings, debug, error, info, reset_cache, trace, warn,
};
use time::OffsetDateTime;
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
use tokio::signal::unix::{SignalKind, signal};
use tokio::sync::{Notify, RwLock};
use tokio::time::sleep;

fn get_socket_path() -> PathBuf {
    let username = env::var("USER").expect("USER environment variable not set");

    let mut socket_path = PathBuf::from("/tmp");
    socket_path.push(format!("hinoirisetr-{username}.sock"));
    socket_path
}

static CONFIG: OnceLock<Arc<RwLock<Config>>> = OnceLock::new();
static LAST_MODIFIED: AtomicU64 = AtomicU64::new(0);

#[derive(Clone)]
enum NotifyState {
    Enabled(InitializedNotificationSystem),
    Disabled,
}

async fn write_response<W: AsyncWrite + Unpin>(
    writer: &mut W,
    response: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    writer.write_all(response.as_bytes()).await?;
    writer.shutdown().await?;
    Ok(())
}

fn get_status_string(
    now: OffsetDateTime,
    config: &Config,
    disabled_temp: &AtomicBool,
    disabled_gamma: &AtomicBool,
) -> String {
    let (cur_temp, cur_gamma) = compute_settings(now, config);
    format!(
        "dimming - {}{}{}",
        if config.temp_backend.iter().all(|b| *b == TempBackend::None) {
            String::new()
        } else {
            format!(
                "temp: {}",
                if disabled_temp.load(Ordering::SeqCst) {
                    "disabled".to_string()
                } else {
                    format!("{cur_temp}K")
                }
            )
        },
        if config.temp_backend.iter().any(|b| *b != TempBackend::None)
            && config
                .gamma_backend
                .iter()
                .any(|b| *b != GammaBackend::None)
        {
            ", "
        } else {
            ""
        },
        if config
            .gamma_backend
            .iter()
            .all(|b| *b == GammaBackend::None)
        {
            String::new()
        } else {
            format!(
                "gamma: {}",
                if disabled_gamma.load(Ordering::SeqCst) {
                    "disabled".to_string()
                } else {
                    format!("{cur_gamma}%")
                }
            )
        }
    )
}

async fn config_reloader(notify: Arc<Notify>) {
    debug!("config reloader started");
    // Config polling every 5 seconds
    loop {
        trace!("config poll tick");
        let config_path = get_config_path();
        if config_path.exists()
            && let Ok(current_modified) = std::fs::metadata(&config_path)
                .and_then(|m| m.modified())
                .map(|t| t.duration_since(UNIX_EPOCH).unwrap().as_secs())
        {
            let last: u64 = LAST_MODIFIED.load(Ordering::SeqCst);
            if 0 != last {
                if current_modified > last {
                    trace!("{current_modified}");
                    trace!("{last}");
                    debug!("Config file modified, reloading...");
                    let _ = reload_config(Arc::clone(&notify)).await;
                }
            } else {
                // File is new, reload to capture initial state
                debug!("Config file detected, reloading...");
                let _ = reload_config(Arc::clone(&notify)).await;
            }
        }
        sleep(Duration::from_secs(5)).await;
    }
}

#[allow(clippy::too_many_arguments)]
async fn handle_flag_update<F, G, W>(
    disabled_temp: &AtomicBool,
    disabled_gamma: &AtomicBool,
    set_temp: F,
    set_gamma: G,
    status: &str,
    #[allow(unused_variables)] trace_msg: &str,
    notify: &Notify,
    writer: &mut W,
) where
    F: FnOnce(&AtomicBool),
    G: FnOnce(&AtomicBool),
    W: AsyncWrite + Unpin,
{
    trace!("{}", trace_msg);
    set_temp(disabled_temp);
    set_gamma(disabled_gamma);
    notify.notify_one();
    info!("{}", status);
    if let Err(e) = write_response(writer, status).await {
        error!("Failed to respond over socket: {e}");
    }
}

macro_rules! toggle_flag {
    ($flag:expr, $notify:expr, $writer:expr, $name:expr, $trace_msg:expr) => {{
        use std::sync::atomic::Ordering::SeqCst;
        trace!("{}", $trace_msg);
        let old = $flag.load(SeqCst);
        let new_val = !old;
        $flag.store(new_val, SeqCst);
        $notify.notify_one();
        let status = format!(
            "{} dimming is {}",
            $name,
            if new_val { "disabled" } else { "enabled" }
        );
        info!("{}", status);
        if let Err(e) = write_response(&mut $writer, &status).await {
            error!("Failed to respond over socket: {e}");
        }
    }};
}

async fn socket_server(
    disabled_temp: Arc<AtomicBool>,
    disabled_gamma: Arc<AtomicBool>,
    // this is used for notifying the backend that it should update the dimming
    notify: Arc<Notify>,
) -> ! {
    let listener = UnixListener::bind(get_socket_path()).expect("Failed to bind socket");

    match std::fs::set_permissions(get_socket_path(), std::fs::Permissions::from_mode(0o600)) {
        Ok(()) => {
            trace!("socket file permissions set");
        },
        Err(e) => {
            error!("Failed to set socket file permissions: {e}");
        },
    }

    trace!("socket server bound");
    let notification: NotifyState =
        hinoirisetr::notify::InitializedNotificationSystem::new("hinoirisetr").map_or_else(
            |_| {
                info!("libnotify not found, disabling 'status_notify' command");
                NotifyState::Disabled
            },
            NotifyState::Enabled,
        );

    let disabler_notify = Arc::new(Notify::new());

    loop {
        let (mut stream, _) = listener.accept().await.unwrap();
        let (reader, mut writer) = stream.split();
        let mut lines = BufReader::new(reader).lines();

        trace!("socket server accepted connection");

        if let Ok(Some(line)) = lines.next_line().await {
            let config = get_config().await;
            if config.disable_timeout > 0 {
                match line.trim() {
                    "toggle" | "toggle_gamma" | "toggle_temp" | "disable" | "disable_gamma"
                    | "disable_temp" => {
                        let disabled_temp = disabled_temp.clone();
                        let disabled_gamma = disabled_gamma.clone();
                        let notification = notification.clone();
                        let notify = notify.clone();
                        let disabler_notify = disabler_notify.clone();
                        if !disabled_gamma.load(Ordering::SeqCst)
                            && !disabled_temp.load(Ordering::SeqCst)
                        {
                            tokio::spawn(async move {
                                let seconds = config.disable_timeout;
                                trace!("waiting {seconds} seconds before enabling the sunset");
                                tokio::select! {
                                    () = sleep(Duration::from_secs(seconds.into())) => {
                                        trace!("disable timeout");

                                        let status = format!(
                                            "it's been {seconds} seconds since you disabled the sunset; enabling it back"
                                        );

                                        disabled_temp.store(false, Ordering::SeqCst);
                                        disabled_gamma.store(false, Ordering::SeqCst);
                                        notify.notify_one();

                                        info!("{}", status);

                                        if let NotifyState::Enabled(ref not) = notification {
                                            let timeout = config.notification_timeout;
                                            match not.show_notification(
                                                "Too long without sunset",
                                                &status,
                                                "notification-icon",
                                                timeout as i32,
                                            ) {
                                                Ok(()) => {}
                                                Err(e) => {
                                                    error!("Failed to show notification: {e:?}");
                                                }
                                            }
                                        }
                                    },
                                    () = disabler_notify.notified() => {
                                        trace!("disabler_notify notified, canceling the sleeper");
                                    },
                                }
                            });
                        }
                    },
                    _ => {},
                }
            }

            match line.trim() {
                "disable_temp" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |flag| flag.store(true, Ordering::SeqCst),
                        |_| {},
                        "temp dimming is disabled",
                        "disable_temp dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "disable_gamma" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |_| {},
                        |flag| flag.store(true, Ordering::SeqCst),
                        "gamma dimming is disabled",
                        "disable_gamma dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "disable" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |flag| flag.store(true, Ordering::SeqCst),
                        |flag| flag.store(true, Ordering::SeqCst),
                        "dimming is disabled",
                        "disable dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "enable_temp" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |flag| flag.store(false, Ordering::SeqCst),
                        |_| {},
                        "temp dimming is enabled",
                        "enable_temp dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "enable_gamma" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |_| {},
                        |flag| flag.store(false, Ordering::SeqCst),
                        "gamma dimming is enabled",
                        "enable_gamma dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "enable" => {
                    handle_flag_update(
                        &disabled_temp,
                        &disabled_gamma,
                        |flag| flag.store(false, Ordering::SeqCst),
                        |flag| flag.store(false, Ordering::SeqCst),
                        "dimming is enabled",
                        "enable dispatched",
                        &notify,
                        &mut writer,
                    )
                    .await;
                },
                "toggle_temp" => {
                    toggle_flag!(
                        disabled_temp,
                        notify,
                        writer,
                        "temp",
                        "toggle_temp dispatched"
                    );
                },
                "toggle_gamma" => {
                    toggle_flag!(
                        disabled_gamma,
                        notify,
                        writer,
                        "gamma",
                        "toggle_gamma dispatched"
                    );
                },
                "toggle" => {
                    let new_val = !disabled_temp.load(Ordering::SeqCst)
                        && !disabled_gamma.load(Ordering::SeqCst);
                    disabled_temp.store(new_val, Ordering::SeqCst);
                    disabled_gamma.store(new_val, Ordering::SeqCst);
                    notify.notify_one();
                    let status = format!(
                        "dimming is now {}",
                        if new_val { "disabled" } else { "enabled" }
                    );
                    info!("{}", status);
                    if let Err(e) = write_response(&mut writer, &status).await {
                        error!("Failed to respond over socket: {e}");
                    }
                },
                "status" => {
                    trace!("status dispatched");
                    let now = get_time();
                    let config = get_config().await;
                    let status = get_status_string(now, &config, &disabled_temp, &disabled_gamma);
                    info!("{}", status);
                    if let Err(e) = write_response(&mut writer, &status).await {
                        error!("Failed to respond over socket: {e}");
                    }
                },
                "reload" => {
                    trace!("reload dispatched");

                    let result = reload_config(notify.clone()).await;
                    let status = match result {
                        Ok(()) => "reloaded config".into(),
                        Err(e) => format!("failed to reload config: {e}"),
                    };

                    if let Err(e) = write_response(&mut writer, &status).await {
                        error!("Failed to respond over socket: {e}");
                    }

                    trace!("reload completed");
                },
                // kinda a hack? around the fact that the backend doesn't update on monitor connect/disconnect
                "reload_full" => {
                    trace!("reload_full dispatched");

                    #[cfg(feature = "wayland-backend")]
                    hinoirisetr::backend::kill_wayland_thread();

                    let result = reload_config(notify.clone()).await;
                    let status = match result {
                        Ok(()) => "reloaded config".into(),
                        Err(e) => format!("failed to reload config: {e}"),
                    };

                    if let Err(e) = write_response(&mut writer, &status).await {
                        error!("Failed to respond over socket: {e}");
                    }

                    trace!("reload_full completed");
                },
                "status_notify" => {
                    trace!("status_notify dispatched");

                    let now = get_time();
                    let config = get_config().await;
                    let status = get_status_string(now, &config, &disabled_temp, &disabled_gamma);

                    let command_status = match notification {
                        NotifyState::Enabled(ref not) => {
                            let timeout = config.notification_timeout;
                            match not.show_notification(
                                "Sunsetting",
                                &status,
                                "notification-icon",
                                timeout as i32,
                            ) {
                                Ok(()) => "notify notification sent".into(),
                                Err(e) => {
                                    error!("Failed to show notification: {e:?}");
                                    format!("Failed to show notification: {e:?}")
                                },
                            }
                        },
                        NotifyState::Disabled => "notify notification disabled".into(),
                    };

                    if let Err(e) = write_response(&mut writer, &command_status).await {
                        error!("Failed to respond over socket: {e}");
                    }
                },
                _ => error!("unknown command: {}", line.trim()),
            }

            if config.disable_timeout > 0 {
                match line.trim() {
                    "toggle" | "toggle_gamma" | "toggle_temp" | "enable" | "enable_gamma"
                    | "enable_temp"
                        if !disabled_temp.load(Ordering::SeqCst)
                            && !disabled_gamma.load(Ordering::SeqCst) =>
                    {
                        trace!("already enabled sunset back, notifying the sleeper");
                        disabler_notify.notify_waiters();
                    },
                    _ => {},
                }
            }
        }
    }
}

async fn send_command(command: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut stream = tokio::net::UnixStream::connect(get_socket_path()).await?;
    let (reader, mut writer) = stream.split();
    let mut lines = BufReader::new(reader).lines();

    writer.write_all(command.as_bytes()).await?;
    writer.shutdown().await?;

    println!("{}", lines.next_line().await?.unwrap_or(String::new()));

    Ok(())
}

fn suggest<'a>(input: &str, cmds: &'a [&str], min_score: f64) -> Option<&'a str> {
    use strsim::jaro_winkler;

    cmds.iter()
        .map(|cmd| (*cmd, jaro_winkler(input, cmd)))
        .filter(|(_, dist)| *dist >= min_score)
        .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
        .map(|(cmd, _)| cmd)
}

const COMMANDS: &[&str] = &[
    "help",
    "version",
    "reload",
    "reload_full",
    "status",
    "status_notify",
    "enable",
    "disable",
    "toggle",
    "enable_temp",
    "disable_temp",
    "toggle_temp",
    "enable_gamma",
    "disable_gamma",
    "toggle_gamma",
];

const MIN_COMMAND_SCORE: f64 = 0.85;

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().collect();

    match env::var("RUST_LOG") {
        Ok(val) => match val.parse::<hinoirisetr::log::LogLevel>() {
            Ok(level) => hinoirisetr::log::set_log_level(level),
            Err(err) => error!("Failed to parse RUST_LOG: {err}"),
        },
        Err(_) => {
            if cfg!(debug_assertions) {
                hinoirisetr::log::set_log_level(hinoirisetr::log::LogLevel::Debug);
            } else {
                hinoirisetr::log::set_log_level(hinoirisetr::log::LogLevel::Info);
            }
        },
    }

    if args.len() >= 2 {
        match args[1].as_str() {
            "--version" | "-v" | "version" => {
                println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
            },
            "help" | "--help" | "-h" => {
                println!("Available commands:");
                println!("  help          - this message");
                println!("  version       - print version");
                println!("  reload        - reload config file");
                println!("  reload_full   - reload config file and restart the backend threads");
                println!("  status        - print current status");
                println!("  status_notify - send desktop notification with current status");
                println!("  enable        - enable automatic adjustments");
                println!("  disable       - disable automatic adjustments");
                println!("  toggle        - toggle automatic adjustments");
                println!("  enable_temp   - enable temperature adjustments");
                println!("  disable_temp  - disable temperature adjustments");
                println!("  toggle_temp   - toggle temperature adjustments");
                println!("  enable_gamma  - enable gamma adjustments");
                println!("  disable_gamma - disable gamma adjustments");
                println!("  toggle_gamma  - toggle gamma adjustments");
            },
            cmd => {
                let error_prefix = match cmd {
                    "reload" | "reload_full" => Some("Failed to reload config: "),
                    "status_notify" => Some("Failed to send notification: "),
                    "status" | "toggle" | "toggle_gamma" | "toggle_temp" | "enable"
                    | "enable_gamma" | "enable_temp" | "disable" | "disable_gamma"
                    | "disable_temp" => Some("Failed to send status: "),
                    _ => None,
                };

                if std::path::Path::new(&get_socket_path()).exists()
                    && std::os::unix::net::UnixStream::connect(get_socket_path()).is_ok()
                {
                    if let Some(prefix) = error_prefix {
                        if let Err(e) = send_command(cmd).await {
                            eprintln!("{prefix}{e}");
                        }
                    } else if let Some(suggestion) = suggest(cmd, COMMANDS, MIN_COMMAND_SCORE) {
                        eprintln!("Unknown command: '{cmd}'. Did you mean '{suggestion}'.");
                    } else {
                        eprintln!("Unknown command: '{cmd}'. Use 'help' for help.");
                    }
                } else {
                    eprintln!("Socket file not found, daemon not running, exiting.");
                    std::process::exit(1);
                }
            },
        }
        return;
    }

    info!("starting the daemon");

    let disabled_temp = Arc::new(AtomicBool::new(false));
    let disabled_gamma = Arc::new(AtomicBool::new(false));
    let notify = Arc::new(Notify::new());

    // load config
    let config_path = get_config_path();
    let cfg: Config = if config_path.exists() {
        debug!("Config file found, loading...");
        LAST_MODIFIED.store(
            std::fs::metadata(&config_path)
                .and_then(|m| m.modified())
                .map(|t| t.duration_since(UNIX_EPOCH).unwrap().as_secs())
                .unwrap_or(0),
            SeqCst,
        );
        match Config::load(&config_path) {
            Ok(cfg) => cfg,
            Err(err) => {
                error!("Failed to load config: {err:?}");
                warn!("Using default config.");
                Config::default()
            },
        }
    } else {
        warn!("Config file not found, using default config.");
        warn!("Config path {}", config_path.display());

        use std::io::Write;

        match std::fs::File::create(&config_path) {
            Ok(cfg_file) => {
                let mut cfg_writer = std::io::BufWriter::new(cfg_file);
                if let Err(e) = write!(cfg_writer, "{}", Config::default_as_str()) {
                    error!("Failed to write default config: {e}");
                }
            },
            Err(e) => {
                error!("Failed to create config file: {e}");
            },
        }

        Config::default()
    };

    fn check_binary(binary: &str) {
        if !is_binary_available(binary) {
            error!("{binary} is not available, exiting.");
            std::process::exit(1);
        }
    }

    for backend in cfg.gamma_backend.iter() {
        match backend {
            GammaBackend::Hyprctl => check_binary("hyprctl"),
            GammaBackend::Ddcutil => check_binary("ddcutil"),
            GammaBackend::Xsct => check_binary("xsct"),
            GammaBackend::ACPI => {},
            #[cfg(feature = "wayland-backend")]
            GammaBackend::Wayland => {},
            GammaBackend::None => {},
        }
    }

    for backend in cfg.temp_backend.iter() {
        match backend {
            TempBackend::Hyprctl => check_binary("hyprctl"),
            TempBackend::Xsct => check_binary("xsct"),
            #[cfg(feature = "wayland-backend")]
            TempBackend::Wayland => {},
            TempBackend::None => {},
        }
    }

    if cfg.temp_backend.iter().all(|b| *b == TempBackend::None)
        && cfg.gamma_backend.iter().all(|b| *b == GammaBackend::None)
    {
        error!("No backends selected, exiting.");
        std::process::exit(1);
    }

    CONFIG.set(Arc::new(RwLock::new(cfg))).unwrap();

    if std::path::Path::new(&get_socket_path()).exists() {
        if std::os::unix::net::UnixStream::connect(get_socket_path()).is_ok() {
            error!("Another instance is running.");
            std::process::exit(1);
        } else {
            warn!("Stale socket found, removing.");
            let _ = std::fs::remove_file(get_socket_path());
        }
    }

    // Spawn control socket server
    {
        let disabled_temp = Arc::clone(&disabled_temp);
        let disabled_gamma = Arc::clone(&disabled_gamma);
        let notify = Arc::clone(&notify);
        tokio::spawn(async move {
            socket_server(disabled_temp, disabled_gamma, notify).await;
        });
    }

    // Spawn config reloader
    {
        let notify = Arc::clone(&notify);
        tokio::spawn(async move {
            config_reloader(notify).await;
        });
    }

    // Spawn timer
    {
        let notify = Arc::clone(&notify);
        tokio::spawn(async move {
            loop {
                let config = get_config().await;
                let target =
                    SystemTime::now() + Duration::from_secs(config.adjustment_frequency.into());
                loop {
                    let now = SystemTime::now();
                    if now >= target {
                        break;
                    }
                    let remaining = target.duration_since(now).unwrap_or_default();
                    let chunk = remaining.min(Duration::from_secs(1));
                    sleep(chunk).await;
                }
                notify.notify_one();
            }
        });
    }

    // Signal handling
    let mut sigint = signal(SignalKind::interrupt()).unwrap();
    let mut sigterm = signal(SignalKind::terminate()).unwrap();

    // set initial settings
    {
        let now = get_time();
        let config = get_config().await;
        #[cfg(feature = "wayland-backend")]
        hinoirisetr::backend::update_wayland_thread(&config);
        let (temp, gamma) = compute_settings(now, &config);
        apply_temp(temp, &config.temp_backend);
        apply_gamma(gamma, &config.gamma_backend);
        trace!("initial settings applied: {temp}K, {gamma}%");
    }

    // Main loop with shutdown support
    tokio::select! {
        _ = async {
            loop {
                let now = get_time();
                let config = get_config().await;

                #[cfg(feature = "wayland-backend")]
                hinoirisetr::backend::update_wayland_thread(&config);

                let (temp, gamma) = compute_settings(now, &config);
                if disabled_temp.load(Ordering::SeqCst) {
                    apply_temp(
                        config.temp_day,
                        &config.temp_backend,
                    );
                } else {
                    apply_temp(temp, &config.temp_backend);
                }
                if disabled_gamma.load(Ordering::SeqCst) {
                    apply_gamma(
                        config.gamma_day,
                        &config.gamma_backend,
                    );
                } else {
                    apply_gamma(gamma, &config.gamma_backend);
                }

                notify.notified().await;
        }} => {},
        _ = sigint.recv() => {
            info!("Received SIGINT, shutting down...");
        },
        _ = sigterm.recv() => {
            info!("Received SIGTERM, shutting down...");
        },
    }

    // Cleanup the socket file on shutdown
    if std::path::Path::new(&get_socket_path()).exists() {
        match std::fs::remove_file(get_socket_path()) {
            Ok(()) => info!("Socket file {} removed.", get_socket_path().display()),
            Err(e) => warn!(
                "Failed to remove socket file {}: {e}",
                get_socket_path().display()
            ),
        }
    }
}

// Function to handle config reloading
async fn reload_config(notify: Arc<Notify>) -> Result<(), ConfigError> {
    trace!("reload_config called");
    let config_handle = config_handle();
    let config_path = get_config_path();
    match Config::load(&config_path) {
        Ok(cfg) => {
            debug!("Config file reloaded successfully");

            fn check_binary(binary: &str) -> String {
                if !is_binary_available(binary) {
                    error!("{binary} is not available, exiting.");
                    return binary.to_string();
                }
                String::new()
            }

            for backend in cfg.gamma_backend.iter().zip(cfg.temp_backend.iter()) {
                let gamma_check = match backend.0 {
                    GammaBackend::Hyprctl => check_binary("hyprctl"),
                    GammaBackend::Ddcutil => check_binary("ddcutil"),
                    GammaBackend::Xsct => check_binary("xsct"),
                    GammaBackend::ACPI => String::new(),
                    #[cfg(feature = "wayland-backend")]
                    GammaBackend::Wayland => String::new(),
                    GammaBackend::None => String::new(),
                };

                let temp_check = match backend.1 {
                    TempBackend::Hyprctl => check_binary("hyprctl"),
                    TempBackend::Xsct => check_binary("xsct"),
                    #[cfg(feature = "wayland-backend")]
                    TempBackend::Wayland => String::new(),
                    TempBackend::None => String::new(),
                };

                if !gamma_check.is_empty() || !temp_check.is_empty() {
                    error!("One or more binaries are not available, retaining old config.");
                    return Err(ConfigError::UnavailableCommand(format!(
                        "binaries {gamma_check} {temp_check} are not available"
                    )));
                }
            }

            *config_handle.write().await = cfg;
            reset_cache();

            let new_modified = std::fs::metadata(&config_path)
                .and_then(|m| m.modified())
                .map(|t| t.duration_since(UNIX_EPOCH).unwrap().as_secs())
                .unwrap_or(0);
            trace!("new_modified: {new_modified:?}");
            LAST_MODIFIED.store(new_modified, SeqCst);
            notify.notify_one();
            Ok(())
        },
        Err(err) => {
            error!("Failed to reload config: {err:?}");
            warn!("Retaining current config");
            Err(err)
        },
    }
}

fn is_binary_available(binary_name: &str) -> bool {
    use std::fs;
    if let Ok(paths) = env::var("PATH") {
        for path in env::split_paths(&paths) {
            let full_path = path.join(binary_name);
            if full_path.exists()
                && fs::metadata(&full_path)
                    .map(|m| m.is_file())
                    .unwrap_or(false)
            {
                return true;
            }
        }
    }
    false
}

#[inline]
fn get_config_path() -> PathBuf {
    let xdg_config_home = env::var("XDG_CONFIG_HOME").ok();
    let home = env::var("HOME").ok();
    let user = env::var("USER").unwrap_or_else(|_| "default".to_string());

    xdg_config_home
        .map(|x| PathBuf::from(format!("{x}/hinoirisetr.toml")))
        .or_else(|| home.map(|h| PathBuf::from(format!("{h}/.config/hinoirisetr.toml"))))
        .unwrap_or_else(|| PathBuf::from(format!("/home/{user}/.config/hinoirisetr.toml")))
}

async fn get_config() -> Config {
    *CONFIG.get().expect("config not init").read().await
}

fn config_handle() -> Arc<RwLock<Config>> {
    CONFIG.get().expect("config not init").clone()
}

// async fn get_config() -> Config {
//     let lock = CONFIG.get().expect("config not initialized").read().await;
//     lock.clone()
// }

fn get_time() -> OffsetDateTime {
    OffsetDateTime::now_local().expect("Failed to get local time")
}