#!/bin/bash

findkeymap () {
    local MAP=$1
    [[ ! -f $MAP ]] && \
	MAP=$(find ${kbddir}/keymaps -type f -name $MAP -o -name $MAP.\* | head -n1)
    [[ " $KEYMAPS " = *" $MAP "* ]] && return
    KEYMAPS="$KEYMAPS $MAP"
    case $MAP in
        *.gz) cmd=zgrep;;
        *.bz2) cmd=bzgrep;;
        *) cmd=grep ;;
    esac

    for INCL in $($cmd "^include " $MAP | cut -d' ' -f2 | tr -d '"'); do
        for FN in $(find ${kbddir}/keymaps -type f -name $INCL\*); do
            findkeymap $FN
        done
    done
}

install_local()
{
# FIXME: i18n stuff isn't really distro-independent :/
    if [[ -f /etc/sysconfig/keyboard || -f /etc/sysconfig/console/default.kmap ]]; then
	if [ -f /etc/sysconfig/console/default.kmap ]; then
            KEYMAP=/etc/sysconfig/console/default.kmap
	else
            . /etc/sysconfig/keyboard
	    if [[ $KEYTABLE && -d ${kbddir}/keymaps ]]; then
		[[ $KEYTABLE =~ *.uni ]] && UNIKEYMAP="$KEYTABLE.map" \
		    || UNIKEYMAP="$KEYTABLE.uni.map"
		KEYMAP="$KEYTABLE.map"
	    fi
	fi
	if [[ $KEYMAP ]]; then
            [ -f /etc/sysconfig/keyboard ] && inst /etc/sysconfig/keyboard
            inst loadkeys
            findkeymap $KEYMAP
            [[ $UNIKEYMAP ]] && findkeymap $UNIKEYMAP
	    [[ $GRP_TOGGLE ]] && findkeymap $GRP_TOGGLE.map
	    findkeymap delete.map
	    findkeymap backspace.map

            for FN in $KEYMAPS; do
		if [ -L $FN ]; then
		    TARGET=$(readlink -f $FN)
		    TG=$(echo $TARGET | sed -e 's/\.gz$//' -e 's/\.bz2$//')
		    LN=$(echo $FN | sed -e 's/\.gz$//' -e 's/\.bz2$//')
                    mkdir -p "$initdir/$(dirname $LN)"
                    ln -s "$TG" "$initdir/$LN"
                    FN=$TARGET
		fi
		inst $FN
		case $FN in
                    *.gz) gzip -d "$initdir$FN" ;;
                    *.bz2) bzip2 -d "$initdir$FN" ;;
		esac
            done
	fi
    fi

    if [ -f /etc/sysconfig/i18n ]; then
	. /etc/sysconfig/i18n
	inst /etc/sysconfig/i18n
	[[ $SYSFONT ]] || SYSFONT=latarcyrheb-sun16
	inst setfont

	for FN in ${kbddir}/consolefonts/$SYSFONT.* ; do
            inst "$FN"
            case $FN in
		*.gz) gzip -d "$initdir$FN" ;;
		*.bz2) bzip2 -d "$initdir$FN" ;;
            esac
	done
	[[ $SYSFONTACM ]] && inst ${kbddir}/consoletrans/$SYSFONTACM
	[[ $UNIMAP ]] && inst ${kbddir}/unimaps/$UNIMAP
    fi
}

for kbddir in /usr/lib/kbd /lib/kbd; do
	[[ -d ${kbddir} ]] && break
done

if [[ $hostonly ]]; then 
    install_local
else
    for i in $(find ${kbddir} -type f -print); do
	dracut_install $i
    done
    # remove unnecessary files
    rm -f "$initdir${kbddir}/consoletrans/utflist" 2>/dev/null
    find "$initdir${kbddir}/" -name README\* -exec rm -f '{}' \;
    dracut_install gzip bzip2
fi

dracut_install /lib/udev/console_init 
dracut_install setfont loadkeys
inst_rules 10-console.rules
inst_hook cmdline 20 "$moddir/parse-i18n.sh"
