#!/bin/bash -e

if [ -z "$3" ]; then
  echo "Usage: $0 source_port destination_ip destination_port"
  exit 1
fi

SPORT=$1
DIP=$2
DPORT=$3

# set packet forwarding
iptables -t nat -I PREROUTING -p tcp -m tcp --dport $SPORT \
  -j DNAT --to-destination $DIP:$DPORT
# masquerade packets
iptables -t nat -I POSTROUTING -d $DIP -p tcp --dport $DPORT -j MASQUERADE

# enable forwarding to and back
iptables -I FORWARD -p tcp --dport $SPORT -j ACCEPT
iptables -I FORWARD -p tcp -s $DIP --sport $DPORT -j ACCEPT   

# enable forwarding
sysctl net.ipv4.ip_forward=1 > /dev/null
