#!/bin/bash

set -e

# Guard against unprivileged users
if [ "$(whoami)" != "root" ]
then
    echo "This script needs to be run as root" >&2
    exit 1
fi


add_mysql_dnat_rule() {
    PLAIN_DESTINATION="$1"
    DNAT_DESTINATION="$2"

    echo -n "Adding DNAT rule for $PLAIN_DESTINATION ... "
    iptables \
        -t nat \
        -A OUTPUT \
        -p tcp \
        --destination "$PLAIN_DESTINATION" \
        --dport mysql \
        -j DNAT \
        --to-destination "$DNAT_DESTINATION"
    echo "done"
}


#The following list has been created by running
#
#  iptables -t nat -L -v -n | grep DNAT | sed -e 's/^.*\(192.168.99.[0-9]*\)[[:space:]] .*to:\(.*\)$/add_mysql_dnat_rule "\1" "\2"/'
#
# as root on a machine that has the needed DNATs
#
add_mysql_dnat_rule "192.168.99.13" "10.64.37.4:3309"
add_mysql_dnat_rule "192.168.99.12" "10.64.37.4:3309"
add_mysql_dnat_rule "192.168.99.11" "10.64.37.4:3309"
add_mysql_dnat_rule "192.168.99.7" "10.64.37.5:3308"
add_mysql_dnat_rule "192.168.99.6" "10.64.37.5:3307"
add_mysql_dnat_rule "192.168.99.5" "10.64.37.4:3308"
add_mysql_dnat_rule "192.168.99.4" "10.64.37.4:3307"
add_mysql_dnat_rule "192.168.99.3" "10.64.37.5:3306"
add_mysql_dnat_rule "192.168.99.2" "10.64.37.4:3306"
add_mysql_dnat_rule "192.168.99.1" "10.64.20.12:3306"
add_mysql_dnat_rule "192.168.99.1" "10.64.20.12:3306"
add_mysql_dnat_rule "192.168.99.2" "10.64.37.4:3306"
add_mysql_dnat_rule "192.168.99.3" "10.64.37.5:3306"
add_mysql_dnat_rule "192.168.99.4" "10.64.37.4:3307"
add_mysql_dnat_rule "192.168.99.5" "10.64.37.4:3308"
add_mysql_dnat_rule "192.168.99.6" "10.64.37.5:3307"
add_mysql_dnat_rule "192.168.99.7" "10.64.37.5:3308"

echo "Done."
