#!/bin/bash

if [[ "$1" == "stop" ]]; then
    printf "Reloading firewall.. "
    firewall-cmd --reload
    exit $?
fi

function usage () {
    printf "\nUsage:

    $0 FROM_PORT TO_ADDR:TO_PORT [PROTO]
    $0 stop
    
    FROM_PORT   External port on public zone
    TO_ADDR     Destination address
    TO_PORT     Destination port
    PROTO       Protocol (tcp/udp, optional,
                defaults to tcp)
    stop        Remove port forwarding

Example:

    $0 8080 192.168.122.122:80
    - will forward connections coming to port 80 to
      a VM with address 192.168.122.122
\n"
    exit 0
}

function forward () {
    echo "Creating port forward from port $FROM_PORT/$PROTO to $TO_ADDR:$TO_PORT."

    printf "Enabling masquerade... "
    firewall-cmd --add-masquerade
    printf "Adding port forward... "
    firewall-cmd --add-forward-port=port=${FROM_PORT}:proto=${PROTO}:toport=${TO_PORT}:toaddr=${TO_ADDR}
#    iptables -D LIBVIRT_FWI -o virbr0 -j REJECT --reject-with icmp-port-unreachable
#    iptables -D LIBVIRT_FWO -i virbr0 -j REJECT --reject-with icmp-port-unreachable

    echo "Done."
    exit 0
}



if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
    usage
fi

if [ "$UID" -ne 0 ]; then
    echo "Run as root."
    exit 1
fi

FROM_PORT=$1
TO_ADDR=${2%:*}
TO_PORT=${2##*:}
PROTO=${3:-'tcp'}

if [[ ! "$TO_ADDR" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    printf "Resolved %s as " "$TO_ADDR"
    TO_ADDR=`dig +short "$TO_ADDR" | head -1`
    printf "%s\n" "$TO_ADDR"
fi

if [[ "$PROTO" != "tcp" ]] && [[ "$PROTO" != "udp" ]]; then
    usage
fi

forward