#!/bin/sh

hostname -f | fgrep "." > /dev/null
if [ $? -ne 0 ]; then
    echo "error, command 'hostname -f' does not return domainname" 1>&2
    exit 1
fi

which ruby > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "error, ruby binary not in path" 1>&2
    exit 1
fi

which puppet > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "error, puppet binary not in path" 1>&2
    exit 1
fi

mkdir -p /etc/puppet/manifests
if [ ! -s /etc/puppet/manifests/site.pp ]; then
    echo "" > /etc/puppet/manifests/site.pp
fi

cat /dev/null > /etc/puppet/puppet.conf

ssldir=`echo "require 'puppet'; Puppet.parse_config; print Puppet.settings.value('ssldir')" | ruby`

if [ ! -d ${ssldir}/ca ]; then
    puppetca --certname ca --keylength 4096
fi

puppet --version | egrep "^0\." > /dev/null 2>&1
if [ $? -eq 0 ]; then
    (
        echo "\$homename = '`hostname -f`'"
        echo "\$puppet_ssldir = '${ssldir}'"
        echo "\$puppet_storeconfigs = 'none'"
        echo "include puppet::server::apache"
        echo "include puppet::manual"
    ) | puppet --no-report
else
    (
        echo "include puppet::server::apache"
        echo "include puppet::manual"
    ) | puppet apply --no-report --manifest /dev/stdin /dev/null
fi
