#!/bin/bash
set -e
read td < <(mktemp --directory --tmpdir=/run/chrony-graph .chrony-graph.XXX)
OUTPUT_DIR=/run/chrony-graph/.chrony-graph
TITLES=~/titles
trap "rm -rf '${td}'" EXIT
td="${td}/chrony-graph"
mkdir "${td}"
if pushd "${td}" > /dev/null
then
	do_run='maybe'
	if ! test -d "${OUTPUT_DIR}"
	then
		mkdir -v "${OUTPUT_DIR}"
		touch -d '@1' "${OUTPUT_DIR}"
	fi
	for i in /var/log/chrony/*
	do
		if ! test -e "${i}"
		then
			do_run=
			echo "no logs"
			break
		fi
		if test -d "${OUTPUT_DIR}" && test "${i}" -nt "${OUTPUT_DIR}"
		then
			do_run='newer'
			break
		fi
	done
	if test -f "${TITLES}" && test "${TITLES}" -nt "${OUTPUT_DIR}"
	then
		do_run='newer'
	fi
	if test "${do_run}" = 'maybe'
	then
		do_run=
		echo "no news"
	fi
	if test -n "${do_run}"
	then
		export OUTPUT_DIR
		export TITLES
		export CHRONY_LOGDIR='/var/log/chrony'
		(
			if rpm -q --qf '%{NAME} %{VERSION}-%{RELEASE} - %{DISTRIBUTION}\n' chrony-graph 2>> 'stderr'
			then
				: good
			else
				echo 'rpm(1) failed'
			fi
			ccs='chronyc -n sources'
			if chronyc -n sources > "${ccs}" 2>> 'stderr'
			then
				sed -i -n '/^\^[+*]/p' "${ccs}"
			else
				echo 'chronyc(1) failed'
			fi
			if head -n -0 /etc/chrony.conf /etc/chrony.d/*.conf "${ccs}" /proc/uptime 'stderr' &> ".$$"
			then
				grep -Evh '^[[:blank:]]*([!#;%]|$)' ".$$"
			else
				echo 'head(1) failed'
			fi
			if test -s 'stderr'
			then
				logger --id=$PPID.$$ --tag 'chrony-graph' < 'stderr'
			fi
		) &> 'notes'
		if bash /usr/libexec/chrony-graph/run
		then
			touch "${OUTPUT_DIR}"
		fi
	fi
	popd > /dev/null
fi
