#!/bin/sh
#
# Parse the macro names out of Nagios' include/macros.h.
#
# Operates on whatever file you give it. That should probably be
# include/macros.h. Just sayin'.
#

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 <input_file>"
    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

# Grabs all of the "#define MACRO..." lines, except for MACRO_X_COUNT
# and MACRO_ENV_VAR_PREFIX which aren't real macros, and outputs the
# macro name (everything after "MACRO_") enclosed in quotes and dollar
# signs, appropriate to be copy/pasted directly into nagios-mode.el.
MACRO_REGEX='#define[[:space:]]\{1,\}MACRO_\([^[:space:]]\{1,\}\)[[:space:]]\{1,\}.*'
sed -n "s/${MACRO_REGEX}/\"\$\1\$\"/p" "${INFILE}" \
      | sed '/X_COUNT\|ENV_VAR_PREFIX/d'           \
      >> "${TEMPFILE}"

# Add "$ARG1$", "$ARG2$",... "$ARG<max>$" to the list, where <max> is
# defined in macros.h.
MAXARG_REGEX='#define[[:space:]]\{1,\}MAX_COMMAND_ARGUMENTS[[:space:]]\{1,\}\([1-9][0-9]*\).*'
MAXARG=$(sed -n "s/${MAXARG_REGEX}/\1/p" "${INFILE}")

for argnum in `seq 1 $MAXARG`; do
    echo "\"\$ARG${argnum}\$\"" >> "${TEMPFILE}"
done

# Also the "$USER<N>$" macros, similar to the above.
MAXUSER_REGEX='#define[[:space:]]\{1,\}MAX_USER_MACROS[[:space:]]\{1,\}\([1-9][0-9]*\).*'
MAXUSER=$(sed -n "s/${MAXUSER_REGEX}/\1/p" "${INFILE}")

for argnum in `seq 1 $MAXUSER`; do
    echo "\"\$USER${argnum}\$\"" >> "${TEMPFILE}"
done

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

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