#!/usr/bin/env bash

source .utils

NAMESPACE="$(kubectl config view --minify --output 'jsonpath={..namespace}' &>/dev/null)"
set -e
NAMESPACE=${NAMESPACE:-default}
POD="kube-ssh"
NODE=""
IMAGE="alpine"

print_usage() {
  blue "kube-ssh - gain access to a Kubernetes host node (ssh-like for when a host doesn't have ssh)"
  echo " "
  underline "Usage:"
  echo "kube-ssh [options]"
  echo " "
  underline "Options:"
  echo "-h, --help            show this help text"
  echo "-n, --namespace       the namespace to launch the pod in"
  echo "-N, --node            the name of the node to access"
  echo "-i, --image           the image to launch for debugging (default: alpine)"
}

while test $# -gt 0; do
  case "$1" in
    -n|--namespace)
      shift
      NAMESPACE=$1
      shift
      ;;
    -N|--node)
      shift
      NODE=$1
      shift
      ;;
    -i|--image)
      shift
      IMAGE=$1
      shift
      ;;
    -h|--help)
      print_usage
      exit 0
      ;;
    *)
      break
      ;;
  esac
done

if [[ "$NODE" == "" ]]; then

  if [ -z "$(which fzf)" ]; then
    NODES=$(kubectl get nodes --no-headers -o custom-columns=name:.metadata.name)
    i=0
    while read -r node; do
      echo "[$i] - $node"
      i=$((i+1))
    done <<< "$NODES"
    read -p "Which node would you like to connect to? " -r
    echo ""
    IFS=$'\n' NODES=($NODES)
    NODE=${NODES[$REPLY]}
  else
    NODES=$(kubectl get nodes)
    NODE=$(echo "$NODES" | _fzf | awk '{print $1}')
  fi
fi

SERVER_VERSION=$(kubectl version --client=false -o json 2>/dev/null | jq -r '.serverVersion.minor')

if [ ${SERVER_VERSION} -ge 22 ]; then
  kubectl debug node/${NODE} -it --image ${IMAGE}
else
  NODE_NAME=$(kubectl get node $NODE -o template --template='{{index .metadata.labels "kubernetes.io/hostname"}}')
  NODE_SELECTOR='"nodeSelector": { "kubernetes.io/hostname": "'${NODE_NAME}'" },'
  kubectl run --namespace ${NAMESPACE} $POD --rm -it --image ${IMAGE} --privileged --overrides '{"spec":{'"${NODE_SELECTOR}"'"hostPID": true}}' --command nsenter -- --mount=/proc/1/ns/mnt -- /bin/bash
fi

