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

let
  service = "caddy";
  cfg = config.homelab.${service};
  sec = config.sops.secrets;
  homelab = config.homelab;
in
{
  options.homelab.${service} = {
    enable = lib.mkEnableOption "enables ${service}";

    # set port options
    data_dir = lib.mkOption {
      type = lib.types.str;
      default = "/var/lib/${service}";
      description = "set data directory for ${service}";
    };
    backup = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = "enable backups for ${service}";
    };
    motd = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = service;
    };
  };

  config = lib.mkIf cfg.enable {
    
    # declare ${service} group
    users.groups.${service} = {};

    # declare ${service} user
    users.users.${service} = {
      description = "${service} server user";
      isSystemUser = true;
      home = cfg.data_dir;
      createHome = true;
      group = service;
      extraGroups = [];
    };

    # enable the ${service} service
    services.${service} = {
      enable = true;
      user = service;
      group = service;
      dataDir = cfg.data_dir;
      email = "me@blakedheld.xyz";
      globalConfig = ''
        auto_https ignore_loaded_certs
      '';
      
      virtualHosts."key.${homelab.public_domain}" = {
        extraConfig = ''
            root * /var/www/keys
            file_server
        '';
      };
    };

    # enable acme for auto ssl certs with lets encrypt
    security.acme = {
      acceptTerms = true;
      defaults.email = "me@blakedheld.xyz";
    };

    # override umask to make permissions work out
    systemd.services.${service}.serviceConfig = {
      UMask = lib.mkForce "0007";
    };

    # open firewall
    networking.firewall.allowedTCPPorts = [ 80 443 ];

    sops.secrets = {
      "ssl_blakedheld_crt" = {
        owner = "caddy";
        group = "caddy";
        path = "/etc/ssl/blakedheld.xyz.crt";
      };
      "ssl_blakedheld_key" = {
        owner = "caddy";
        group = "caddy";
        path = "/etc/ssl/blakedheld.xyz.key";
      };
      "klefki_pub.asc" = {
        owner = "caddy";
        group = "caddy";
        path = "/var/www/keys/klefki_pub.asc";
      };
    };
 

    # add to backups
   homelab.backups.baks = {
      ${service} = { paths = [ cfg.data_dir ]; };
    };
  };
}
