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

./select_target.sh "$@"

function find_open_port() {
  local port="$1"
  while (lsof -i -P -n | grep LISTEN | grep --quiet "$port") >&2; do
    port=$((port+1))
  done
  echo "$port"
}

pod_name=redis-master-0
remote_port=6379
local_port="$(find_open_port 6380)"

echo Forwarding $pod_name:$remote_port to localhost:$local_port... >&2
kubectl port-forward "$pod_name" "$local_port:$remote_port" >/dev/null &
port_forward_pid="$!"

function onexit() {
  kill -INT "$port_forward_pid"
}
trap onexit EXIT

# Wait for port to become occupied.
while ! (lsof -i -P -n | grep LISTEN | grep --quiet "$local_port") >&2; do
  sleep 1
done

shift # drop the first argument which is the wv namespace
redis-cli -p "$local_port" "$@"
