#!/bin/bash
# License: GPL 
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to set the font size in the console automatically.
# This file contains code generated by Grok, created by xAI.

#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Load the config in ocs-live.conf. This is specially for Clonezilla live. It will overwrite some settings of /etc/drbl/drbl-ocs.conf, such as $DIA...
[ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf

# Settings
console_setup_cfg="/etc/default/console-setup"

#
USAGE() {
   echo "Usage: $0 [Font size] "
   echo "Available font size: 6x12, 8x14, 8x16, 10x20, 12x24, 14x28 and 16x32." 
   echo "If font size is not assigned, it will be detected based on the screen resolution."
   echo "Ex:"
   echo "To set the font size as 14x28, run"
   echo "   $ocs 14x28"
   echo
}
# Function to get screen resolution
get_resolution() {
  if [ -f /sys/class/graphics/fb0/modes ]; then
      resolution=$(cat /sys/class/graphics/fb0/modes | head -n1 | cut -d: -f2 | cut -d'p' -f1)
      echo "$resolution"
  elif command -v fbset >/dev/null 2>&1; then
      resolution=$(fbset -s | grep 'mode "' | cut -d'"' -f2)
      echo "$resolution"
  else
      echo "Unable to detect resolution" >&2
      exit 1
  fi
}

# Function to get console dimensions
get_console_dims() {
  dims=$(stty size 2>/dev/null)
  if [ $? -eq 0 ]; then
      echo "$dims"
  else
      echo "Unable to detect console dimensions" >&2
      exit 1
  fi
}

# Function to select font based on resolution and console dimensions
select_font() {
  local width=$1
  local height=$2
  local rows=$3
  local cols=$4
  local fontsize_

  # Calculate pixel density (simplified: pixels per character)
  pixel_per_char="$(( (width * height) / (rows * cols) ))"

  # Font selection logic using non-bold Terminus fonts
  if [ "$width" -ge 2560 ] && [ "$pixel_per_char" -gt 360 ]; then
      font="Lat2-Terminus32x16"
      fontsize_="16x32"
  elif [ "$width" -ge 1366 ] && [ "$pixel_per_char" -gt 120 ]; then
      font="Lat2-Terminus28x14"
      fontsize_="14x28"
  else
      font="Lat2-Terminus16"
      fontsize_="8x16"
  fi

  # Check if the font exists, fallback to Uni2-Terminus16 if not
  if [ -f "/usr/share/consolefonts/$font.psf.gz" ]; then
      echo "$font $fontsize_"
  else
      echo "Uni2-Terminus16 8x16"  # Fallback to a known non-bold font
  fi
} # end of select_font

# Function to update $console_setup_cfg
update_and_set_console_setup() {
  local font=$1
  local fontsize_=$2

  # Backup the original file
  cp $console_setup_cfg ${console_setup_cfg}.ocs-saved

  # Update FONT and FONTSIZE in $console_setup_cfg
  sed -i "s|^FONTFACE=.*|FONTFACE=\"$font\"|" $console_setup_cfg
  sed -i "s|^FONTSIZE=.*|FONTSIZE=\"$fontsize_\"|" $console_setup_cfg

  if [ $? -eq 0 ]; then
      echo "Updated $console_setup_cfg with FONTFACE=$font and FONTSIZE=$fontsize_"
  else
      echo "Failed to update $console_setup_cfg" >&2
      exit 1
  fi
  # Verify setupcon can apply the settings
  setupcon --force
  if [ $? -eq 0 ]; then
      echo "Successfully applied font settings with setupcon"
  else
      echo "Failed to apply font settings with setupcon" >&2
      exit 1
  fi
} # end of update_and_set_console_setup

####################
### Main program ###
####################

ocs_file="$0"
ocs=`basename $ocs_file`
#
while [ $# -gt 0 ]; do
 case "$1" in
   -*)     echo "${0}: ${1}: invalid option" >&2
           USAGE >& 2
           exit 2 ;;
   *)      break ;;
 esac
done
#
font_size="$1"

#
check_if_root
ask_and_load_lang_set $specified_lang

if [ ! -e "$console_setup_cfg" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "Config file $console_setup_cfg not found."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "$msg_program_stop!"
  my_ocs_exit 1
fi

if [ -z "$font_size" ]; then
  # Will decide the font and size later
  font_size="auto_size"
else
  font="Fixed"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Using font and its size for the console: $font, $font_size"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

if [ "$font_size" = "auto_size" ]; then
  # From screen resolution we can decide the font and size later
  # Get resolution
  res="$(get_resolution)"
  if [ -z "$res" ]; then
      echo "Failed to get resolution" >&2
      exit 1
  fi
  width="$(echo "$res" | cut -d'x' -f1)"
  height="$(echo "$res" | cut -d'x' -f2)"
  
  # Get console dimensions
  dims="$(get_console_dims)"
  if [ -z "$dims" ]; then
      echo "Failed to get console dimensions" >&2
      exit 1
  fi
  rows="$(echo "$dims" | cut -d' ' -f1)"
  cols="$(echo "$dims" | cut -d' ' -f2)"
  
  # Select font and font_size
  font_info="$(select_font "$width" "$height" "$rows" "$cols")"
  font="$(echo "$font_info" | cut -d' ' -f1)"
  font_size="$(echo "$font_info" | cut -d' ' -f2)"
  
  echo "Using font and its size for the console: $font, $font_size"
  # Apply font immediately
  if [ -f "/usr/share/consolefonts/$font.psf.gz" ]; then
    echo "Set console font to $font ($font_size) for resolution ${width}x${height} and console ${rows}x${cols}"
    set_font_cmd="setfont /usr/share/consolefonts/$font.psf.gz"
    echo "Running: $set_font_cmd"
    # Later we still write font and its size to $console_setup_cfg.
  else
    echo "Font $font not found in /usr/share/consolefonts/" >&2
    exit 1
  fi
fi

# Update and set $console_setup_cfg for persistence
update_and_set_console_setup "$font" "$font_size"

exit 0
