#!/bin/sh
#
# 2015 Steven Armstrong (steven-cdist at armstrong.cc)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

name="$(cat "$__object/parameter/name" 2>/dev/null || echo "$__object_id")"
conf_dir="/etc/consul/conf.d"
conf_file="check_${name}.json"
state="$(cat "$__object/parameter/state")"

# Sanity checks
if [ -f "$__object/parameter/script" -a -f "$__object/parameter/ttl" ]; then
   echo "Use either --script together with --interval OR --ttl, but not both" >&2
   exit 1
fi
if [ -f "$__object/parameter/script" -a ! -f "$__object/parameter/interval" ]; then
   echo "When using --script you must also define --interval" >&2
   exit 1
fi

# Generate json config file
(
echo "{"
printf '   "check": {\n'
printf '      "name": "%s"\n' "$name"
for param in $(ls "$__object/parameter/"); do
   case "$param" in
      state|name|interval) continue ;;
      script)
         printf '      ,"script": "%s"\n' "$(cat "$__object/parameter/script")"
         printf '      ,"interval": "%s"\n' "$(cat "$__object/parameter/interval")"
      ;;
      *)
         key="$(echo "$param" | tr '-' '_')"
         printf '      ,"%s": "%s"\n' "$key" "$(cat "$__object/parameter/$param")"
      ;;
   esac
done
# end check
echo "   }"
# end json file
echo "}"
) | \
require="__directory${conf_dir}" \
   __config_file "${conf_dir}/${conf_file}" \
      --owner root --group consul --mode 640 \
      --state "$state" \
      --onchange 'service consul status >/dev/null && service consul reload || true' \
      --source -
