#!/bin/sh
#
# Copyright (c) 2003,2004 ALT Linux Ltd.
# Copyright (c) 2003,2004 Stanislav Ievlev <inger@altlinux.org>
#
# alternatives-upgrade - utility from alternatives subsystem
# converts all configs from old format (XML based) to current
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#

if [ "$0" = ./alternatives-upgrade ]; then
	. ./functions
	lib_dir="$(/bin/pwd)"
else
	. /usr/share/alternatives/functions
fi

exit_handler()
{
	local rc=$?
	trap - 0
	rm -rf -- $TEMPFILE
	exit $rc
}

trap exit_handler 0 1 2 3 9 13

upgrade_file()
{
    echo "warning: file $1 has deprecated format" >&2
    cat $1|sed $sed_options 's/.*link[[:punct:]]>\(.*\)<.*/link	\1/
    s/.*real[[:punct:]]>\(.*\)<.*/real	\1/
    s/.*current[[:punct:]]>\(.*\)<.*/real	\1/
    s/.*weight[[:punct:]].*>\(.*\)<.*/weight	\1/'|
    awk $awk_options -f $lib_dir/upgrade.awk 
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options] 

The alternatives-upgrade program converts alternatives config files from old
format (XML based) to new.
This utility process only files from $package_dir directory.

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
				     
Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}


TEMP=`getopt -n $PROG -o h,v -l help,version -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

dump_file=$auto_dir/dump.xml

#upgrade all configs
for i in $package_dir/*
do
    grep -qs candidate $i || continue
    TEMPFILE=`mktemp -t $PROG.XXXXXX`
    upgrade_file $i >$TEMPFILE
    mv "$TEMPFILE" $i
    chmod 644 $i
done

#remove old links
rm -f $root_dir/*\|*

#convert dump file to manual alternatives
[ -f $dump_file ] || exit 

grep -qs candidate $dump_file
if [ $? -eq 0 ]; then
    upgrade_file $dump_file |
    while read i
    do
	candidate="${i#*	}"
	alternatives-manual "${i%%	*}" "${candidate%	*}"
    done
fi

rm -f $dump_file
