#!/bin/bash
# Script that checks whether bms-network-config was running successfully
# If so, it disables the network config in cloud-init, as this creates a
# conflict otherwise on SLES12 where it renames eth0 to bond0 ...
# Reference: osTicket #579132
# (c) Kurt Garloff <kurt.garloff@t-systems.com>, 9/2017
# License: CC-BY-SA-3.0

BMSCLOUDCFG=${BMSCLOUDCFG:-/etc/cloud/cloud.cfg.d/91_bms_netdisable.cfg}
BMSCLOUDDS=${BMSCLOUDDS:-/etc/cloud/cloud.cfg.d/92_bms_configdrivedisable.cfg}

disable_netcfg()
{
	echo "Disabling network.config for cloud-init $BL"
	cat >$BMSCLOUDCFG <<EOT
## File autogenerated by bms-disable-cloudinit-network
## Your changes will be overwritten!
network: 
  config: disabled
datasource:
  OpenStack:
    max_wait: 120
    timeout: 50
    retries: 5
    apply_network_config: false
EOT
	# TODO: Should we detect whether we need to disable the ConfigDrive DataSource
	# 'cause meta_data.json is incomplete/broke on OTC BMS? Looking at hostname ... 
	echo "Disabling ConfigDrive DataSource for cloud-init"
	cat >$BMSCLOUDDS <<EOT
## File autogenerated by bms-disable-cloudinit-network
## Your changes will be overwritten!
# Remove ConfigDrive from OTC standard DataSource list
datasource_list: [ OpenStack ]
EOT
	#echo "Disabling cloud-init-local"
	#systemctl disable cloud-init-local.service
	cat >/etc/cloud/ds-identify.cfg <<EOT
policy: search,found=first,maybe=all,notfound=disabled
datasource_list: [ OpenStack ]
EOT

        echo ""
	echo "$(date) show /etc/cloud/ds-identify.cfg:"
	cat /etc/cloud/ds-identify.cfg
        echo ""

        echo ""
	echo "$(date) show ${BMSCLOUDCFG}:"
	cat ${BMSCLOUDCFG}
        echo ""

        echo ""
	echo "$(date) show ${BMSCLOUDDS}:"
	cat ${BMSCLOUDDS}
        echo ""

        echo ""
	echo "$(date) bms-network-setup, finished: disable_netcfg"
        echo ""
}

enable_netcfg()
{
	echo "Enabling network.config for cloud-init"
	cat >$BMSCLOUDCFG <<EOT
## File autogenerated by bms-disable-cloudinit-network
## Your changes will be overwritten!
#network: 
#  config: disabled
#datasource:
#  OpenStack:
#    max_wait: 120
#    timeout: 50
#    retries: 5
#    apply_network_config: false
EOT
	echo "Enabling ConfigDrive DataSource for cloud-init"
	cat >$BMSCLOUDDS <<EOT
## File autogenerated by bms-disable-cloudinit-network
## Your changes will be overwritten!
# Remove ConfigDrive from OTC standard DataSource list
#datasource_list: [ OpenStack ]
EOT
	#echo "Enabling cloud-init-local"
	#systemctl enable cloud-init-local.service
	cat >/etc/cloud/ds-identify.cfg <<EOT
policy: search,found=first,maybe=all,notfound=disabled
datasource_list: [ OpenStack ]
EOT

}

is_disabled()
{
	grep '^[^#].*config: disabled[ }]*$' $BMSCLOUDCFG >/dev/null 2>&1
}


detect_bms()
{
	if test -n "$DEBUG"; then return $DEBUG; fi
	if test -e /etc/is_bms; then return 0; fi
	return 1
}

# main
if detect_bms; then
	if ! is_disabled; then disable_netcfg; fi
else
	if is_disabled; then enable_netcfg; fi
fi
