#!/bin/dash

# Configure console keyboard defaults from /etc/default/keyboard.
# Intended to run on the "kbd" node add event (see kbd-default.act).

set -u

. "$VDEV_HELPERS/subr.sh"

main() {
    local _setupcon _rc

    # Only relevant when the kernel "kbd" node is added.
    if [ "${VDEV_ACTION:-}" != "add" ]; then
        return 0
    fi
    if [ "${VDEV_PATH:-}" != "kbd" ]; then
        return 0
    fi

    if [ ! -f /etc/default/keyboard ]; then
        vdev_log "/etc/default/keyboard not found; skip keyboard defaults"
        return 0
    fi

    _setupcon=""
    if [ -x /bin/setupcon ]; then
        _setupcon=/bin/setupcon
    elif [ -x /usr/bin/setupcon ]; then
        _setupcon=/usr/bin/setupcon
    fi

    # setupcon is the canonical Debian path to apply /etc/default/keyboard.
    if [ -n "$_setupcon" ]; then
        "$_setupcon" --force >/dev/null 2>&1
        _rc=$?
        if [ $_rc -ne 0 ]; then
            vdev_warn "$_setupcon --force exited with $_rc"
        else
            vdev_log "applied keyboard defaults via $_setupcon --force"
        fi
        return 0
    fi

    vdev_warn "setupcon not found; cannot apply /etc/default/keyboard automatically"
    return 0
}

if [ "${VDEV_DAEMONLET:-0}" -eq 0 ]; then
    main
    exit $?
fi
