#!/bin/sh -e
#
# 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/>.
#

cdist_type="${__type##*/}"
watch_type="${cdist_type##*_}"
conf_dir="/etc/consul/conf.d"
conf_file="watch_${watch_type}_${__object_id}.json"
state="$(cat "$__object/parameter/state")"

# Sanity checks
if [ -f "$__object/parameter/filter-service" -a -f "$__object/parameter/filter-state" ]; then
   echo "Use either --filter-service or --filter-state but not both." >&2
   exit 1
fi

# Generate json config file
(
echo "{"
printf '   "watches": [{\n'
printf '      "type": "%s"\n' "$watch_type"
for param in $(ls "$__object/parameter/"); do
   case "$param" in
      state) continue ;;
      filter-*)
         key="${param##*-}"
         printf '      ,"%s": "%s"\n' "$key" "$(cat "$__object/parameter/$param")"
      ;;
      *)
         key="$(echo "$param" | tr '-' '_')"
         printf '      ,"%s": "%s"\n' "$key" "$(cat "$__object/parameter/$param")"
      ;;
   esac
done
# end watches
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 -
