#!/bin/sh

# Test PuppetDB & Puppet integration
# Configure PuppetDB and Puppet master to talk to each other, do a client run
# and check the results.

. "$(dirname $0)/common.sh"

set -e

trap 'cleanup' EXIT

certname="$(puppet config print certname)"
hostcert="$(puppet config print hostcert)"
hostkey="$(puppet config print hostprivkey)"
cacert="$(puppet config print cacert)"

adduser puppetdb puppet

cat >>/etc/puppetdb/conf.d/jetty.ini <<-EOF
	ssl-host = 0.0.0.0
	ssl-port = 8081
	ssl-key = ${hostkey}
	ssl-cert = ${hostcert}
	ssl-ca-cert = ${cacert}
EOF

systemctl restart puppetdb

puppet config set --section=master reports puppetdb
puppet config set --section=master storeconfigs true
puppet config set --section=master storeconfigs_backend puppetdb

cp /usr/share/doc/puppet-terminus-puppetdb/routes.yaml.example /etc/puppet/routes.yaml
cat >/etc/puppet/puppetdb.conf <<-EOF
	[main]
	server_urls = https://${certname}:8081
EOF

systemctl reload apache2

mkdir -p /etc/puppet/code/environments/production/manifests

cat >/etc/puppet/code/environments/production/manifests/default.pp <<-EOF
	node default {
	  file { '/tmp/testfile' :
	    ensure  => present,
	    content => "autopkgtest\n",
	  }
	}
EOF

echo "Waiting for PuppetDB to start"
wait_for_pdb

echo "Running puppet"
puppet agent --test --server "$certname" && [ $? -eq 2]

echo "Checking for /tmp/testfile"
test -f /tmp/testfile

sleep 5 # Let PuppetDB commit stuff to the database

echo "Checking for node existence"
query "nodes/${certname}" | jq -e ".certname == \"${certname}\""

echo "Checking the fqdn fact"
query "nodes/${certname}/facts/fqdn" | jq -e ".[0].value == \"${certname}\""

echo "Checking the node's catalog"
query "catalogs/${certname}" | jq -e 'has("catalog_uuid")'

echo "Checking the node's report"
query "reports" | jq -e "(map(select(.certname == \"${certname}\")) | length) >= 1"

echo "Checking 'puppet node status ${certname}'"
puppet node status "$certname" | grep -qi "\bactive\b"

echo "Deactivating node"
puppet node deactivate "$certname"

sleep 2 # Let PuppetDB process everything

echo "Checking 'puppet node estatus ${certname}' again"
puppet node status "$certname" | grep -qi "Deactivated"
