#!/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}
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: [ NoCloud, OpenStack, Ec2, OpenNebula, Azure, AltCloud, OVF, MAAS, GCE, CloudSigma, CloudStack, None ]
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: [ NoCloud, OpenStack, Ec2, OpenNebula, Azure, AltCloud, OVF, MAAS, GCE, CloudSigma ]
EOT

	# These shadow eth* files get in our way
	rm -f /etc/sysconfig/network-scripts/ifcfg-lan*
}

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: enabled}
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: [ NoCloud, OpenStack, ConfigDrive, Ec2, OpenNebula, Azure, AltCloud, OVF, MAAS, GCE, CloudSigma, CloudStack, None ]
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: [ NoCloud, OpenStack, ConfigDrive, Ec2, OpenNebula, Azure, AltCloud, OVF, MAAS, GCE, CloudSigma ]
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
