#!/bin/sh
#
# Script to bootstrap new machines. Created on KVM hosts and copied to VMs
# when they are created. Source is templates/kvm/bootstrap-cosmos.sh.erb.
#

set -e

cmd_hostname="$1"
if test -z "$cmd_hostname"; then
    echo "Usage: $0 HOSTNAME REPO TAGPATTERN"
    exit 1
fi

cmd_repo="$2"
if test -z "$cmd_repo"; then
   echo "Usage $0 HOSTNAME REPO TAGPATTERN"
   exit 2
fi

cmd_tags="$3"
if test -z "$cmd_tags"; then
   echo "Usage $0 HOSTNAME REPO TAGPATTERN"
   exit 3
fi

set -x


# cloud-init runs with LANG='US-ASCII' which is likely to fail because of non-US-ASCII chars in the manifest
export LANG='en_US.UTF-8'

<% if @proxy_server != "" -%>
# Set up HTTP proxy for eduID (dev)
cat >> /etc/environment <<EOF
HTTP_PROXY='<%= @proxy_server %>'
http_proxy='<%= @proxy_server %>'
HTTPS_PROXY='<%= @proxy_server %>'
https_proxy='<%= @proxy_server %>'
no_proxy='<%= @no_proxy %>'
EOF
. /etc/environment
export HTTP_PROXY http_proxy HTTPS_PROXY https_proxy no_proxy
<% else -%>
# No proxy server configured in this environment
<% end %>

export DEBIAN_FRONTEND='noninteractive'

apt-get update
apt-get -y install rsync git-core
dpkg -i cosmos_1.5-1_all.deb

if ! test -d /var/cache/cosmos/repo; then
    cosmos clone "$cmd_repo"
fi


if [ ! -f /etc/rc.local ]; then 
	echo "#!/bin/bash" > /etc/rc.local
	echo >> /etc/rc.local
	chmod +x /etc/rc.local
fi

if [ -f /etc/rc.local ]; then
    # re-run cosmos at reboot until it succeeds - use bash -l to get working proxy settings
    grep -v "^exit 0" /etc/rc.local > /etc/rc.local.new
    (echo ""
     echo "test -f /etc/run-cosmos-at-boot && (bash -l cosmos -v update; bash -l cosmos -v apply && rm /etc/run-cosmos-at-boot)"
     echo ""
     echo "exit 0"
    ) >> /etc/rc.local.new
    mv -f /etc/rc.local.new /etc/rc.local
    chmod +x /etc/rc.local
fi

touch /etc/run-cosmos-at-boot

hostname $cmd_hostname

# Set up cosmos models. They are in the order of most significant first, so we want
# <host> <group (if it exists)> <global>
_host_types=`echo $cmd_hostname | awk -F[-.] '
{
    for (i = 1; i <= NF; i++) {
        if (i > 1)
           var=var "-"
        var=var $i
        print var
        }
}'`

models=$(
    echo -n '\\$COSMOS_REPO/'"$cmd_hostname/:"
    for _i in $_host_types; do
	test -d /var/cache/cosmos/repo/${_i}-common && echo -n '\\$COSMOS_REPO/'"${_i}-common/:"
    done
    echo -n '\\$COSMOS_REPO/global/'
)
echo "Configuring cosmos with the following models:"
echo "${models}"

perl -pi -e "s,#COSMOS_REPO_MODELS=.*,COSMOS_REPO_MODELS=\"${models}\"," /etc/cosmos/cosmos.conf
perl -pi -e "s,#COSMOS_UPDATE_VERIFY_GIT_TAG_PATTERN=.*,COSMOS_UPDATE_VERIFY_GIT_TAG_PATTERN=\"${cmd_tags}*\"," /etc/cosmos/cosmos.conf

env COSMOS_BASE=/var/cache/cosmos COSMOS_KEYS=/var/cache/cosmos/repo/global/overlay/etc/cosmos/keys /var/cache/cosmos/repo/global/post-tasks.d/015cosmos-trust

(date; nohup cosmos -v update && nohup cosmos -v apply && rm /etc/run-cosmos-at-boot; date) 2>&1 | tee /var/log/cosmos.log

exit 0
