#!/bin/bash

function mac_to_iface {
    MAC=$1
    ifconfig|grep $MAC| awk '{print $1}'|grep -v '\.'
}

function generate_mac_from_ip {
    IP=$1
    printf "02:42:%02x:%02x:%02x:%02x\n" `echo $IP|awk -F '.' '{print $1, $2, $3, $4}'`
}

iptables -L > /dev/null
ip6tables -L > /dev/null

MONITORING_CHANNEL=monitoring-channel-{{ unique_id }}
HEADNODEFLATLANIP={{ headnode_flat_lan_ip }}
HOST_FORWARDING_PORT_FOR_CEILOMETER={{ ceilometer_host_port }}

docker inspect $MONITORING_CHANNEL > /dev/null 2>&1
if [ "$?" == 1 ]
then
    #sudo docker build -t monitoring-channel -f Dockerfile.monitoring_channel .
    #sudo docker pull srikanthvavila/monitoring-channel
if [ -z "$HEADNODEFLATLANIP" ] || [ "$HEADNODEFLATLANIP" == "None" ]
then
    docker run -d --name=$MONITORING_CHANNEL --privileged=true -p $HOST_FORWARDING_PORT_FOR_CEILOMETER:8000 -v /usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config:/usr/local/share/ceilometer_proxy_config srikanthvavila/monitoring-channel
else
    docker run -d --name=$MONITORING_CHANNEL --add-host="ctl:$HEADNODEFLATLANIP" --privileged=true -p $HOST_FORWARDING_PORT_FOR_CEILOMETER:8000 -v /usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config:/usr/local/share/ceilometer_proxy_config srikanthvavila/monitoring-channel
fi
else
    docker start $MONITORING_CHANNEL
fi

# Set up networking via pipework
#SHARED_LAN_IFACE=$( mac_to_iface {{ shared_lan_mac }} )
#docker exec $MONITORING_CHANNEL ifconfig eth0 >> /dev/null || pipework $SHARED_LAN_IFACE -i eth0 $MONITORING_CHANNEL 192.168.0.1/24

# Make sure VM's eth0 (hpc_client) has no IP address
#ifconfig $HPC_IFACE 0.0.0.0

# Now copy ceilometer proxy configuration to container
#cat /usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config | sudo docker exec -i $MONITORING_CHANNEL bash -c 'cat > /usr/local/share/ceilometer_proxy_config'

# Attach to container
#docker start -a $MONITORING_CHANNEL
