{
  pkgs,
  inputs,
  config,
  ...
}:

let
  ncSecret = key: {
    sopsFile = ../secrets/nc.yaml;
    inherit key;
    owner = "mizuki-nc";
    group = "mizuki-nc";
    mode = "0400";
  };
in
{
  users.users.mizuki-nc = {
    isSystemUser = true;
    group = "mizuki-nc";
  };

  users.groups.mizuki-nc = { };

  sops.secrets."google/api-key" = ncSecret "google/api-key";

  systemd.services.mizuki-nc = {
    description = "mizuki.guru";
    wantedBy = [ "multi-user.target" ];

    preStart = ''
      set -eu
      umask 077

      rm -f /var/lib/mizuki-nc/config.toml

      cat > /tmp/mizuki-nc-config.toml <<EOF
[google]
api-key = "$(cat ${config.sops.secrets."google/api-key".path})"
EOF

      install -o mizuki-nc -g mizuki-nc -m 0400 \
        /tmp/mizuki-nc-config.toml \
        /var/lib/mizuki-nc/config.toml

      rm -f /tmp/mizuki-nc-config.toml
    '';

    serviceConfig = {
      User = "mizuki-nc";
      Group = "mizuki-nc";

      StateDirectory = "mizuki-nc";
      StateDirectoryMode = "0750";
      WorkingDirectory = "/var/lib/mizuki-nc";

      ExecStart = "${inputs.mizuki-nc.packages.${pkgs.system}.default}/bin/mizuki-nc";

      Restart = "always";
      RestartSec = 3;
    };
  };
}
