#!/bin/bash
#Nifty: LEGACY! Installs puppet agent for old puppet v3 master
PDEPL='echo -en (\e[01;33mDEPLOY MESSAGE\e[00m) '
DETECT=`egrep -i -e "(centos|centos linux|cloudlinux server) release ([0-9])" /etc/redhat-release`

if [ "$?" = "0" ]; then
	echo "This is an allowed release"
else
	echo "ERROR! This release is not supported."
	cat /etc/redhat-release
	exit 1 
fi

#  Decide whether 5 or 6
RELEASE=`rpm -qa "*-release" | grep -Ei "redhat|centos|cloudlinux" | cut -d"-" -f3`

if [ "$RELEASE" = "5" ] || [ "$RELEASE" = "6" ] || [ "$RELEASE" = "7" ]; then
	$PDEPL ;echo "RHEL/CentOS/Cloud Linux $RELEASE detected"
	RPMINSTALL="rpm -Uvh http://yum.puppetlabs.com/el/$RELEASE/products/x86_64/puppetlabs-release-$RELEASE-11.noarch.rpm"
else
	$PDEPL ;echo "Dying. OS/Release not supported in this script"
	exit 1
fi

# Lets just test if puppet is already there
if [ -f "/etc/puppet/puppet.conf" ]; then
	$PDEPL; echo "I am gonna stop you here."
	$PDEPL; echo "I was able to find a puppet.conf!"
	$PDEPL; echo "I refuse to autodeploy - I do not want to break stuff."
	exit 1
fi



$PDEPL ;echo "Installing the Puppet repository"
$RPMINSTALL

$PDEPL ; echo "Installing the Puppet client from repository"
yum install -y puppet ruby-shadow

$PDEPL ;echo "Will now assign the puppet master and ask it to sign my key - please care for the output and notice any errors"
sleep 1

chkconfig puppet on

puppet agent --server puppetmaster1.zitcom.dk --waitforcert 30 --test
$PDEPL ;echo "Getting the puppet configuration file"

if [ -f "/etc/puppet/puppet.conf" ]; then
	rm /etc/puppet/puppet.conf
fi

wget -O /etc/puppet/puppet.conf https://mirror.zitcom.dk/internal/nifty.sh/deprecated/puppet/puppet.conf

pkill puppet
if [ "$RELEASE" = "7" ]; then
  systemctl start puppet
else
  /etc/init.d/puppet start
fi
$PDEPL ; echo "So.. I am done now!"
