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

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

let
  cfg = config.my.forgejo-runner;
in {
  options.my.forgejo-runner = {
    enable = lib.mkEnableOption "forgejo runner";

    enablePodman = lib.mkEnableOption "forgejo runner with Podman labels";

    selfHostedLabels = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [];
    };
  };

  config = lib.mkMerge [
    (lib.mkIf cfg.enable {
      my.vault.secrets.forgejo-runner-environment = {
        restartUnits = ["gitea-runner-${utils.escapeSystemdPath config.services.gitea-actions-runner.instances.depot.name}.service"];
        group = "root";
        template = ''
          {{ with secret "kv/apps/forgejo-runner" }}
          TOKEN={{ .Data.data.TOKEN }}
          {{ end }}
        '';
      };
      services.gitea-actions-runner = {
        package = pkgs.forgejo-runner;
        instances.depot = {
          enable = true;
          name = config.networking.hostName;
          url = "https://git.lukegb.com";
          tokenFile = config.my.vault.secrets.forgejo-runner-environment.path;
          labels = map (label: "${label}:host") cfg.selfHostedLabels;
          hostPackages = with pkgs; [
            bash
            coreutils
            curl
            gawk
            gitMinimal
            gnused
            nodejs
            wget
            lix
            jq
            depot.go.nix.bcacheup
          ];
          settings = {
            runner.capacity = 10;
          };
        };
      };

      nix.gc.automatic = false;
    }) (lib.mkIf (cfg.enable && cfg.enablePodman) {
      services.gitea-actions-runner.instances.depot.labels = lib.mkAfter [
        "debian-latest:docker://node:22-bookworm"
        "lix:docker://git.lix.systems/lix-project/lix:${pkgs.lix.version}"
      ];
      virtualisation.podman = {
        enable = true;
        dockerSocket.enable = true;
      };
    })];
}