#!/bin/bash
set -eux

if [[ "rhel rhel7 centos7 fedora" =~ "$DISTRO_NAME" ]]; then
    yum -y install --enablerepo=updates-testing kubernetes bridge-utils

    cat > /etc/sysconfig/network-scripts/ifcfg-cbr0 <<EOF
DEVICE=cbr0
TYPE=Bridge
IPADDR=10.240.1.1
NETMASK=255.255.255.0
ONBOOT=yes
STP=yes
MTU=1450

# With the default forwarding delay of 15 seconds,
# many operations in a 'docker build' will simply timeout
# before the bridge starts forwarding.
DELAY=2
EOF

cat > /etc/sysconfig/network-scripts/route-cbr0 <<EOF
10.240.0.0/16 dev cbr0 scope link src 10.240.1.1
EOF

# defer docker starting until cbr0 is up
cat > /etc/systemd/system/docker.service <<EOF
.include /usr/lib/systemd/system/docker.service
[Unit]
After=network-online.target docker.socket
EOF

cat > /etc/systemd/system/heat-config-kubelet-nat-rule.service <<EOF
[Unit]
Description=iptables rule to allow nat masquerading out of 10.240.1.0/24

[Service]
ExecStart=/usr/sbin/iptables -t nat -A POSTROUTING -o eth0 -s 10.240.1.0/24 -j MASQUERADE
Type=oneshot

[Install]
WantedBy=multi-user.target
EOF

if [ -f "/opt/heat-docker/images.tar" ]; then
    cat > /etc/systemd/system/heat-config-kubelet-load-images.service <<EOF
[Unit]
Description=Call docker load on /opt/heat-config/images.tar
After=docker.service
Before=os-collect-config.service kubelet.service

[Service]
ExecStart=/bin/docker load -i /opt/heat-docker/images.tar
ExecStart=/bin/rm -f /opt/heat-docker/images.tar
Type=oneshot

[Install]
WantedBy=multi-user.target
EOF
    systemctl enable heat-config-kubelet-load-images.service
fi


    cat > /etc/sysconfig/docker <<EOF
OPTIONS=--selinux-enabled --bridge cbr0 --mtu 1450 --iptables=false --insecure-registry 192.168.20.112:5001
EOF

    sed -e 's|KUBELET_ARGS=""|KUBELET_ARGS="--config=/var/lib/heat-config/heat-config-kubelet/kubelet-manifests"|g' -i /etc/kubernetes/kubelet
    sed -e '/KUBE_ETCD_SERVERS/ s/^#*/#/' -i /etc/kubernetes/config
    systemctl disable docker.service
    systemctl enable docker.service
    systemctl enable kubelet.service
    systemctl enable heat-config-kubelet-nat-rule.service
    systemctl disable firewalld

SCRIPTDIR=$(dirname $0)
install -D -g root -o root -m 0755 ${SCRIPTDIR}/hook-kubelet.py /var/lib/heat-config/hooks/kubelet

else
    echo "Distribution '$DISTRO_NAME' is not supported"
    exit 1
fi
