# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ pkgs, config, depot, lib, ... }:
let
  inherit (lib) mkOption types mkBefore mkIf;

  cfg = config.my.vault.tokend;
in
{
  options.my.vault.tokend = {
    enable = mkOption {
      type = types.bool;
      default = true;
    };
  };

  config = mkIf cfg.enable {

    users.groups.tokend = {};
    users.users.tokend = { isSystemUser = true; group = "tokend"; };

    systemd.services.tokend = {
      description = "Daemon for dynamically issuing Vault tokens based on connecting UID";
      wants = [ "vault-agent.service" "network.target" ];
      after = [ "network.target" ];
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        User = "tokend";
        SupplementaryGroups = [ "vault-agent" ];
        RuntimeDirectory = "tokend";
        RuntimeDirectoryMode = "0755";

        NoNewPrivileges = true;
        ProtectSystem = "strict";
        ProtectHome = "yes";

        ExecStart = "${depot.go.tokend}/bin/tokend --logtostderr";
      };
    };
  };
}