#!/bin/sh

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

print_version()
{
	cat <<EOF
$PROG version @VERSION@

Written by Stanislav Ievlev, Anton Farygin

Copyright (C) 2005 ALT Linux Team
EOF
	exit
}


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

alterator backend to get list of avaliable video drivers

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -l, --list	get list of available vendors/drivers
  -t, --type	check for vendor/driver existance
  -d, --delete	(empty action, required for backend)
  -r, --read	read driver information
  -w, --write	(empty action, required for backend)

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

VCARDINFO=/usr/bin/vcardinfo

dump_drv_data()
{
	"$VCARDINFO"
}

#quote filenames,to made it usable in filesystem
encode_drv_name()
{
	#hide / symbols - both for input and output
	sed $sed_options 's,%,%%,g
	s,|,%|,g
	s,/,|,g'
}

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

search_drv()
{
	dump_drv_data|grep "^$1;" >/dev/null
	return $?
}

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

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		-l|--list)
			shift;dir="$1";
			if [ "$dir" == "/" ] ;then
				echo "auto_detect d"
				echo "drivers d"
			elif [ "$dir" == "drivers" ];then
				dump_drv_data|encode_drv_name|
					sed 's,.*,& r,'
			elif [ "$dir" == "auto_detect" ];then
				pciscan -c003 -q slot|encode_drv_name|
					sed 's,.*,& r,'
			fi
			;;
		-d|--delete)
			#ignore
			shift;drv="$1";
			;;
		-t|--type)
			shift;drv="$1";
			if [ "$drv" == "auto_detect" ];then
				echo "auto_detect d"
			elif [ "$drv" == "drivers" ];then
				echo "drivers d"
			fi
			#TODO: also check for existance of auto_detect and drivers data
			;;
		-r|--read)
			shift;drv="$1";
			if [ "${drv:0:12}" == "auto_detect/" ];then
			    echo "name:`pciscan -c003 -s${drv:12} -qname 2>/dev/null`"
			    echo "driver:`x11createconfig -c -s${drv:12} 2>/dev/null`"
			fi
			;;
		-w|--write)
			#ignore
			shift;drv="$1";
			while read l; do
				echo -n
			done
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done
