#!/bin/sh

# Forward local ports to production redis + postgres via kubernetes

set -euo pipefail

function die() {
  echo "$@" >&2
  exit 1
}

function forward_redis {
  redis_auth=$(
    kubectl get secret -n=redis \
      prod-redis \
      -o jsonpath='{.data.redis-password}' \
      | base64 -d
  )

  [ -n "$redis_auth" ] || die "Failed to retrieve redis password from secret"

  redis_pods=$(
    kubectl get pod -n=redis \
      -o jsonpath="{range.items[*]}{..metadata.name}{'\n'}{end}" \
      --field-selector=status.phase=Running
  )

  for pod in $redis_pods; do
    kubectl exec -n=redis -i $pod -c redis -- \
      redis-cli --pass "$redis_auth" set testkey 1 \
      | grep -q READONLY || break
  done

  [ -n "$pod" ] || die "No master pod found"

  exec kubectl port-forward --address 0.0.0.0 -n=redis pod/$pod 6379 >/dev/null
}

function forward_postgres {
  exec kubectl port-forward --address 0.0.0.0 -n=production svc/postgres-proxy 5433:5432 >/dev/null
}

function forward_fusion_auth {
  SVC_NAME=$(kubectl get svc --namespace fusionauth -l "app.kubernetes.io/name=fusionauth,app.kubernetes.io/instance=wavtool-idp" -o jsonpath="{.items[0].metadata.name}")
  exec kubectl port-forward --address 0.0.0.0 --namespace fusionauth svc/$SVC_NAME 9011:9011 >/dev/null
}

forward_redis &
forward_postgres &
forward_fusion_auth
