#!/bin/bash

set -x

# Masquerade traffic from the LAN to the local host
iptables -A POSTROUTING -t nat -j MASQUERADE -o eth0

while (( "$#" )); do
  TARGET_HOST="$1"
  TARGET_PORT="$2"

  if [[ ${TARGET_HOST} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    TARGET_IP="${TARGET_HOST}"
  else
    # Grep for IPv4 address
    OUTPUT=$(host "${TARGET_HOST}" | grep "has address")

    if [[ "${OUTPUT}" == *NXDOMAIN* ]]; then
      echo "ERROR: Domain not found (${TARGET_HOST})"
      exit 1
    elif [[ "${OUTPUT}" == *address* ]]; then
      TARGET_IP=$(host "${TARGET_HOST}" | grep "has address" | cut -d' ' -f4)
    fi
  fi

  if [ -z "${TARGET_PORT}" ]; then
    TARGET_PORT="1:65535"
  fi

  # Route tcp traffic from the local host to the LAN
  iptables -t nat -A PREROUTING  -i eth0 -p tcp --dport ${TARGET_PORT} -j DNAT --to-destination ${TARGET_IP}
  iptables -t nat -A POSTROUTING -o tun0 -p tcp --dport ${TARGET_PORT} -j MASQUERADE

  #echo "Connected to ${TARGET_HOST} (${TARGET_IP}) on port ${TARGET_PORT}..."

  shift
  shift
done

echo "Connected. Press Ctrl+C to stop."

while [ true ]; do
  sleep 3600
done
