#!/bin/sh -e
#
# 2011 Steven Armstrong (steven-cdist at armstrong.cc)
# 2012-2014 Nico Schottelius (nico-cdist at schottelius.org)
# 2014 Daniel Heule     (hda at sfs.biz)
#
# 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/>.
#


state_should="$(cat "$__object/parameter/state")"
state_is="$(cat "$__object/explorer/state")"
fire_onchange=''

if [ "$state_is" = "$state_should" ]; then
    exit 0
fi

# here we check only if the states are valid,
# emit messages and
# let awk do the work ...
case "$state_should" in
    absent)
        case "$state_is" in
            absent|nosuchfile)
                # nothing to do
            ;;
            wrongformat|wrongvalue|present)
                echo "remove" >> "$__messages_out"
                fire_onchange=1
            ;;
            *)
                echo "Unknown explorer state: $state_is" >&2
                exit 1
            ;;
        esac
    ;;
    present)
        case "$state_is" in
            nosuchfile)
                echo "create" >> "$__messages_out"
                fire_onchange=1
            ;;
            absent)
                echo "insert" >> "$__messages_out"
                fire_onchange=1
            ;;
            wrongformated|wrongvalue)
                echo "change" >> "$__messages_out"
                fire_onchange=1
            ;;
            present)
                # nothing to do
            ;;
            *)
                echo "Unknown explorer state: $state_is" >&2
                exit 1
            ;;
        esac
    ;;
    *)
        echo "Unknown state: $state_should" >&2
        exit 1
    ;;
esac

cat "$__type/files/remote_script.sh"

if [ -n "$fire_onchange" ]; then
    cat "$__object/parameter/onchange"
fi
