#!/bin/sh
#$Id$
#Copyright (c) 2020-2021 Pierre Pronchery <khorben@defora.org>
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.



#variables
DEVNULL="/dev/null"
DRYRUN=0
PACKAGE="configure"
PREFIX="/usr/pkg"
LIBEXECDIR="$PREFIX/libexec"
PROGNAME="configure-update"
PROJECTCONF="project.conf"
VERBOSE=1
#executables
CMP="cmp"
CP="cp -f"
DEBUG=
FIND="find"


#functions
#configure_update
_configure_update()
{
	target="$1"
	scriptdir="$LIBEXECDIR/$PACKAGE/scripts"

	if [ ! -f "$target/$PROJECTCONF" ]; then
		_error ""
		exit $?
	fi
	(cd "$scriptdir" && $DEBUG $FIND */ -name '*.sh') | while read script; do
		[ -f "$target/$script" ]			|| continue
		$DEBUG $CMP "$scriptdir/$script" "$target/$script" > "$DEVNULL"
		[ $? -ne 0 ]					|| continue
		_info "Updating script $script"
		if [ $DRYRUN -eq 0 ]; then
			$DEBUG $CP "$scriptdir/$script" "$target/$script" \
								|| return 2
		fi
	done
}


#debug
_debug()
{
	echo "$@" 1>&3
	"$@"
}


#error
_error()
{
	echo "$PROGNAME: $@" 1>&2
	return 2
}


#info
_info()
{
	[ $VERBOSE -ge 1 ] && echo "$PROGNAME: $@"
}


#usage
_usage()
{
	echo "Usage: $PROGNAME -nqv [target...]" 1>&2
	return 1
}


#main
while getopts "O:nqv" name; do
	case $name in
		O)
			export "${OPTARG%%=*}"="${OPTARG#*=}"
			;;
		n)
			DRYRUN=1
			;;
		q)
			VERBOSE=0
			;;
		v)
			VERBOSE=$((VERBOSE + 1))
			;;
		?)
			_usage
			exit $?
			;;
	esac
done
shift $(($OPTIND - 1))

exec 3>&1
if [ $# -eq 0 ]; then
	_configure_update "."
else
	for target in "$@"; do
		_configure_update "$target"
	done
fi
