#!/sbin/openrc-run

description="Bootstrap procedure if running on Docker Azure edition"

depend()
{
	need docker
	need net
}

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

	for i in $(seq 1 20)
	do
		einfo "Pulling Windows Azure Linux Agent container"

		docker pull docker4x/agent-azure >/dev/null

		if [ $? -eq 0 ]
		then
			break
		fi

		# Wait for... network to come up?  DNS servers to be reachable?
		# Not certain, but Azure continually fails to achieve this pull so
		# far because it can't dial the DNS lookup properly.
		# 
		# TODO: Debug.
		sleep 5
	done

	einfo "Running Windows Azure Linux Agent container"

	docker run -d \
		--privileged \
		--name agent \
		--ipc host \
		--pid host \
		--net host \
		--uts host \
		--restart unless-stopped \
		-v /usr/bin/docker:/usr/local/bin/docker:ro \
		-v /var/run/docker.sock:/var/run/docker.sock \
		-v /var/log:/var/log \
		-v /mnt:/mnt \
		-v /home:/home \
		-v /etc:/etc \
		-v /etc/hostname:/etc/hostname \
		-v /lib/modules:/lib/modules \
		-v /lib/firmware:/lib/firmware \
		-v /var/lib/waagent:/var/lib/waagent \
		docker4x/agent-azure

	# Wait for docker user to be added by agent.
	while [ ! -d /home/docker ]
	do
		sleep 5
	done

	# TODO: Make this cleaner.
	# User gets added by waagent.
	# Need to unlock it to login via SSH.
	passwd -u docker
	checkpath --directory --mode 0700 /home/docker/.ssh

	# Wait for WALinux agent provisioning to finish before invoking the
	# passed custom data.  This assures us that hostname etc. is set
	# correctly before running, say, swarm commmands.
	while [ ! -f /var/lib/waagent/provisioned ]
	do
		sleep 5
	done

	# Hack to fix swarm hostname issue.  See
	# https://github.com/docker/docker/issues/27173
	service docker restart

	. /var/lib/waagent/CustomData

	eend 0
}

stop()
{
	[ "$(mobyplatform)" != "azure" ] && exit 0
	docker rm -f agent || true
	passwd -l docker
}
