#!/bin/sh -e
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*- 
# $Id: alternatives,v 1.3 2005/10/19 13:24:53 inger Exp $ 

. /usr/share/alternatives/functions

PROG="${0##*/}" #program name

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

alterator backend for alternatives manipulations

Valid options are:
  -h, --help	display help screen
  -l, --list	get list of avaliable locales
  -t, --type	check for existance
  -d, --delete	(empty action, required for backend)
  -r, --read	read locale information
  -w, --write	change locale information

Report bugs to <legion@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o h,l:,d:,r:,w:,t: -l help,list:,delete:,read:,write:,type: -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-l|--list) shift; dir="$1"
			if [ "$dir" = "/" ] ;then
			    echo "available d"
			    echo "view r"
			elif [ "$dir" = "available" ]; then
			    alternatives-list | sed -ne 's,^\(.*\) points to.*,\1 r,p' | sort -ru
			fi
			;;
		-d|--delete)
			#ignore
			shift;dir="$1";
			;;
		-t|--type)
			#ignore
			shift;dir="$1";
			;;
		-r|--read) shift; dir="$1"
			alternative="${dir#view}"
			[ "$alternative" != "$dir" ] || exit 1
			
			if ! cut -f1 "$package_dir"/* | grep -sxF "$alternative" >/dev/null 2>&1; then
			    printf 'ERROR: %s\n' "Can't find alternative: $alternative" >&2
			    exit 1    
			fi

			alternative_name="${alternative##*/}"
			[ -n "$alternative_name" ] || 
			    { printf 'ERROR: %s\n' "Can't extract alternative name: $alternative">&2; exit 1; }
			    
			status=auto
			if grep -qs "^$alternative[[:space:]].*manual$" "$manual_file"; then
			    status=manual
			fi
			printf 'status:%s\n' "$status"

			printf 'points:'
			alternatives-list "$alternative" | sed -ne 's,^.* points to \(.*\)$,\1,p'			

			printf 'candidates:'
			grep -h "^$alternative[[:space:]]" "$package_dir"/* | 
			    sort -u | 
			    sed 's,[[:space:]]\+,\t,g' | 
			    cut -f2 | 
			    tr '\n' ' '
			echo			
			;;
		-w|--write) shift
			alternative=
			status=
			candidate=
			while read l; do
				option="${l%%:*}"
				value="${l#*:}"
				[ "$option" != "alternative" ] || alternative="$value"
				[ "$option" != "candidate" ] || candidate="$value"
				[ "$option" != "status" ] || status="$value"
			done

			[ -n "$status" -a -n "$candidate" ]

			if [ "$status" = "auto" ]; then
			    alternatives-auto "$alternative" && alternatives-update
			    exit 0
			fi

			if [ -n "$candidate" -a "$status" = "manual" -a -f "$candidate" ]; then
			    alternatives-manual "$alternative" "$candidate" && alternatives-update
			fi
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done
