# Function to do all of the configuration file migration work
#
_clean_configs()
{
    #
    # Usage: _clean_configs [-n|-v] new_dir old_dir ...
    #
    # Across all the files in the new_dir and old_dir args, match
    # names and pick the most recently modified version and leave
    # this (same mode and modification date) in new_dir
    #
    # -n option is show-me for benign debugging
    # -v option is verbose mode for active debugging
    #

    if [ $# -gt 0 -a X"$1" = "X-n" ]
    then
	MKDIR="echo + mkdir "
	CP="echo + cp "
	shift
    else
	MKDIR=mkdir
	CP=cp
    fi

    _verbose=false
    if [ $# -gt 0 -a X"$1" = "X-v" ]
    then
	_verbose=true
	shift
    fi

    if [ $# -lt 2 ]
    then
	echo >&2 "Usage: _clean_configs [-n|-v] new_dir old_dir ..."
	return
    fi

    _new="$1"
    if [ ! -d "$_new" ]
    then
	$verbose && echo >&2 + mkdir -p "$_new"
	$MKDIR -p "$_new"
    fi

    shift
    for _dir
    do
	[ "$_dir" = "$_new" ] && continue
	if [ -d "$_dir" ]
	then
	    ( cd "$_dir" ; find . -type f -print ) \
	    | sed -e 's/^\.\///' \
	    | while read _file
	    do
		_want=false
		if [ -f "$_new/$_file" ]
		then
		    # file exists in both directories, pick the more
		    # recently modified one
		    #
		    _try=`find "$_dir/$_file" -newer "$_new/$_file" -print`
		    [ -n "$_try" ] && _want=true
		else
		    _want=true
		fi
		if $_want
		then
		    _dest=`dirname $_new/$_file`
		    if [ ! -d "$_dest" ]
		    then
			$verbose && >&2 echo + mkdir "$_dest"
			$MKDIR "$_dest"
		    fi
		    $_verbose && echo >&2 + cp -p "$_dir/$_file" "$_new/$_file"
		    $CP -p "$_dir/$_file" "$_new/$_file"
		fi
	    done
	fi
    done
}

