{ config, pkgs, lib, ... }:
let
  cfg = config.services.gitea-themes;
  giteaCfg = config.services.gitea;
in
{
  options.services.gitea-themes = lib.mkOption {
    description = ''
      Derivations containing gitea themes to install.

      The theme should be named `theme-<name>.css`, and reside in `$out/share/gitea/public/assets/css/`.
    '';
    default = { };
    type = with lib.types; attrsOf path;
  };

  config = lib.mkIf (cfg != { }) {
    services.gitea.settings.ui.THEMES = lib.strings.concatStringsSep "," ([
      "gitea"
      "arc-green"
    ] ++ (lib.concatMap (drv: drv.passthru.gitea-themes) (lib.attrValues cfg)));

    systemd.services.install-gitea-themes = {
      description = "Install gitea themes in gitea's CUSTOM_DIR";
      wantedBy = [ "gitea.service" ];
      requiredBy = [ "gitea.service" ];
      restartTriggers = lib.attrValues cfg;

      serviceConfig =  {
        Type = "oneshot";
        User = giteaCfg.user;
        Group = giteaCfg.group;
      };
      script = lib.concatMapStringsSep "\n" ({ name, value }: ''
        install -Dm444 "${value}"/share/gitea/public/assets/css/*.css -t "${giteaCfg.customDir}/public/assets/css/"
      '') (lib.attrsToList cfg);
    };
  };
}