#!/bin/bash

# Establish iptables-based reverse proxy

# Thanks to user55518 in http://unix.stackexchange.com/questions/111841/regular-expression-in-bash-to-validate-ip-address#111843
re='^[1-2]\{0,1\}[0-9]\{0,1\}[0-9]\{1\}\.[1-2]\{0,1\}[0-9]\{0,1\}[0-9]\{1\}\.[1-2]\{0,1\}[0-9]\{0,1\}[0-9]\{1\}\.[1-2]\{0,1\}[0-9]\{0,1\}[0-9]\{1\}$'


if [ ! -z "$1" ] && [ "$1" == "--reset" ]; then
    iptables -F -t nat
    exit $?
fi

if [ ! -z "$1" ] && [ "$1" == "--list" ]; then
    iptables -S -t nat
    exit $?
fi

if [ -z "$1" ] || [ -z "$2" ] || ! (echo "$2" | grep -x "$re" &> /dev/null) || [ -z "$3" ]; then
    printf "Usage: $0 localport remoteIP remoteport [ --local ]\n"
    printf "       $0 --reset\n"
    printf "       $0 --list\n"
    exit 1
fi

# Tell the kernel to allow forwarding packets.
echo 1 > /proc/sys/net/ipv4/ip_forward

# Set up masquerading if not already done
if [ `iptables -S -t nat | grep -c '\-A POSTROUTING -j MASQUERADE'` -ne 1 ]; then
    iptables -t nat -A POSTROUTING -j MASQUERADE;
fi

# Handle local forwarding.
if [ "$4" == "--local" ] || [ "$2" == "127.0.0.1" ]; then
    iptables -t nat -I OUTPUT -p tcp -o lo --dport "$1" -j REDIRECT --to-ports "$3"
    iptables -t nat -A PREROUTING -p tcp --dport "$1" -j REDIRECT --to "$3"
else  # Handle remote
    iptables -t nat -A PREROUTING -p tcp -m tcp --dport "$1" -j DNAT --to-destination "$2":"$3"
fi

echo Done -- all traffic connecting to port "$1" will be redirected to "$2":"$3"