#!/bin/sh
########################################################################
# Begin $rc_base/init.d/cloud-init
########################################################################

. /etc/sysconfig/rc
. ${rc_functions}

case "${1}" in
	start)
		# Check if we are running in the cloud
		if running_on_ec2; then
			scriptname="/etc/rc.d/helper/aws-setup"
		elif running_on_exoscale; then
			scriptname="/etc/rc.d/helper/exoscale-setup"
		elif running_on_azure; then
			scriptname="/etc/rc.d/helper/azure-setup"
		elif running_on_gcp; then
			scriptname="/etc/rc.d/helper/gcp-setup"
		elif running_on_oci; then
			scriptname="/etc/rc.d/helper/oci-setup"
		else
			# This system is not running in the cloud
			exit 0
		fi

		# Find the first interface to use
		for i in /sys/class/net/red* /sys/class/net/eth* \
				/sys/class/net/*; do
			[ -d "${i}" ] || continue
			i=$(basename ${i})

			# Skip loopback
			[ "${i}" = "lo" ] && continue

			# Use whatever we have found
			intf="${i}"
			break
		done

		# Check if we found a network interface
		if [ ! -n "${intf}" ]; then
			echo_failure

			boot_mesg -n "Could not find a network interface" ${FAILURE}
			boot_mesg "" ${NORMAL}
		fi

		# Run a DHCP client and set up the system accordingly
		dhclient -sf "${scriptname}" "${intf}"

		# End DHCP client immediately
		dhclient -sf "${scriptname}" -r "${intf}" &>/dev/null

		# Rename network devices
		udevadm trigger --action="add" --subsystem-match="net"

		exit 0
		;;

	status)
		# Check Amazon
		if running_on_ec2; then
			echo "This system is running on AWS EC2"
			exit 0

		# Check Exoscale
		elif running_on_exoscale; then
			echo "This system is running on Exoscale"
			exit 0

		# Check Microsoft
		elif running_on_azure; then
			echo "This system is running on Microsoft Azure"
			exit 0

		# Check Google
		elif running_on_gcp; then
			echo "This system is running on Google Cloud"
			exit 0

		# The rest
		else
			echo "This system is NOT running in the cloud"
			exit 1
		fi
		;;

	*)
		echo "Usage: ${0} {start|status}"
		exit 1
		;;
esac

# End $rc_base/init.d/cloud-init
