#!/bin/sh
### BEGIN INIT INFO
# Provides:          keyboard-setup
# Required-Start:    mountkernfs
# Required-Stop:
# Should-Start:      keymap udev
# X-Start-Before:    checkroot
# Default-Start:     S
# Default-Stop:
# X-Interactive:     true
# Short-Description: Set preliminary keymap
# Description:       Set the console keyboard as early as possible
#                    so during the file systems checks the administrator
#                    can interact.  At this stage of the boot process
#                    only the ASCII symbols are supported.
### END INIT INFO

DEFAULT_FONT="Uni2-VGA16"

# This script is not used by keyboard-configuration.  It is used
# jointly by console-setup and console-setup-mini

main() {
    case "$1" in
        stop|status)
            # keyboard-setup isn't a daemon
            ;;
        start|force-reload|restart|reload)
            do_start
            ;;
        *)
            echo 'Usage: /etc/init.d/keyboard-setup {start|reload|restart|force-reload|stop|status}'
            exit 1
            ;;
    esac

    exit 0
}

do_start() {
    local param font should_run dont_run
    for param in $(cat /proc/cmdline /live/config/cmdline 2>/dev/null); do
        case "$param" in
                       lang=*) should_run=true  ;;
        kbd=*|kbopt=*|kbvar=*) should_run=true  ;;
          noloadkeys|conkbd=*)   dont_run=true  ;;
                    confont=*) font=${param#*=} ;;
        esac
    done

    . /lib/lsb/init-functions

    if [ -n "$should_run" -a -z "$dont_run" ]; then
        normal_start
        [ ${#font} -gt 0 ] && set_console_font $font
    else
        set_console_font $font
    fi

    exit 0
}

normal_start() {
    set -e
    test -f /bin/setupcon || return 0

    if [ -f /etc/default/locale ]; then
        # In order to permit auto-detection of the charmap when
        # console-setup-mini operates without configuration file.
        . /etc/default/locale
        export LANG
    fi

    log_action_begin_msg "Setting preliminary keymap"
    if setupcon 2>/dev/null; then
        log_action_end_msg 0
    else
        log_action_end_msg $?
    fi
}

set_console_font() {
    set +e
    local font=$1
    case $font in
            [0-9][0-9]x[0-9][0-9])  font=Uni2-Terminus$font            ;;
        [bB][0-9][0-9]x[0-9][0-9])  font=Uni2-TerminusBold${font#[bB]} ;;
    esac

    local file=/usr/share/consolefonts/$font
    [ -e $file -o -e $file.gz -o -e $file.psf.gz -o -e $file.psfu.gz \
        -o -e $file.cp.gz -o -e $file.cp ] || font=

    : ${font:=$DEFAULT_FONT}

	log_action_begin_msg "Setting console font to $font"

    local n ret=0
    for n in 1 2 3 4 5 6; do
        local tty=/dev/tty$n
        test -e $tty || continue
        setfont -C $tty $font || ret=$?
    done

    log_action_end_msg $ret
    return $ret
}


main "$@"

