#!/bin/sh
set -eu

listen_port=${NETEM_LISTEN_PORT:-15432}
target_host=${NETEM_TARGET_HOST:-}
target_port=${NETEM_TARGET_PORT:-}

case "$listen_port:$target_port" in
  *[!0-9:]*|:*|*:) echo "NETEM_LISTEN_PORT and NETEM_TARGET_PORT must be numeric" >&2; exit 64 ;;
esac
case "$target_host" in
  ""|*[!A-Za-z0-9.-]*) echo "NETEM_TARGET_HOST must be a DNS name or address" >&2; exit 64 ;;
esac

exec socat \
  "TCP-LISTEN:${listen_port},fork,reuseaddr,keepalive" \
  "TCP:${target_host}:${target_port},connect-timeout=10"
