#!/bin/bash
set -u

watch_mode=false
args=()
for arg in "$@"; do
    if [[ "$arg" == "-w" || "$arg" == "--watch" ]]; then
        watch_mode=true
    else
        args+=("$arg")
    fi
done

render_pods() {
    local q="${1:-}"
    local raw
    if [[ "$q" == "all" || "$q" == "-A" || "$q" == "-a" ]]; then
        raw=$(kubectl get pods -A 2>/dev/null || true)
    else
        if [[ -n "$q" ]]; then
            raw=$(kubectl get pods -A 2>/dev/null | awk -v q="$q" 'NR==1 || tolower($1) ~ tolower(q) || tolower($2) ~ tolower(q)' || true)
        else
            raw=$(kubectl get pods -A 2>/dev/null | awk 'NR==1 || ($1 !~ /^(kube-system|flux-system|cert-manager|external-secrets)$/ && $4 != "Completed")' || true)
        fi
    fi

    echo "$raw" | awk '
    BEGIN {
        ERR  = "\033[38;2;255;46;76m"
        RUN  = "\033[38;2;180;190;254m"
        WARN = "\033[38;2;250;179;135m"
        HEAD = "\033[38;2;147;154;183m"
        RST  = "\033[0m"
    }
    NR==1 {
        print HEAD $0 RST
        next
    }
    {
        if ($0 ~ /CrashLoopBackOff|Error|OOMKilled|ImagePullBackOff/) {
            print ERR $0 RST
        }
        else if ($0 ~ /ContainerCreating|Pending|Terminating|Init:/ || ($0 ~ /Running/ && $2 ~ /^0\//)) {
            print WARN $0 RST
        }
        else if ($0 ~ /Running/) {
            print RUN $0 RST
        }
        else {
            print $0
        }
    }'
}

if [[ "$watch_mode" == true ]]; then
    trap 'tput cnorm 2>/dev/null || true; echo ""; exit 0' INT TERM
    tput civis 2>/dev/null || true
    clear
    while true; do
        tput cup 0 0 2>/dev/null || true
        render_pods "${args[@]:-}"
        tput ed 2>/dev/null || true
        sleep 1
    done
else
    render_pods "${args[@]:-}"
fi
