#!/bin/sh
#
# 2011 Nico Schottelius (nico-cdist at schottelius.org)
#
# 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/>.
#
#
# Run explorers - FIXME: this function is ugly
#

__cdist_explorer_run()
{
   [ $# -eq 5 ] || __cdist_usage "<global|type> <local explorer dir> <remote explorer dir> <remote out dir> <local out dir>"

   # Ensure there is at least one explorer
   num="$(ls -1 "$__cdist_explorer_dir" | wc -l)"
   if [ "$num" -lt 1 ]; then
      __cdist_exit_err "${__cdist_explorer_dir}: Contains no explorers"
   fi

   # Check whether to setup variable for type explorer
   case "$1" in
      global)
      ;;
      type)
         # FIXME: think about how and where this gets setup!
         "$__cdist_name_var_object=\"$(__cdist_remote_object_dir "$__cdist_object_self")\""
      ;;
   esac

   # Transfer explorers
   __cdist_dir push "$2" "$3"

   # Create output directory
   __cdist_run_remote mkdir -p "$4"

   # Execute all explorers - FIXME: isolate cd call?
   cd "$2";
   # FIXME: cleanup double variable, no need when in directory
   for __cdist_explorer_run_explorer in *; do
      __cdist_explorer_explorer_name="${__cdist_explorer_run_explorer##*/}"

      if [ -f "$__cdist_explorer_run_explorer" ]; then
         if [ ! -x "$__cdist_explorer_run_explorer" ]; then
            __cdist_exit_err "Explorer \"$__cdist_explorer_run_explorer\" exists, but is not executable."
         fi

      else
         if [ -e "$__cdist_explorer_run_explorer" ]; then
            __cdist_exit_err "Explorer \"$__cdist_explorer_run_explorer\" exists, but is not a file."
         fi
      fi

      # FIXME: no need for remote out dir probably?
      # or should we leave it and continue using __cdist_dir pull?
      __cdist_run_remote \
         "export $__cdist_name_var_explorer=\"$__cdist_remote_explorer_dir\";" \
         "export $__cdist_name_var_global=\"$__cdist_remote_out_dir\";" \
         "$3/$__cdist_explorer_run_explorer" ">" \
            "$4/$__cdist_explorer_run_explorer" || \
               __cdist_exit_err "Explorer $__cdist_explorer_run_explorer failed."
   done

   # Transfer results back
   __cdist_dir pull "$4" "$5"
}