#!/bin/sh -e
#
# 2015-2016 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/ttl" ]; then
   for conflicts_ttl in 'docker-container-id' 'http' 'script' 'tcp' 'timeout'; do
      if [ -f "$__object/parameter/${conflicts_ttl}" ]; then
         echo "Can not use --ttl together with --${conflicts_ttl}." >&2
         exit 1
      fi
   done
fi
if [ ! -f "$__object/parameter/interval" ]; then
   for requires_interval in 'docker-id' 'http' 'script' 'tcp'; do
      if [ -f "$__object/parameter/${requires_interval}" ]; then
         echo "When using --${requires_interval} you must also define --interval." >&2
         exit 1
      fi
   done
fi
if [ -f "$__object/parameter/docker-container-id" ] && [ ! -f "$__object/parameter/script" ]; then
   echo "When using --docker-container-id you must also define --script." >&2
   exit 1
fi

# Generate json config file
(
echo "{"
printf '   "check": {\n'
printf '      "name": "%s"\n' "$name"
cd "$__object/parameter/"
for param in *; do
   case "$param" in
      state|name) continue ;;
      *)
         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 -
