#!/bin/sh

set -e

PACKAGE=console-tools
CONFDIR=/etc/${PACKAGE}
KMAPEXT=kmap

if [ $# != 1 ]
then
    echo >&2 "Usage: `basename $0` keymap_file"
    exit 1
fi

keymap=$1

do_preserving_keymap()
# execute shell command-line preserving the keymap
{
    # save keymap
    TMP=`tempfile`
    /usr/bin/dumpkeys >${TMP}

    eval "$*"

    # restore keymap
    /bin/loadkeys -q ${TMP}
    rm ${TMP}
}

# Be extra safe
mkdir -p ${CONFDIR}

NEW=`tempfile`.gz
CONFFILE=${CONFDIR}/default.${KMAPEXT}.gz

backup_and_install()
{
    # Keep a backup if no backup already exists
    [ -r ${CONFFILE} -a ! -r ${CONFDIR}/default.old.${KMAPEXT}.gz ] && 
	mv ${CONFFILE} ${CONFDIR}/default.old.${KMAPEXT}.gz
    # Also backup this one, although it should probably not exist
    [ -r ${CONFFILE%.gz} -a ! -r ${CONFDIR}/default.old.${KMAPEXT} ] && 
	mv ${CONFFILE%.gz} ${CONFDIR}/default.old.${KMAPEXT}
    
    mv $NEW $CONFFILE
}


do_preserving_keymap "loadkeys -q $keymap ; dumpkeys | gzip -9n > $NEW"

# if diff is available, use it to install only if needed
if [ -r $CONFFILE -a -x /usr/bin/diff ]
then
    if diff -q $CONFFILE $NEW >/dev/null
    then
	rm $NEW
    else
	backup_and_install
    fi
else
    backup_and_install
fi
