#!/bin/sh -e
#
# Copyright (c) 2003,2004 ALT Linux Ltd.
# Copyright (c) 2003,2004 Stanislav Ievlev <inger@altlinux.org>
# decode function is written by  Fr. Br. George <george@altlinux.ru>
#
# This files defines functions used by alternatives scripts
#
# 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.
#

. shell-error
. shell-args

#made sorting in C locale
export LC_COLLATE=C

#main work files and directories
root_dir=/etc/alternatives

auto_dir=$root_dir/auto
package_dir=$root_dir/packages.d
links_dir=$root_dir/links
manual_file=$root_dir/manual

[ -f $manual_file ] || touch $manual_file #create manual config file if nesessary

lib_dir=/usr/share/alternatives

awk_options="--traditional"
#sed_options="--posix" #WARNING: use this flag only for debug

print_version()
{
	cat <<EOF
$PROG version 0.4

Written by Stanislav Ievlev

Copyright (C) 2003-2008 ALT Linux Team
EOF
	exit
}

#generate current state of alternatives
# cat all data, skip non-existence files and
# choose weights using awk script
get_list()
{
    ls -1 $package_dir/* >/dev/null 2>&1 #check are some files in autodir available
    [ $? -ne 0 ] && return 0

    local line
    (for i in "$@"; do echo "$i $i ignore";done ; cat $manual_file $package_dir/*) |
    tr -s '	' ' '|
    while read -r line
    do
	line=${line## }
	line=${line%% }
	[ -z "${line##* * *}" ] || print_warning "broken config line: $line"
	local file="${line#* }"
	file="${file%% *}"
	[ -f "$file" -o -d "$file" ] && echo $line
    done | awk $awk_options -f $lib_dir/list.awk 
}


#simple pathname encoding
#/   ---> |
#|   ---> %|
#%   ---> %%
alternatives_encode()
{
    sed $sed_options 's,%,%%,g
	 s,|,%|,g
	 s,/,|,g'
}

alternatives_decode()
{
    local separator=$(printf '\007')
    sed  $sed_options "s,%\(.\),$separator\1,g
	    s,\([^$separator]\|^\)|,\1/,g
	    s,\([^$separator]\|^\)|,\1/,g
	    s,$separator,,g"
}
