#!/bin/bash set -eE -o pipefail trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR m() { printf "%s\n" "$*"; "$@"; } gw=$(/usr/sbin/ip route | sed -rn 's/^default via .* dev (\S+).*/\1/p') do-forward() { cmd=$1; shift for port; do m /sbin/iptables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 10.8.0.4:$port # we could leave these on all the time but its convenient to do it here done m /sbin/iptables $cmd FORWARD -i tun+ -o $gw -j ACCEPT m /sbin/iptables $cmd FORWARD -i $gw -o tun+ -j ACCEPT } ports=(25 143 587) case $1 in start) do-forward -A ${ports[@]} ;; stop) do-forward -D ${ports[@]} ;; *) echo "$0: error: expected 1 argument of start or stop" exit 1 ;; esac