#!/bin/sh

case $1 in
    apache|webrick)
    SERVER=$1
    ;;

    *)
    echo "usage: $0 apache|webrick" 1>&2
    exit 1
    ;;
esac

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

if [ -s /etc/puppet/puppet.conf ]; then
    mv /etc/puppet/puppet.conf /etc/puppet/puppet.conf.orig
fi

FQDN="$(hostname -f)"

mkdir -p /etc/puppet/manifests/node

if [ ! -s /etc/puppet/manifests/site.pp ]; then
    cat > /etc/puppet/manifests/site.pp << EOF
import "node/*.pp"

\$puppet_server = "${FQDN}"
EOF
fi

if [ ! -s /etc/puppet/manifests/node/${FQDN}.pp ]; then
    cat > /etc/puppet/manifests/node/${FQDN}.pp << EOF
node "${FQDN}" {

EOF

    if [ -f /etc/redhat-release ]; then
        cat >> /etc/puppet/manifests/node/${FQDN}.pp << EOF
    include yum::repo::epel

EOF
        if [ "${SERVER}" = "apache" ]; then
        cat >> /etc/puppet/manifests/node/${FQDN}.pp << EOF
    include user::system
    realize(User["httpsd"], Group["httpsd"])

EOF
        fi
    fi

cat >> /etc/puppet/manifests/node/${FQDN}.pp << EOF
    include puppet::server::${SERVER}
    include puppet::manual

}
EOF
fi

puppet cert --keylength 4096 --list
puppet apply --no-report --tags apt,yum,ruby /etc/puppet/manifests/site.pp
puppet apply --no-report /etc/puppet/manifests/site.pp
