#!/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/>.
#
#
# Generate code from one object (object must be relative path!)
# WARNING: OUTPUT ON STDOUT, ERRORS NEED TO BE ON STDERR!
#

. cdist-config
[ $# -eq 3 ] || __cdist_usage "<target host>" "<object>" "<type>"
set -eu

__cdist_target_host="$1"; shift
__cdist_object_self="$1"; shift
__cdist_gencode_type="$1"; shift

__cdist_type="$(__cdist_type_from_object "$__cdist_object_self")"
__cdist_type_gencode="$(__cdist_type_gencode "$__cdist_type" "$__cdist_gencode_type")"
__cdist_code_output="$(__cdist_object_code "$__cdist_object_self" "$__cdist_gencode_type")"

# export variables for the gencode script
export __object_id="$(__cdist_object_id_from_object "$__cdist_object_self")"
export __object="$(__cdist_object_dir "$__cdist_object_self")"
export __global="$__cdist_out_dir"

if [ -x "$__cdist_type_gencode" ]; then
   __cdist_exec_fail_on_error "$__cdist_type_gencode" > "$__cdist_tmp_file"
else
   if [ -e "$__cdist_type_gencode" ]; then
      __cdist_exit_err "$__cdist_type_gencode exists, but is not executable"
   fi

   # Ensure it's empty, if there is no gencode
   : > "$__cdist_tmp_file"
fi

# Only create code, if gencode created output
if [ "$(wc -l < "$__cdist_tmp_file")" -gt 0 ]; then
   cat - "$__cdist_tmp_file" << eof > "$__cdist_code_output"
#
# The following code was generated by $__cdist_type_gencode
#

eof
   chmod u+x "${__cdist_code_output}"
fi
