#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-2.0-only

build() {
    # prevent conflicting variables from affecting vconsole.conf values
    # shellcheck disable=SC2034
    local KEYMAP KEYMAP_TOGGLE FONT FONT_MAP FONT_UNIMAP XKBLAYOUT XKBMODEL XKBVARIANT XKBOPTIONS

    add_binary setfont

    # subshell to avoid namespace pollution
    (
        # shellcheck disable=SC1091
        [[ -s /etc/vconsole.conf ]] && . /etc/vconsole.conf

        if [[ -n "$FONT" ]]; then
            for file in "/usr/share/kbd/consolefonts/$FONT".@(fnt|psf?(u))?(.gz|.zst); do
                if [[ -e "$file" ]]; then
                    [[ "$file" =~ (\.(fnt|psfu?))(\.gz|\.zst)?$ ]] && ext="${BASH_REMATCH[2]}"
                    if [[ "$file" == *'.gz' ]]; then
                        gzip -cd "$file" | add_file - "/consolefont.$ext" 644
                    elif [[ "$file" == *'.zst' ]]; then
                        zstd -qd "$file" | add_file - "/consolefont.$ext" 644
                    else
                        add_file "$file" "/consolefont.$ext"
                    fi
                    exit 0
                fi
            done
            error "consolefont: requested font not found: '%s'" "$FONT"
            exit 1
        else
            warning 'consolefont: no font found in configuration'
            exit 1
        fi
    ) && add_runscript
}

help() {
    cat <<HELPEOF
This hook loads consolefont specified in vconsole.conf during early userspace.
HELPEOF
}

# vim: set ft=sh ts=4 sw=4 et:
