#!/bin/sh

##############################
## TODO: PIPESTATUS is bashism
##############################

logfile=cronbuild-apply-hooks.log
difffile=cronbuild-apply-hooks.diff
EXIT_MAGIC_CODE_NOTHING_TO_DO=77

error_hook()
{
    local hook_name="$1"; shift;
    echo "cronbuild: the hook $hook_name exited ubnormally. see $logfile for details."
    exit 2
}

do_hook()
{
    local hook="$1"; shift;
    local default_hook="$1"; shift;
    cronbuild_hook_name=`basename "$hook"`
    if [ -x "$hook" ]; then
	echo running "$hook" "$@"
	"$hook" "$@" 2>&1 | tee -a "$logfile" 
	[ ${PIPESTATUS[0]} -gt 0 ] && error_hook "$hook"
    else
	echo running default $cronbuild_hook_name "$default_hook" "$@"
	$default_hook "$@" 2>&1  | tee -a "$logfile"
	[ ${PIPESTATUS[0]} -gt 0 ] && error_hook "$default_hook"
    fi
    return 0
}

missing_hook()
{
    echo "cronbuild: the required hook $cronbuild_hook_name is missing."
    exit 3
}

add_changelog_builtin()
{
    local gear_specfile="$1"; shift;
    adate=$(date +"%Y%m%d")
    add_changelog -e "- repocop cronbuild $adate. At your service." $gear_specfile
}

if ! [ -d .gear ]; then 
    echo ".gear directory not found. exiting."
    exit 1
fi

[ -e "$logfile" ] && rm -f "$logfile"
[ -e "$difffile" ] && rm -f "$difffile"

gear_specfile="$(gear --command sh -- -c 'printf %s "$gear_specfile"')"
if [ -z "$gear_specfile" ] || ! [ -e "$gear_specfile" ]; then
    echo "cronbuild: can't find spec file. exiting."
    exit 1
fi

last_commit=`git show-ref --head HEAD | awk '{if ($2=="HEAD") print $1;}'`
last_commit=${last_commit:=HEAD}
do_hook ./.gear/cronbuild-update-source missing_hook $gear_specfile
git diff $last_commit > "$difffile"
if ! [ -s "$difffile" ]; then
    echo "INFO: source files did not change after cronbuild-update. Nothing to do.";
    rm -f "$difffile"
    exit $EXIT_MAGIC_CODE_NOTHING_TO_DO;
fi
rm -f "$difffile"
do_hook ./.gear/cronbuild-update-version gear-cronbuild-update-spec-timestamp $gear_specfile
do_hook ./.gear/cronbuild-add-changelog add_changelog_builtin $gear_specfile
git add $gear_specfile
