#!/sbin/openrc-run

description="Bootstrap procedure if running on Docker for AWS"

depend()
{
	need docker
}

start()
{
	[ "$(mobyplatform)" != "aws" ] && exit 0
	ebegin "Running AWS-specific initialization"

	INSTANCE_DATA_ENDPOINT=http://169.254.169.254/latest
	METADATA="${INSTANCE_DATA_ENDPOINT}/meta-data"
	USERDATA="${INSTANCE_DATA_ENDPOINT}/user-data"

	USER_SSH_DIR=/home/docker/.ssh

	# setup SSH keys
	if [ ! -d ${USER_SSH_DIR} ]
	then
		mkdir -p ${USER_SSH_DIR}
		chmod 700 ${USER_SSH_DIR}
	fi

	# Put instance SSH key in place.
	wget -q -O /tmp/my-key ${METADATA}/public-keys/0/openssh-key &>/dev/null
	if [ $? -eq 0 ]
	then
		cat /tmp/my-key >> ${USER_SSH_DIR}/authorized_keys
		chmod 700 ${USER_SSH_DIR}/authorized_keys
		rm /tmp/my-key
	else
		echo "No SSH public key found to add to instance"
	fi

	# TODO: The docker user should be given more permissions on FS by
	# default, this is temporary hack
	chown -R docker /home/docker
	chgrp -R docker /home/docker
	chown -R docker /var/log
	chgrp -R docker /var/log
	passwd -u docker

	HOSTNAME=$(wget -qO- ${METADATA}/local-hostname)

	# Set hostname based on what AWS tells us it should be.
	echo ${HOSTNAME} >/etc/hostname
	hostname -F /etc/hostname

	# Needed for ELB integration.
	mkdir -p /var/lib/docker/swarm

	# Get user data file and use it to bootstrap Moby in the cloud
	wget -q -O /tmp/user-data ${USERDATA}/

	# For now we will have a shell script which executes on boot.
	# TODO(nathanleclaire/kencochrane): Migrate this to mobyconfig, or similar.
	if [ $? -eq 0 ]
	then
		chmod 755 /tmp/user-data
		/tmp/user-data
	fi

	eend 0
}
