#!/bin/bash

set -e

if [[ "$(whoami)" != "root" ]]; then
        echo 'script must run as root'
        exit 1;
fi


echo 
echo "Hostname: $(hostname --fqdn)"
echo "is this correct? ctrl-c to abort"
read

echo "Which puppet branch does this machine run? type 'testing' or 'production'"
read puppet_branch 

if [[ "$puppet_branch" != "testing" && "$puppet_branch" != 'production' ]]; then
        echo "invalid branch: $puppet_branch"
        exit 1;
fi

source /etc/lsb-release

echo 'Running initial apt-get update/upgrade..'
apt-get -qq update
apt-get -qq -y upgrade

echo "Getting puppet deb for $DISTRIB_CODENAME"
sleep 2
gpg --keyserver pgp.mit.edu --recv-key 7F438280EF8D349F
gpg -a --export EF8D349F | apt-key add -
wget --quiet "http://deb.office.basesoft.com/puppetlabs-release-$DISTRIB_CODENAME.deb"
dpkg -i puppetlabs-release-$DISTRIB_CODENAME.deb
apt-get -qq update 
apt-get -qq install -y puppet

echo "Writing /etc/puppet/puppet.conf.."
sleep 2
cat > /etc/puppet/puppet.conf << EOF
[main]
logdir=/var/log/puppet
vardir=/var/lib/puppet
ssldir=/var/lib/puppet/ssl
rundir=/var/run/puppet
factpath=\$vardir/lib/facter
#templatedir=\$confdir/templates
certname=$(hostname --fqdn)

[master]
# These are needed when the puppetmaster is run by passenger
# and can safely be removed if webrick is used.
ssl_client_header = SSL_CLIENT_S_DN 
ssl_client_verify_header = SSL_CLIENT_VERIFY

[agent]
server = puppet.office.basesoft.com
environment = $puppet_branch
pluginsync = true
report = true
listen = true
EOF
cat /etc/puppet/puppet.conf

echo
echo 'Enabling puppet on boot..'
sleep 2
sed -i -e 's/START=no/START=yes/g' /etc/default/puppet

echo 'Registering to puppet server, you should now sign the certificate..'
puppet agent --test --waitforcert 10
