#!/bin/bash

# Puppet CA endpoint. Overridable via the environment (systemd reads
# /etc/sysconfig/puppet-initial via EnvironmentFile), so kickstart %post can
# point a host at a different CA without rebuilding the RPM. Defaults to the
# in-cluster puppetserver CA service.
PUPPETCA_HOST="${PUPPETCA_HOST:-puppetca.k8s.syd1.au.unkin.net}"
PUPPETCA_PORT="${PUPPETCA_PORT:-8140}"

# Ensure the hostname is set
hostnamectl set-hostname $(hostname -s).main.unkin.net
grep '^HOSTNAME=' /etc/sysconfig/network | cut -d= -f2 | grep -q '\.' || sed -i 's/^\(HOSTNAME=[^\.]*\)$/\1.main.unkin.net/' /etc/sysconfig/network

# Install CA for Puppet
test -f /etc/puppetlabs/puppet/ssl/certs/ca.pem || mkdir -p /etc/puppetlabs/puppet/ssl/certs && wget --no-check-certificate "https://${PUPPETCA_HOST}:${PUPPETCA_PORT}/puppet-ca/v1/certificate/ca" -O /etc/puppetlabs/puppet/ssl/certs/ca.pem

# Registering to Puppet server
/opt/puppetlabs/bin/puppet agent --test --server "${PUPPETCA_HOST}" --noop --onetime --no-daemonize --verbose

# Running Puppet agent five times with a 30-second gap between each run, stop puppet service at the end of each run
for i in {1..5}; do
    /opt/puppetlabs/bin/puppet agent -t --server puppet.query.consul
    systemctl stop puppet
    sleep 30
done

# Start and enable the puppet service at the end
systemctl start puppet.service
systemctl enable puppet.service

# Disable the systemd service at the end
systemctl disable puppet-initial.service
