#! /bin/sh

PACKAGE=kbd

# kbdconfig - Configuration script for the `kbd' and `console-tools' packages
# Copyright (c) 1997, 1998  Yann Dirson
# Copyright (c) 1996  Dominik Kubla

KBDCONF_VERSION=1998.04.21

set -e

LIBDIR=/usr/share
LOCALLIBDIR=/usr/local/share
CONFDIR=/etc/${PACKAGE}

if [ $# -gt 0 ]
then
    case $1 in
    --help)
	echo
	echo "Usage: kbdconfig [ --help | --version ]"
	echo
	echo "  --help      show this information and exit"
	echo "  --version   show version information and exit"
	echo
	exit 0
	;;		
    --version)	
	echo "This is \`kbdconfig' for Linux Console Tools version ${KBDCONF_VERSION%-*}, Debian release ${KBDCONF_VERSION##*-}"
	exit 0
	;;
    *)
	echo "kbdconfig: Unknown option or parameter $1."
	echo "Use \`kbdconfig --help' for further information."
	exit 1
	;;
    esac
fi

if [ ! `id -u` = 0 ]
then
    echo "You must be root to run \``basename $0`'."
    exit 1
fi

case ${PACKAGE} in
kbd)
    KMAPEXT=map
    ;;
console-tools)
    KMAPEXT=kmap
;;
esac

function yesno # message [default choice] [secure]
{
    local REPLY=x
  
    # default choice
    if [ $# -ge 2 ]
    then
	DEFAULT=$2
    else
	DEFAULT=y
    fi
  
    # default font fallback ?
    if [ $# -ge 3 ]
    then
	SECURE=$3
    else
	SECURE=n
    fi
  
    # get answer
    until [ $REPLY = y -o $REPLY = n ]
    do
	if [ $SECURE = y ]
	then
	    echo "  NOTE: Answering anything else than 'y', 'n', or RETURN"
	    echo "        will reload the kernel's default keymap."
	fi
	echo -n $1 " [${DEFAULT}] "
	read REPLY
	if [ x$REPLY = x ]
	then
	    REPLY=$DEFAULT
	fi
	if [ $SECURE = y -a ! x$REPLY = xy -a ! x$REPLY = xn ]
	then
	    /bin/loadkeys -d
	fi
    done
    test x$REPLY = xy
}


function test_and_install
{
    if [ $keymap != NONE ]
    then
	# Maybe test the keymap before installing
	#
	if /usr/bin/showkey --keymap --timeout=1 >/dev/null 2>&1
	then
	    if yesno "Do you want to test the new keymap right now ?" y
	    then
		TMP=$(tempfile)
		echo "Saving keymap to ${TMP}"
		/usr/bin/dumpkeys >${TMP}
		/bin/loadkeys ${keymap%.gz}
		/usr/bin/showkey --keymap
		/bin/loadkeys ${TMP}
		rm ${TMP}
	    else
		echo "WARNING: keymap was not tested... use it at your own risk !"
	    fi
	else
	    echo "Sorry, I can't make you test this keymap now (showkey does not accept --keymap)."
	fi
    fi
  
    # Maybe install the new keymap
    #
    if yesno "Do you accept the chosen map for installation ?" y y
    then
	MAP_ACCEPTED=1
      
	echo Removing `rm -fv ${CONFDIR}/default.${KMAPEXT}{,.gz}`
      
	if [ "${keymap}" != "NONE" ] 
	then
	    echo -n "Copying "
	    case $keymap in
	    *.${KMAPEXT})
		cp -fpv $keymap ${CONFDIR}/default.${KMAPEXT} 2>/dev/null
		echo -n "Compressing "
		gzip -9fv ${CONFDIR}/default.${KMAPEXT}
		;;
	    *.${KMAPEXT}.gz)
		cp -fpv $keymap ${CONFDIR}/default.${KMAPEXT}.gz 2>/dev/null
		;;
	    esac
      
	fi
    fi
}


# try to guess COLUMNS if not set
#
if [ "${COLUMNS}" = "" -a -x /usr/bin/X11/resize ]
then
    eval `/usr/bin/X11/resize -u`
fi

# fallback to decent defaults if it failed
if [ "${COLUMNS}" = "" ]
then
    COLUMNS=80
