{ config, lib, pkgs, ... }:
let
  cfg = config.services.dwierz;
  dwierz = import (pkgs.fetchgit {
    url = "https://git.morj.men/morj/annshalom";
    deepClone = false;
    leaveDotGit = false;
    rev = "24e19241f2292cf6fd02de43ba47fd3715047d29";
    hash = "sha256-WZJVybLLdmPYXMNRJeJKGXAIdlIxdYfgpjxaHKpbFKQ=";
  }) { inherit pkgs; };
in {
  options.services.dwierz = {
    enable = lib.mkEnableOption "dwierz";
    services = lib.mkOption {
      type = lib.types.str;
      default = "{}";
      description = lib.mdDoc ''
        Configuration of services in RON format
      '';
      example = ''
        {
          "jellyfin.local": (
              port: 8096,
              title: "Jellyfin",
              description: "Media player",
              icon: "jellyfin.svg",
          ),
        }
      '';
    };
    staticPath = lib.mkOption {
      type = lib.types.str;
      default = "/var/empty/dwierz";
      description = lib.mdDoc ''
        Path to static files used in the portal. Filetype detection in portal is very limited.
      '';
    };
    port = lib.mkOption {
      type = lib.types.port;
      default = 80;
      description = lib.mdDoc ''
        Port to listen on. Anything other than 80 won't work without debug mode.
      '';
    };
    bindAddress = lib.mkOption {
      type = lib.types.str;
      default = "*";
      description = lib.mdDoc ''
        Host to bind to, in the weird warp format where * means any ipv4 and ipv6.
      '';
    };
    user = lib.mkOption {
      type = lib.types.str;
      default = "root";
      example = "yourUser";
      description = lib.mdDoc ''
        The user to service as. Recommended option: administrator user.
      '';
    };
    group = lib.mkOption {
      type = lib.types.str;
      default = "root";
      example = "yourGroup";
      description = lib.mdDoc ''
        The group to service as. Recommended option: administrator group.
      '';
    };
  };
  config = lib.mkIf cfg.enable {
    systemd.packages = [dwierz];
    systemd.services.dwierz = {
      description = "Local services annoucer and server";
      after = [ "avahi-daemon.service" ];
      requires = [ "avahi-daemon.service" ];
      wantedBy = ["multi-user.target"];
      serviceConfig = {
        User = cfg.user;
        Group = cfg.group;
        ExecStart = ''${dwierz}/bin/dwierz \
          --port=${toString cfg.port} \
          --bind=${cfg.bindAddress} \
          --static=${cfg.staticPath} \
          --services=${pkgs.writeText "services.ron" cfg.services}
        '';
      };
    };
  };
}