#!/bin/bash

# Codesets on Debian
#
#  CyrAsia    Greek    Lat7
#  CyrKoi     Lat15    Uni2
#  CyrSlav    Lat2     Uni3

export TEXTDOMAIN="console-font-select"

lib_dir=/usr/lib/shell
loc_lib=./lib
test -e $loc_lib/lib-screen.sh && lib_dir=$loc_lib
. $lib_dir/lib-screen.sh
. $lib_dir/lib-grid.sh

main() {

    [ ${#CODESET} -eq 0 ] && CODESET=$(lang_to_codeset $LANG)
    FONT_MENU="$(read_console_fonts | sort -n | cut -d: -f2)"
    [ ${#FONT_MENU} -eq 0 ] && fatal "No fonts found"

    set_color_scheme light

    local cur_width=$(get_current_width)

    screen_set title1=$"Select a Console Font"
    screen_set title2=$"Press: <Enter> to select a font <q> to quit, <h> for help"
    screen_set title3="$(printf $"Current width is %s characters" "$cur_width")"
    screen_set border=0

    init

    grid_fill_labels

    hide_tty
    clear
    redraw
    main_loop
}

init() {
    screen_init
    grid_read_new console_font "$FONT_MENU"
    grid_large y=3 title="$(printf "%s Console Fonts" "$CODESET")"
    grid_fill_y 50
    grid_finalize
}

redraw() {
    screen_draw
    grid_activate
}

restart() {
    local save_sel=$GRID_SEL
    local save_def=$GRID_DEFAULT_SEL
    init
    GRID_SEL=$save_sel
    GRID_DEFAULT_SEL=$save_def
    clear
    redraw
}

key_callback() {
    local key=$1
    [ "$key" = "t" ] || return 1
    clear

    echo -n $cyan
    showconsolefont -i
    echo -n $nc
    showconsolefont
    echo

    echo "$cyan Press any key to continue$nc"

    read -s -n1 xxx
    clear
    redraw
    return 0
}

#------------------------------------------------------------------------------
# Set the selected font on the current display then restart so we rebuild the
# menu based on the new screen size.
#------------------------------------------------------------------------------
console_font_on_enter() {
    local font=$1  sel=$3
    local full=$(expand_font "$font")

    GRID_DEFAULT_SEL=$sel
    if [ -z "$SCREEN_IN_VT" ]; then
        grid_activate
        db_msg "Would set font to %s" "$white$full"
        return
    fi

    local term=$(fgconsole)

    setfont $full
    local ret=$?

    log "term=$term  font=$full"
    clear

    if [ $ret -eq 0 ]; then
        local cur_width=$(get_current_width)
        screen_set title3="$(printf $"Screen is %s chars wide, font is %s" "$yellow$cur_width$magenta" "$yellow$font")"
    fi

    restart

    if [ $ret -eq 0 ]; then
        db_msg "${green}set font to %s" "$yellow$full"
    else
        db_msg "${red}Failed to set font %s" "$yellow$full"
    fi
}


#------------------------------------------------------------------------------
# Gather names of actual font files that we recognize.  Then make short names
# out of them to be displayed.
#------------------------------------------------------------------------------
read_console_fonts() {
    local dir=/usr/share/consolefonts

    local file font size name
    for file in $(ls $dir | sort); do
        font=${file%%.*}
        case $file in
            $CODESET-TerminusBold[0-9]*) size=${font#$CODESET-TerminusBold}    ; name="-Bold"     ;;
                $CODESET-Terminus[0-9]*) size=${font#$CODESET-Terminus}        ; name=""          ;;
         $CODESET-TerminusBoldVGA[0-9]*) size=${font#$CODESET-TerminusBoldVGA} ; name="-VGA-Bold" ;;
                     $CODESET-VGA[0-9]*) size=${font#$CODESET-VGA}             ; name="-VGA"      ;;
                   $CODESET-Fixed[0-9]*) continue                                                 ;;
                                      *) continue                                                 ;;
        esac

        # Sizes without the "x" are all 8 wide (AFAIK)
        case $size in
            8|14|16) size=${size}x8
        esac

        # Sort by width first then height then name
        local width=${size##*[x-]}
        local height=${size%%[x-]*}
        local index=$(printf "%04d%04d" "$width" "$height")
        echo $index:$size$name
        continue

    done
}

#------------------------------------------------------------------------------
# Undo what was done in read_console_fonts() to get back to the actual font
# name that can be used by setfont.
#------------------------------------------------------------------------------
expand_font() {
    local font=$1
    local name=Terminus  size=${font%%-*}
    case $font in
           *-VGA-Bold) name=${name}BoldVGA ;;
               *-Bold) name=${name}Bold    ;;
              *-Fixed) name=Fixed          ;;
                *-VGA) name=VGA            ;;
                   *)                      ;;
    esac

    case $size in
         8x8) size=8  ;;
        14x8) size=14 ;;
        16x8) size=16 ;;
    esac

    echo "$CODESET-$name$size"
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
fatal() {
    local fmt=$1 ; shift
    printf "Error: $fmt\n" "$@"
    exit 7
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
lang_to_codeset() {
    local lang=$1
    case ${lang%%_*} in
                     kk|ky|tj) echo CyrAsia  ;;
                        ru|uk) echo CyrKoi   ;;
                  bg|mk|ru|sr) echo CyrSlav  ;;
      bs|hr|cs|hu|pl|ro|sk|sl) echo Lat2     ;;
        af|sq|ast|da|nl|et|fr) echo Lat15    ;;
    "fi"|de|is|id|pt|es|sv|tr) echo Lat15    ;;
                        lt|lv) echo Lat7     ;;
                           el) echo Greek    ;;
                            *) echo Uni2     ;;
    esac
}

#------------------------------------------------------------------------------
# Convenience routine to give the width of the screen in CHARACTERS
#------------------------------------------------------------------------------
get_current_width() { stty size | cut -d" " -f2; }

my_dir=$(readlink -f "$(dirname "$0")")

HELP_PAGE=console-font-select

[ "$DEBUG" ] || log_file=/dev/null

main "$@" 2>> $log_file
