#!/bin/sh

# Parse directive names out of Nagios' xdata/xodtemplate.c.

EXIT_USAGE=1
EXIT_INPUT_FILE_DOESNT_EXIST=2

posix_mktemp(){
  # Securely create a temporary file under ${TMPDIR} using the
  # template "tmpXXXXXX", and echo the result to stdout. This works
  # around the absence of "mktemp" in the POSIX standard.
  printf 'mkstemp(template)' | m4 -D template="${TMPDIR:-/tmp}/tmpXXXXXX"
}

if [ $# -lt 1 ]; then
    echo "Usage: $0 <path-to-xodtemplate.c>"
    exit $EXIT_USAGE
fi


INFILE="${1}"
TEMPFILE="$(posix_mktemp)"

if [ ! -f "$INFILE" ]; then
    echo "Error: input file $INFILE doesn't exist."
    exit $EXIT_INPUT_FILE_DOESNT_EXIST
fi

# The list of weekday names, taken from xdata/xodtemplate.c. The
# Nagios strcmp parser doesn't look for them individually. Since
# they're unlikely to change, appending them manually sounds
# reasonable to me.
printf '"sunday"
"monday"
"tuesday"
"wednesday"
"thursday"
"friday"
"saturday"
' >> "${TEMPFILE}"

# This grabs all of the variable names that are explicitly checked for
# with strcmp in xdata/xodtemplate.c. We include these because some
# valid variable names (e.g. "hostgroups") are implicitly mapped to
# "real" variables whose names differ.
#
# The "name", "register", and "use" directives are special (literally,
# they get the "special" font in nagios-mode.el), so we drop them from
# the list.
#
# Before we parse the names, though, we move each !strcmp to its own
# line, which greatly simplifies the parsing.
VARCMP_REGEX='.*!strcmp(variable,[[:space:]]*"\([A-Za-z_]\{1,\}\)").*'
sed "s/\!strcmp(/\n\!strcmp(/g" < "${INFILE}" \
  | sed -n "s/${VARCMP_REGEX}/\"\1\"/p"       \
  | sed '/^"name\|use\|register"$/d'          \
  >> "${TEMPFILE}"

# Finally, sort the list and print it.
sort < "${TEMPFILE}" | uniq

# ... and clean up
rm "${TEMPFILE}"
