#!/bin/bash
#
# This selects your default screen font from among the ones in
# /usr/share/kbd/consolefonts.
#

# Load defaults:
if [ -r /etc/default/rc.font ]; then
  . /etc/default/rc.font
fi

# IF FONT=none (or is unset), exit leaving the existing console font alone:
[ "$FONT" = "none" -o -z "$FONT" ] && exit 0

if [ "$FONT" = "auto" ]; then
  # Automatically find the best-sized Terminus font.
  font=ter-${F}14${W}
  prevfont=$font
  setfont $font
  prevcolumns=$(tput cols)
  # Leave if setfont can't load the first font.
  if [ ! $? = 0 -o "$prevcolumns" -lt "$MINCOLS" ]; then
    # Revert to system default:
    setfont
    exit 1
  fi
  for font in ter-${F}16${W} ter-${F}20${W} ter-${F}22${W} ter-${F}24${W} ter-${F}28${W} ter-${F}32${W} ; do
    setfont $font
    if [ "$(tput cols)" -lt "$MINCOLS" ]; then
      # Too big, the previous font is the closest one:
      break;
    fi
    prevfont=$font
    prevcolumns=$(tput cols)
    prevdouble=""
  done
  # If we made it all the way through that list, let's try another pass using
  # doubled fonts:
  if [ "$prevfont" = "ter-${F}32${W}" ]; then
    for font in ter-${F}20${W} ter-${F}22${W} ter-${F}24${W} ter-${F}28${W} ter-${F}32${W} ; do
      setfont -d $font
      if [ "$(tput cols)" -lt "$MINCOLS" ]; then
        # Too big, the previous font is the closest one:
        break;
      fi
      prevfont=$font
      prevcolumns=$(tput cols)
      prevdouble=" -d "
    done
  fi
  # Load the font:
  echo "Loading console font ($prevfont, $prevcolumns columns):"
  setfont -v $prevdouble $prevfont
else
  # Set the font to the requested font, $FONT:
  setfont $FONTDOUBLE $FONT
  echo "Loading custom console font ($FONT, $(tput cols) columns):"
  setfont $FONTDOUBLE -v $FONT
fi
