# Pull everywhere; enable push only on the host that runs `nixos-rebuild --target-host` (needs sops `cachix/auth-token`).
{ inputs, ... }: {
  flake.nixosModules.systemCachingCachix =
    { config, lib, pkgs, ... }:
    let
      cfg = config.chiasson.system.caching.cachix;
    in
    {
      imports = [ inputs.sops-nix.nixosModules.sops ];

      options.chiasson.system.caching.cachix = with lib; {
        enable = mkOption {
          type = types.bool;
          default = false;
          description = "Enable Cachix cache integration for this host.";
        };

        cacheName = mkOption {
          type = types.str;
          default = "";
          example = "chiasson-nixosnew";
          description = "Your Cachix cache name (from app.cachix.org). Leave empty to disable.";
        };
        publicKey = mkOption {
          type = types.str;
          default = "";
          example = "chiasson-nixosnew.cachix.org-1:xxxx=";
          description = "Public key for the cache (shown on the cache page).";
        };
        enablePush = mkOption {
          type = types.bool;
          default = false;
          description = "Push every build to Cachix (enable only on the machine that runs nixos-rebuild --target-host).";
        };
        pushExcludePatterns = mkOption {
          type = types.listOf types.str;
          default = [ ];
          example = [ "wallpaper" "hm_wallpapers" ".iso" "-source" "large-assets" ];
          description = "Substring patterns: store paths containing any of these are not pushed to Cachix (saves cache space for heavy outputs).";
        };
      };

      config = let
        enabled = cfg.enable && cfg.cacheName != "" && cfg.publicKey != "";
        cacheUrl = "https://${cfg.cacheName}.cachix.org";
      in
      lib.mkMerge [
        (lib.mkIf enabled {
          nix.settings = {
            substituters = lib.mkAfter [ cacheUrl ];
            trusted-public-keys = lib.mkAfter [ cfg.publicKey ];
          };
        })
        (lib.mkIf (enabled && cfg.enablePush) {
          nix.settings.post-build-hook = pkgs.writeShellScript "upload-to-cachix" ''
            set -eu
            set -f
            token_path="${config.sops.secrets."cachix/auth-token".path}"
            if [ ! -r "$token_path" ]; then
              echo "cachix: skipping push (token not readable at $token_path)" >&2
              exit 0
            fi
            export PATH="${lib.makeBinPath [ pkgs.cachix ]}:$PATH"
            export CACHIX_AUTH_TOKEN=$(cat "$token_path")

            push_paths=""
            skipped_roots=0
            pushed_roots=0
            for path in $OUT_PATHS; do
              skip=0
              skip_reason=""

              closure_paths="$(nix-store -qR "$path" 2>/dev/null || true)"
              for candidate in "$path" $closure_paths; do
                while IFS= read -r pat; do
                  pat="$(printf '%s' "$pat" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
                  [ -z "$pat" ] && continue
                  case "$candidate" in
                    *"$pat"*)
                      skip=1
                      skip_reason="$pat ($candidate)"
                      break
                      ;;
                  esac
                done << 'EXCLUDE_PATTERNS'
            ${lib.concatStringsSep "\n" cfg.pushExcludePatterns}
            EXCLUDE_PATTERNS
                if [ "$skip" -eq 1 ]; then
                  break
                fi
              done

              if [ "$skip" -eq 0 ]; then
                push_paths="$push_paths $path"
                pushed_roots=$((pushed_roots + 1))
              else
                skipped_roots=$((skipped_roots + 1))
                echo "cachix: skipping root $path (matches exclude pattern via $skip_reason)" >&2
              fi
            done

            echo "cachix: root paths selected for push: $pushed_roots, skipped: $skipped_roots" >&2

            if [ -n "$push_paths" ]; then
              if ! cachix push ${lib.escapeShellArg cfg.cacheName} $push_paths; then
                echo "cachix: push failed (build succeeded; check token/network)" >&2
              fi
            fi
            exit 0
          '';

          sops.secrets."cachix/auth-token" = {
            owner = "root";
            group = "root";
            mode = "0400";
          };
        })
      ];
    };
}
