{
  lib,
  config,
  pkgs,
  ...
}:
let
  cfg = config.khscodes.infrastructure.vault-server-approle;
  userExists =
    username: (builtins.hasAttr username config.users.users) && config.users.users.khs.enable;
  setKhsPassword = pkgs.writeShellApplication {
    name = "set-khs-password";
    runtimeInputs = [
      pkgs.uutils-coreutils-noprefix
    ];
    text = ''
      owner_id="$(stat -c "%u" /run/unix-users/khs)"
      group_id="$(stat -c "%g" /run/unix-users/khs)"

      if [[ "$owner_id" != "0" || "$group_id" != "0" ]]; then
        >&2 echo "Not setting password due to bad ownership"
        exit 1
      fi
      hashed_passwd="$(cat /run/unix-users/khs)"
      /run/current-system/sw/bin/usermod --password "$hashed_passwd" khs
    '';
  };
in
{
  config = lib.mkIf (cfg.enable && (userExists "khs")) {
    khscodes.infrastructure.vault-server-approle.policy = {
      "unix-users/data/khs/password" = {
        capabilities = [ "read" ];
      };
    };
    khscodes.services.vault-agent.templates = [
      {
        contents = ''
          {{- with secret "unix-users/data/khs/password" -}}
          {{ .Data.data.hashedPassword }}
          {{- end -}}
        '';
        destination = "/run/unix-users/khs";
        perms = "0600";
        owner = "root";
        group = "root";
        restartUnits = [ "set-khs-password.service" ];
      }
    ];
    systemd.services.set-khs-password = {
      enable = true;
      unitConfig = {
        ConditionPathExists = "/run/unix-users/khs";
      };
      serviceConfig = {
        Type = "oneshot";
        User = "root";
        Group = "root";
        ExecStart = lib.getExe setKhsPassword;
      };
    };
  };
}
