#!/bin/sh
# vi: ts=4 noexpandtab

XN=cloud-setup
. /usr/share/cloud/functions

start() {
	local i=0 max=${MD_MAX_TRIES} iid="" uptime="" toks="" n="" cmdline=""
	is_nocloud &&
		{ msg "nocloud specified, not using metadata"; return 0; }
	[ -f "${STATE_D}/cloud_tries" ] && read max < "${STATE_D}/cloud_tries"
	if ! lxc-is-container; then
		# reading cmdline in a container doesn't make sense, as you get the HOST's
		read cmdline < /proc/cmdline
		for n in ${cmdline}; do
			case "${n}" in
				cloud_tries=*) max=${n#cloud_tries=}; break;;
				ds=nocloud*)
					msg "kernel option nocloud specified. not using md"; return 0;;
			esac
		done
	fi
	[ ${max} -lt 0 ] && max=$((60*60*24*3)) ; # 3 days, is plenty
	
	msg "checking ${MDURL}/instance-id"
	i=0
	while [ $i -lt ${max} ] && i=$(($i+1)); do
		read uptime cputime < /proc/uptime
		iid=""
		if mdget instance-id; then
			iid=${_RET}
			[ "${iid#i-}" != "${iid}" ] && break
			msg "failed $i/${max}: up ${uptime}. iid had ${iid}"
		else
			msg "failed $i/${max}: up ${uptime}. request failed"
		fi
		sleep 1
		if [ $i -eq "${MD_DEBUG_COUNT}" ]; then
			msg "after ${MD_DEBUG_COUNT} fails, debugging"
			mddebug
		fi
	done

	if [ -n "${iid}" ]; then
		msg "successful after ${i}/${max} tries: up ${uptime}. iid=${iid}"
	else
		msg "failed to read iid from metadata. tried ${max}"; return 1;
	fi

	marked "$iid" import-keys &&
		{ msg "previously ran for ${iid}"; return 0; }

	local prefix="command=\"echo Please login as \\'cirros\\' user, not as root; echo; sleep 10\""
	if ec2metadata --public-keys > "$TMPF"; then
		su -c "ssh-add-key -" cirros < "$TMPF"
		HOME=/root ssh-add-key --replace --prefix "$prefix" - < "$TMPF"
	fi

	mark "$iid" import-keys

	return 0
}

case "$1" in
	start) start;;
	*) msg "unknown argument ${1}";;
esac
