#!/usr/bin/env bash

# Credit: https://github.com/junegunn/fzf/blob/master/ADVANCED.md

read -ra tokens < <(
  kubectl get pods --all-namespaces |
    fzf --info=inline --layout=reverse --header-lines=1 --border \
        --prompt "$(kubectl config current-context | sed 's/-context$//')> " \
        --header $'Press CTRL-O to open log in editor\n\n' \
        --bind ctrl-/:toggle-preview \
        --bind "ctrl-o:execute:${EDITOR:-vim} <(kubectl logs --namespace {1} {2}) > /dev/tty" \
        --preview-window up,follow \
        --preview 'kubectl logs --follow --tail=100000 --namespace {1} {2}' "$@"
)
[ ${#tokens} -gt 1 ] &&
  kubectl exec -it --namespace "${tokens[0]}" "${tokens[1]}" -- /bin/sh