#!/bin/sh -e

. /usr/share/debconf/confmodule

hasEc2Md() {
	local d=/var/lib/cloud i=/var/lib/cloud/instance/ f=""
	local flist="${i}/datasource ${i}/obj.pkl ${d}/cache/obj.pkl"
	# search current instance data source information
	for f in ${flist}; do
		[ -f "${f}" ] || continue
		grep -q DataSourceEc2 "${f}" 2>/dev/null && return 0
	done


	# there was no data above found that would have been indicated
	# by a upgrade. lets just see if we can't find the metadata
	# service.  if wget is not present (it is not 'essential')
	# then we will quietly return 1
	local url="http://169.254.169.254/2009-04-04/meta-data/instance-id"
	i=""
	if command -v wget >/dev/null 2>&1; then
		local tout="--connect-timeout 5 --read-timeout 5 --tries 1" 
		i=$(wget "${url}" ${tout} -O - 2>/dev/null) || :
	elif command -v curl >/dev/null 2>&1; then
		i=$(curl "${url}" --max-time 1) || :
	fi
	# if instance-id starts with 'i-' then in all likelyhood its good
	[ "${i#i-}" != "${i}" ] && return 0
	return 1
}

get_yaml_list() {
	# get_yaml_list(file, key, def): return a comma delimited list with the value
	# for the yaml array defined in 'key' from 'file'. if not found , return 'def'
	# only really supports 'key: [en1, en2 ]' format.
	local file="$1" key="$2" default="$3"
	[ -f "$file" ] || return 1
	# any thing that didn't match the key is deleted so the final 'p' only
	# prints things that matched.
	RET=$(sed -n -e "/^$key:/"'!'d -e "s/$key:[ \[]*//"\
		-e "s, \]$,," -e p "$file")
	[ -n "$RET" ] || RET="$default"
}

# old_dpkg_cfg is very old file that is no longer read by cloud-init.
# it gets re-named to cloud.cfg.d/90_dpkg.cfg in the preinst.
dpkg_cfg="/etc/cloud/cloud.cfg.d/90_dpkg.cfg"
old_dpkg_cfg="/etc/cloud/distro.cfg"
if [ -f "${old_dpkg_cfg}" -a ! -f "$dpkg_cfg" ]; then
	dpkg_cfg="${old_dpkg_cfg}"
   echo "WARN: reading value from ${old_dpkg_cfg}" 1>&2
fi
if [ -f "$dpkg_cfg" ]; then
	if get_yaml_list "$dpkg_cfg" datasource_list NOTFOUND &&
		val="$RET" && [ "$val" != "NOTFOUND" ]; then
		db_set cloud-init/datasources $val
	else
		echo "WARN: failed to read datasource_list from $dpkg_cfg" 1>&2
	fi
elif { db_fget cloud-init/datasources seen || : ; } &&
		[ "${RET}" = "false" ]; then
	# this is the first time this we've run (installation or re-install after
	# purge). try to determine if the Ec2 datasource is there.
	# if it is, and Ec2 was not in the default list, then add it.
	db_get cloud-init/datasources
	def="${RET}"
	case " ${def}," in
		*\ Ec2,*) :;;
		*) hasEc2Md &&
			db_set cloud-init/datasources "${def:+${def}, }Ec2";;
	esac
fi

db_input low cloud-init/datasources || true
db_go

exit 0
# vi: ts=4 noexpandtab
