#!/bin/bash

set -xe

migrate_all() {
    sed -r -n -e 's/^listen ([0-9]+):([0-9.]+):([0-9]+)/\1 \2 \3/ p' /etc/openshift/port-proxy.cfg.rpmsave | {
        while read port daddr dport
        do
            echo $port $daddr:$dport
            oo-iptables-port-proxy addproxy $port $daddr:$dport
        done
    }
}

conf='/etc/sysctl.conf'
command cp -f "$conf"{,.ugsave.`date +%Y-%m-%d-%H:%M:%S`}

# openshift-iptables-port-proxy requires several additional NAT-related
# sysctl settings to be changed that the old openshift-port-proxy did
# not need.
if ! grep -q 'net\.ipv4\.ip_forward\s*=\s*1\>' "$conf"
then
  cat <<EOF >> $conf

# Enable forwarding for the OpenShift port proxy.
net.ipv4.ip_forward = 1
EOF
fi

if ! grep -q 'net\.ipv4\.conf\.all\.route_localnet=\s*1\>' "$conf"
then
  cat <<EOF >> $conf

# Allow the OpenShift port proxy to route using loopback addresses.
net.ipv4.conf.all.route_localnet = 1
EOF
fi

chkconfig openshift-iptables-port-proxy on

# openshift-iptables-port-proxy hooks into the iptables configuration by
# adding a new table and having the INPUT chain jump to this new table.
if ! iptables -L rhc-app-comm > /dev/null 2>&1
then
  iptables -N rhc-app-comm
  iptables -I INPUT 4 -j rhc-app-comm
fi

# Make sure that the above modifications to iptables persist.
service iptables save

# reload the sysctl config to pick up the changes
sysctl -p $conf || true

# Migrate the existing openshift-port-proxy config to 
# openshift-iptables-port-proxy
migrate_all

# Stop the openshift-iptables-port-proxy since we are in maintenance mode
# at this point
service openshift-iptables-port-proxy stop
