#!/bin/bash

# -------------------------------------------- USAGE -----------------------------------------------
function USAGE {
cat<<ENDUSAGE
 USAGE: pod-gdb <(POD-NAME-MASK | CONTAINER-NAME)> [<Options>]        - list of all processes running in pod
        pod-gdb <(POD-NAME-MASK | CONTAINER-NAME)> [<Options>] <PID>  - interactive debug of a process using gdb
 Options:
        -b      --bt                                                  - show backtrace for all the process threads (it matters only if PID is specified)
        -v      --verbose                                             - turn verbose mode on
ENDUSAGE
}

# --------------------------------------------- MAIN -----------------------------------------------
[ -z "$1" ] && USAGE && exit 0
for ARG in "$@"; do
    [[ $ARG =~ ^[0-9]+$ ]] && PID=$ARG && continue
    case $ARG in
        -v|--verbose)
            set -x
            ;;
        -b|--bt)
            CMD="--ex \"thread apply all bt\""
            ;;
    esac
done

if [[ $1 =~ -[0-9]{10}-[a-z0-9]{5}$ ]]; then
    POD=$1
else
    POD=$(kubectl get pod|grep $1|grep -m1 Running|cut -d' ' -f1) # get first pod with matching mask
    [ -z $POD ] && echo "ERROR: No running pod found by mask \"$1\"" && exit 1
fi
POD_INFO=($(kubectl get po $POD -o jsonpath='{.status.containerStatuses[0].containerID} {.status.hostIP}'))
POD_ID=$(echo ${POD_INFO[0]} | cut -c10-21)
POD_INT_IP=${POD_INFO[1]}
POD_EXT_IP=$(gcloud compute instances list --filter="INTERNAL_IP:$POD_INT_IP" --format="value(EXTERNAL_IP)")

[ -z "$PID" ] && exec kubectl exec $POD -- ps aux
for i in 1 2
do
    ssh -ti ~/.ssh/google_compute_engine $USER@$POD_EXT_IP "sudo nsenter -t \$(docker inspect --format {{.State.Pid}} $POD_ID) -m -p gdb -p $PID $CMD" # < /dev/tty
    EXIT_STATUS=$?
    [[ $EXIT_STATUS != 255 || $i == 2 ]] && exit $EXIT_STATUS
    echo "WARNING: Failed to establish ssh connection. Let's update project ssh metadata and try once again..."
    CONN_STR=$(gcloud compute instances list --filter="INTERNAL_IP:$POD_INT_IP" --format="value(ZONE, NAME)")
    gcloud compute ssh --zone $CONN_STR --command "exit"
done
