#!/bin/bash

# Original written and copyright by Adam Majer <adamm@zombino.com>
#
# This file is 100% public domain. Use it for whatever you wish.
#

function update_configs()
{
	[ -x /usr/share/misc/config.${1} ] || return 0
	LATEST_VERSION=`/usr/share/misc/config.${1} -t`
	UPDATE_FILES=`find -type f | grep "/config\.${1}\$"`

	echo "Latest version of config.${1} file is ${LATEST_VERSION}"
	for i in $UPDATE_FILES; do
		head -1 "$i" | grep -q '#!.*\/bin\/sh'
		EXE=$?
		if [ -x "$i" ] || [ $EXE -eq 0 ]; then
			V=`sh -e "${i}" -t`
			echo "Updating ${V} version file at  ${i}"
			if [[ "$LATEST_VERSION" > "$V" ]]; then
				mv "${i}" "${i}.orig_update"
				ln -s /usr/share/misc/config.$1 "${i}"
			else
				echo "WARNING: Debian version of config.${1} is older than this package's upstream."
			fi
		fi
	done
	return 0
}


function reset_configs()
{
	UPDATED_FILES=`find -type l | grep "/config\.${1}\$"`
	for i in ${UPDATED_FILES}; do
		if [ -e "${i}.orig_update" ]; then
			mv "${i}.orig_update" "${i}"
		fi
	done
	return 0
}


# Check if we are updating, reseting or whatever
case "$1" in
	update)
		update_configs sub
		update_configs guess
		;;
	reset)
		reset_configs sub
		reset_configs guess
		;;
	*)
		echo "The only allowed parameters are 'update' or 'reset'"
		exit 2;
		;;
esac

exit 0
