{ lib, config, pkgs, ... }:

let
  cfg = config.snowhawk.redshift;
  cfgDir = config.xdg.configHome + "/redshift";

  sops = config.snowhawk.sops.enable;
in
{
  options.snowhawk.redshift = {
    enable = lib.mkEnableOption "redshift home-manager module";
  };

  config = lib.mkIf cfg.enable {
    systemd.user.services.redshift = {
      Unit = {
        Description = "redshift service";
        PartOf = [ "graphical-session.target" ];
        After = lib.mkIf sops [ "sops-nix.service" ];
      };
      Service = {
        Type = "exec";
        ExecStart =
          let
            catFile = file: "\$(${pkgs.coreutils}/bin/cat ${file})";
            toPaths = deg: "${cfgDir}/${deg}";
            fetchLatLon = lib.right
              (lib.strings.concatStringsSep ":")
              (map catFile)
              (map toPaths)
              [ "lat" "lon" ];
          in
          ''${pkgs.bash}/bin/bash -c "${pkgs.redshift}/bin/redshift -l ${fetchLatLon}"'';
      };
      Install.WantedBy = [ "graphical-session.target" ];
    };

    sops.secrets = lib.mkIf sops {
      "locations/snowhawk/lat".path = "${cfgDir}/lat";
      "locations/snowhawk/lon".path = "${cfgDir}/lon";
    };

    home.packages = with pkgs; [
      redshift
    ];
  };
}