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

# Checks if socat is installed
if ! command -v socat > /dev/null; then
  echo "Using 'port-forward' mode to run ssh session on Kubernetes instances requires 'socat' to be installed. Please install 'socat'" >&2
  exit
fi

# Checks if lsof is installed
if ! command -v lsof > /dev/null; then
  echo "Checking port availability for 'port-forward' mode requires 'lsof' to be installed. Please install 'lsof'" >&2
  exit 1
fi

# Function to check if port is in use
is_port_in_use() {
    local port="$1"
    lsof -i :${port} > /dev/null 2>&1
}

# Start from a fixed local port and increment if in use
local_port={{ local_port }}
while is_port_in_use "${local_port}"; do
    local_port=$((local_port + 1))
done

# Establishes connection between local port and the ssh jump pod
kubectl port-forward svc/{{ ssh_jump_name }} "${local_port}":22 &

# Terminate the port-forward process when this script exits.
K8S_PORT_FWD_PID=$!
trap "kill $K8S_PORT_FWD_PID" EXIT

# checks if a connection to local_port of 127.0.0.1:[local_port] is established
while ! nc -z 127.0.0.1 "${local_port}"; do
    sleep 0.1
done

# Establishes two directional byte streams to handle stdin/stdout between
# terminal and the jump pod.
# socat process terminates when port-forward terminates.
socat - tcp:127.0.0.1:"${local_port}"