#!/bin/bash

# Install Open source Puppet using Ruby Gems per
# https://docs.puppetlabs.com/guides/install_puppet/install_gem.html

OS=Darwin

case $OS in
Darwin)
    GEM=/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/gem
    GEMPKG=
    PUPPET=/usr/bin/puppet
    CURL=/usr/bin/curl
    CONFDIR=/private/etc/puppet
    CONF=${CONFDIR}/puppet.conf
    INIT=/Library/LaunchDaemons/com.puppetlabs.puppet.plist
    CONFURI='http://anfadmin.ucsd.edu/puppet/darwin.conf'
    #INITURI='https://raw.githubusercontent.com/puppetlabs/puppet/master/ext/osx/puppet.plist'
    INITURI='http://anfadmin.ucsd.edu/puppet/puppet.plist'
    SVC=com.puppetlabs.puppet
    ;;
FreeBSD)
    GEM=/usr/local/bin/gem
    PUPPET=/usr/local/bin/puppet
    CURL=/usr/local/bin/curl
    CONFDIR=/usr/local/etc/puppet
    CONF=${CONFDIR}/puppet.conf
    INIT=/usr/local/etc/rc.d/puppetd
    CONFURI='http://anfadmin.ucsd.edu/puppet/freebsd.conf'
    INITURI='http://anfadmin.ucsd.edu/puppet/freebsd.init'
    SVC=puppet

    # FreeBSD may need some package help
    if [ ! -x $CURL ]; then pkg install -y curl; fi
    if [ ! -x $GEM  ]; then pkg install -y devel/ruby-gems; fi
    ;;
*)
    "Unsupported OS family, '${OS}'."
    exit 1
    ;;
esac

if [ "${USER}" != 'root' ]; then
    echo "Must run as root, not ${USER}"
    exit 2
fi

# Shut down puppet as needed and install needed packages
if [ -x $PUPPET ]; then $PUPPET resource service $SVC ensure=stopped; fi

$GEM install facter --version=2.4.4 && \
$GEM install hiera  --version=1.3.4 && \
$GEM install puppet --version=3.8.1 || exit 3

if [ -f $CONF ]; then
    echo "${CONF} exists. Not replacing."
else
    $CURL -o $CONF $CONFURI
fi

if [ -f $INIT ]; then
    echo "${INIT} exists. Updating..."
fi
$CURL -o $INIT ${INITURI}

if [ -x $PUPPET ]; then
    $PUPPET resource group puppet ensure=present system=true && \
    $PUPPET resource user  puppet ensure=present system=true gid=puppet shell='/usr/sbin/nologin' && \
    $PUPPET resource file    $INIT    ensure=file      group=puppet mode=0755 && \
    $PUPPET resource file    $CONFDIR ensure=directory group=puppet mode=0755 && \
    $PUPPET resource file    $CONF    ensure=file      group=puppet mode=0644 && \
    $PUPPET resource service $SVC     ensure=running   enable=true
else
    exit 4
fi
