{ pkgs, lib, fluxLocal, ... }:

with pkgs;

writeShellApplication rec {
  name = "flux-diff";

  runtimeInputs = [ fluxLocal ];

  text = ''
    #!/usr/bin/env bash
    set -euo pipefail

    # Ensure flux-local is available
    export PATH="${fluxLocal}/bin:$PATH"

    # Default values for inputs
    PATH_INPUT="''${PATH_INPUT:-kubernetes}"
    RESOURCE="''${RESOURCE:-kustomization}"
    LIVE_BRANCH_DIR="''${LIVE_BRANCH_DIR:-./workspace/default}"
    PR_BRANCH_DIR="''${PR_BRANCH_DIR:-./workspace/pull}"
    DIFF_LINES="''${DIFF_LINES:-6}"
    STRIP_ATTRS="''${STRIP_ATTRS:-helm.sh/chart,checksum/config,app.kubernetes.io/version,chart}"
    LIMIT_BYTES="''${LIMIT_BYTES:-10000}"
    SKIP_SECRETS="''${SKIP_SECRETS:-true}"
    SKIP_CRDS="''${SKIP_CRDS:-true}"
    KUSTOMIZE_BUILD_FLAGS="''${KUSTOMIZE_BUILD_FLAGS:-}"
    SOURCES="''${SOURCES:-}"
    API_VERSIONS="''${API_VERSIONS:-}"
    DEBUG="''${DEBUG:-false}"

    # Adjust log level based on debug input
    if [[ "$DEBUG" == "true" ]]; then
      LOG_LEVEL="DEBUG"
    else
      LOG_LEVEL="INFO"
    fi

    # Additional flags for helmrelease resources
    EXTRA_FLAGS=""
    if [[ "$RESOURCE" == "helmrelease" && -n "$API_VERSIONS" ]]; then
      EXTRA_FLAGS="--api-versions=$API_VERSIONS"
    fi

    # Adjust skip flags
    if [[ "$SKIP_SECRETS" == "true" ]]; then
      SKIP_SECRETS_FLAG="--skip-secrets"
    else
      SKIP_SECRETS_FLAG="--no-skip-secrets"
    fi

    if [[ "$SKIP_CRDS" == "true" ]]; then
      SKIP_CRDS_FLAG="--skip-crds"
    else
      SKIP_CRDS_FLAG="--no-skip-crds"
    fi

    # Loop over paths and resources
    for path in $PATH_INPUT; do
      diff_file="diff-$path-$RESOURCE.patch"

      flux-local \
        --log-level "$LOG_LEVEL" \
        diff "$RESOURCE" \
        --unified "$DIFF_LINES" \
        --path "$PR_BRANCH_DIR/$path" \
        --path-orig "$LIVE_BRANCH_DIR/$path" \
        --strip-attrs "$STRIP_ATTRS" \
        $SKIP_SECRETS_FLAG \
        $SKIP_CRDS_FLAG \
        --limit-bytes "$LIMIT_BYTES" \
        --all-namespaces \
        --kustomize-build-flags="$KUSTOMIZE_BUILD_FLAGS" \
        --sources "$SOURCES" \
        --output-file "$diff_file" \
        "$EXTRA_FLAGS"

      # Output the diff if it exists
      if [[ -s "$diff_file" ]]; then
        echo "Differences found for path: $path and resource: $RESOURCE"
        cat "$diff_file"
      else
        echo "No differences found for path: $path and resource: $RESOURCE"
      fi
    done
  '';

  meta = with lib; {
    homepage = "https://code.252.no/tommy/containers";
    description = "Perform Flux diffs locally";
    license = licenses.mit;
    maintainers = with maintainers; [ "tommy-skaug" ];
  };
}