#!/bin/sh

# Check a standalone PuppetDB instance
# Perform basic checks using the REST endpoints. No puppet integration is
# tested at this point.

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

CERTNAME="autopkgtest"

trap 'cleanup' EXIT

echo "Querying PuppetDB version ..."
puppetdb version

echo "Starting PuppetDB ..."
systemctl start puppetdb

echo "Checking read DB status (should be up)"
check_status_var read_db_up? true

echo "Checking write DB status (should be up)"
check_status_var write_db_up? true

echo "Issuing replace_facts for '$CERTNAME'"
curl -s -X POST \
  -H 'Content-Type:application/json' \
  -H 'Accept:application/json' \
  -d '{"certname": "'$CERTNAME'",
        "environment":"DEP-8",
        "values":{"debian":"rocks"},
        "producer_timestamp":"2017-08-07",
        "producer":"builder"}' \
  "http://localhost:8080/pdb/cmd/v1?command=replace_facts&version=5&certname=$CERTNAME" >/dev/null

sleep 5

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

echo "Checking the value of 'debian' fact"
query "nodes/${CERTNAME}/facts/debian" | jq -e '.[0].value == "rocks"'

echo "Reloading PuppetDB ..."
systemctl reload puppetdb

sed -n -e '/SIGHUP handler restarting TK apps/,$p' /var/log/puppetdb/puppetdb.log | \
    grep -qi "PuppetDB finished starting, disabling maintenance mode"
