#!/bin/bash

set -e

SEEDS=("10.64.16.147" "10.64.16.149" "10.64.0.200")
JMX_PORT=7199
CLUSTER_PORTS=($JMX_PORT 9042 7000) # (jmx, cql, cassandra inter-node)
JMX_USERS=("eevans" "gwicke" "mobrovac" "root")

iptables_cmd()
{
    [ -n "$DEBUG" ] && echo "sudo iptables $@" || sudo /sbin/iptables $@
}

filtered_seeds()
{
    for seed in "${SEEDS[@]}"; do
        if ! test "$seed" = "`hostname -i`"; then echo $seed; fi
    done
}

### Input

iptables_cmd -F INPUT

iptables_cmd -A INPUT -i lo -j ACCEPT
iptables_cmd -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables_cmd -A INPUT -p tcp --dport ssh  -j ACCEPT
iptables_cmd -A INPUT -p tcp --dport 5666 -j ACCEPT  # npre
iptables_cmd -A INPUT -p tcp --dport 7231 -j ACCEPT  # restbase

for port in "${CLUSTER_PORTS[@]}"; do
    for seed in `filtered_seeds`; do
        iptables_cmd -A INPUT -s $seed -p tcp --dport $port -j ACCEPT
    done
done

iptables_cmd -A INPUT -j REJECT  # Default policy, reject

# Or optionally set the INPUT policy to REJECT
#iptables_cmd -P INPUT REJECT

### Output

iptables_cmd -F OUTPUT

# restrict outgoing jmx to "trusted" user set; other nodes implicitly trust us
for user in "${JMX_USERS[@]}"; do
    iptables_cmd -A OUTPUT -o lo   -p tcp --dport $JMX_PORT -m owner --uid-owner $user -j ACCEPT    
    iptables_cmd -A OUTPUT -o eth0 -p tcp --dport $JMX_PORT -m owner --uid-owner $user -j ACCEPT
done

# deny outgoing jmx to everyone else
iptables_cmd -A OUTPUT -o lo   -p tcp --dport $JMX_PORT -j REJECT
iptables_cmd -A OUTPUT -o eth0 -p tcp --dport $JMX_PORT -j REJECT
