#!/usr/local/bin/bash

#############
# FUNCTIONS #
#############

# Display usage then exit
function usage {
  local libexecdir=/usr/local/libexec/puppetdb
  local files="${libexecdir}/puppetdb-*"

  # Seems trying to match an asterisk is hard in bash
  if expr $files : ".*\*.*" > /dev/null; then
    echo "ERROR: No sub-commands found in ${libexecdir}"
    exit 1
  fi

  cat <<EOD
usage: $(basename $0) [--help] <command> [<args>]

The most commonly used puppetdb commands are:
EOD

  # Iterate and display commands in the libexec folder
  for f in $files; do
    if [ ! -e $f ]; then
      continue
    fi
    echo "   ${f##*/puppetdb-}"
  done

  cat << EOD

See '$(basename $0) <command> -h' for more information on a specific command.
EOD
  exit 0
}

# Execute the subcommand if available.
#
# $1 - subcommand
# $n - arguments
#
# Example:
#
#   execsubcommand export -o test.dump -H 1.1.1.1
#
function execsubcommand {
  sub=$1
  shift
  cmd="/usr/local/libexec/puppetdb/puppetdb-${sub}"

  if [ -e ${cmd} ]; then
    exec "${cmd}" "$@"
  else
    echo "puppetdb: '${sub}' is not a puppetdb command. See '$(basename $0) --help'."
  fi
}

########
# MAIN #
########

if [ -z $1 ] || [ $1 = "--help" ] || [ $1 = "-h" ]; then
  usage
fi

execsubcommand "$@"
