Speed up kubectl commands (and k9s) when using AWS

AWS runs the AWS-CLI every time you run a command using kubectl. It's in your kubeconfig file. I started to notice it and came up with this script to bypass the slow AWS CLI.

#!/usr/bin/env bash
set -euo pipefail

# Build an array of non-flag arguments by iterating over all arguments.
# For any argument starting with "--" that does NOT include "=",
# skip that argument and (if available) its immediate next value.
args=("$@")
nonflag_args=()
i=0
while [ $i -lt "${#args[@]}" ]; do
    arg="${args[$i]}"
    if [[ "$arg" == --* ]]; then
        # If the flag is provided in the form "--flag=value", treat it as one argument.
        if [[ "$arg" != *=* ]]; then
            # Skip this flag and its following value (if any).
            i=$((i+2))
            continue
        fi
    else
        nonflag_args+=("$arg")
    fi
    i=$((i+1))
done

# Check if the first two non-flag arguments are "eks" and "get-token".
if [[ "${nonflag_args[0]:-}" != "eks" || "${nonflag_args[1]:-}" != "get-token" ]]; then
    exec aws "$@"
fi

# Extract the --cluster-name value from the arguments (supports both forms).
CLUSTER_NAME=""
for (( i=0; i < ${#args[@]}; i++ )); do
    case "${args[$i]}" in
        --cluster-name)
            if (( i+1 < ${#args[@]} )); then
                CLUSTER_NAME="${args[$((i+1))]}"
            fi
            ;;
        --cluster-name=*)
            CLUSTER_NAME="${args[$i]#--cluster-name=}"
            ;;
    esac
done

if [[ -z "$CLUSTER_NAME" ]]; then
    echo "Error: --cluster-name not provided." >&2
    exit 1
fi

# Set up the cache directory and file.
CACHE_DIR="${HOME}/.aws/kubetokencache"
CACHE_FILE="${CACHE_DIR}/${CLUSTER_NAME}.json"

# Check if a cached token exists and is valid for at least 30 seconds.
if [[ -f "$CACHE_FILE" ]]; then
    # Extract the expirationTimestamp using jq.
    EXPIRATION=$(jq -r '.status.expirationTimestamp // empty' "$CACHE_FILE")
    if [[ -n "$EXPIRATION" ]]; then
        # Convert the expiration timestamp (ISO 8601) to epoch seconds.
        exp_epoch=$(date -d "$EXPIRATION" +%s 2>/dev/null || date -j -f "%Y-%m-%dT%H:%M:%SZ" "$EXPIRATION" "+%s")
        now_epoch=$(date +%s)
        # If the token remains valid for at least another 30 seconds, output the cached file.
        if (( exp_epoch - now_epoch > 30 )); then
            cat "$CACHE_FILE"
            exit 0
        fi
    fi
fi

# No valid cached token found; run the actual AWS CLI command.
TOKEN_JSON=$(aws "$@")

# Create the cache directory if it doesn't exist.
mkdir -p "$CACHE_DIR"

# Cache the new token.
echo "$TOKEN_JSON" > "$CACHE_FILE"

# Output the token.
echo "$TOKEN_JSON"