fi


MAP_ACCEPTED=0
until [ $MAP_ACCEPTED = 1 ]
do
    # Security
    #
    echo -e "\nDo you want the kernel's default keymap to be reloaded ?"
    echo "If you can't press 'n' and hit RETURN, I will assume you need that."
    echo -n "Your choice: "
    read REPLY
    if [ x$REPLY != xn ]
    then
	/bin/loadkeys -d
    fi
  
    cat << EOT

Please choose one of the following keyboard tables for the VT devices:
----------------------------------------------------------------------
EOT

    # list all maps, compressed or not
    (
	# get the longest item-length from $LIBDIR and $LOCALLIBDIR
	cd $LIBDIR/keytables
	# the first item:
	ITEM=`ls -x -w ${COLUMNS} *.${KMAPEXT}{,.gz} 2>/dev/null |
	    sed -e 's/ /£/g' |
	    head -1 | sed 's/^\([^£]*££*\)[^£].*$/\1/'`
	if [ -d $LOCALLIBDIR/keytables ]
	then
	    cd $LOCALLIBDIR/keytables
	    # the first item:
	    ITEM1=`ls -x -w ${COLUMNS} *.${KMAPEXT}{,.gz} 2>/dev/null |
		sed -e 's/ /£/g' |
		head -1 | sed 's/^\([^£]*££*\)[^£].*$/\1/'`
	    # the longest:
	    if [ ${#ITEM} -lt ${#ITEM1} ] 
	    then
		ITEM=$ITEM1
	    fi
	fi
	# NOTE: bash doesn't want to assign spaces to variable, so we first use '£'
	#  (or I can't figure out how :)
	# a string of as may £ (for spaces) as an item, plus 3 for readability:
	SPACES=`echo -n ${ITEM} | tr -c "£" "£"`
	ls -1 {$LIBDIR,$LOCALLIBDIR}/keytables/*.${KMAPEXT}{,.gz} 2>/dev/null | # the files
	    sed -e 's+.*/++' | 			# keep basename only
	    sort | 
	    sed -e 's/\.gz//g' -e "s/\.${KMAPEXT}/${SPACES}/g" -e 's/£/ /g' |    # pad with enough spaces
	    fold -w ${#SPACES} | sed -e '/^ *$/d' | 	# strip spaces to needed length
	    awk -v ORS='' '{print}' | 		# remove newlines
	    fmt -w ${COLUMNS}			# make columns
	set +x
    )

  
    cat <<EOF | fold -s -w ${COLUMNS}

Or answer NONE to skip the loading of a keytable. (Just pressing RETURN will abort the procedure.)
EOF

    echo -n "What keytable to load? "; read keymap
    if [ -z "$keymap" ] 
    then
	echo "Leaving configuration unchanged."
	exit 0
    fi
  
    # Canonify name and check that wanted keymap exists
    #
    if [ $keymap = NONE ]
    then
	test_and_install
    else
	keymap=${keymap%.gz}
	keymap=${keymap%.${KMAPEXT}}.${KMAPEXT}
	if [ -r ${LIBDIR}/keytables/${keymap} ]
	then
	    keymap=${LIBDIR}/keytables/${keymap}
	    test_and_install
	elif [ -r ${LIBDIR}/keytables/${keymap}.gz ]
	then
	    keymap=${LIBDIR}/keytables/${keymap}.gz
	    test_and_install
	elif [ -r ${LOCALLIBDIR}/keytables/${keymap} ]
	then
	    keymap=${LOCALLIBDIR}/keytables/${keymap}
	    test_and_install
	elif [ -r ${LOCALLIBDIR}/keytables/${keymap}.gz ]
	then
	    keymap=${LOCALLIBDIR}/keytables/${keymap}.gz
	    test_and_install
	else
	    echo "Sorry, cannot find keymap ${keymap}."
	fi
    fi
done

# Maybe load the last installed keymap
#
if yesno "Do you want changes to take effect right now ?" y
then
    if [ "$keymap" != NONE ]
    then
	/bin/loadkeys ${CONFDIR}/default.${KMAPEXT}
    else
	/bin/loadkeys -d
    fi
else
  echo "Any changes you made will take effect after the next boot."
fi
