#!/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

TEMPFILE=
cleanup()
{
	trap - EXIT
	rm -f -- $TEMPFILE
	exit "$@"
}

exit_handler()
{
	cleanup $?
}

signal_handler()
{
	cleanup 143
}

trap exit_handler EXIT
trap signal_handler HUP PIPE INT QUIT TERM

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 
}

show_help()
{
	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
	exit
}


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

while :; do
	case "$1" in
		--) shift; break ;;
		*) parse_common_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` || exit
    upgrade_file $i >$TEMPFILE
    mv "$TEMPFILE" $i
    TEMPFILE=
    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
