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

with lib;

let
  cfg = config.athenix.sw;
  builderCfg = cfg.builders;
in
mkIf builderCfg.giteaRunner.enable {
  services.gitea-actions-runner.instances.${builderCfg.giteaRunner.name} = {
    enable = true;
    url = builderCfg.giteaRunner.url;
    tokenFile = builderCfg.giteaRunner.tokenFile;
    labels = builderCfg.giteaRunner.extraLabels;
    name = builderCfg.giteaRunner.name;

    # Run as engr-ugaif user to access SSH keys
    settings = {
      runner = {
        user = "engr-ugaif";
      };
    };
  };

  # Configure the systemd service for better handling in LXC containers
  systemd.services."gitea-runner-${builderCfg.giteaRunner.name}" = {
    unitConfig = {
      # Only start the service if token file exists
      # This allows graceful deployment before the token is manually installed
      ConditionPathExists = builderCfg.giteaRunner.tokenFile;
    };
    serviceConfig = {
      # Run as engr-ugaif user
      User = mkForce "engr-ugaif";
      Group = mkForce "users";

      # Give the service more time to stop cleanly
      TimeoutStopSec = mkForce 60;

      # Add Node.js and other tools to PATH for GitHub Actions compatibility
      Environment = [
        "PATH=${pkgs.nodejs}/bin:${pkgs.bash}/bin:${pkgs.coreutils}/bin:${pkgs.git}/bin:${pkgs.nix}/bin:/run/current-system/sw/bin"
        "HOME=/home/engr-ugaif"
      ];

      # Disable all namespace isolation features that don't work in LXC containers
      # Remove systemd security features that conflict with home directory access
      DynamicUser = mkForce false;
      PrivateMounts = mkForce false;
      MountAPIVFS = mkForce false;
      BindPaths = mkForce [ ];
      BindReadOnlyPaths = mkForce [ ];
      ReadWritePaths = mkForce [ ];
      ReadOnlyPaths = mkForce [ ];
      InaccessiblePaths = mkForce [ ];
      PrivateTmp = mkForce false;
      PrivateDevices = mkForce false;
      ProtectSystem = mkForce false;
      ProtectHome = mkForce false;
      PrivateUsers = mkForce false;
      ProtectKernelTunables = mkForce false;
      ProtectKernelModules = mkForce false;
      ProtectControlGroups = mkForce false;
      RestrictAddressFamilies = mkForce [ ];
      SystemCallFilter = mkForce [ ];
    };
  };
}
