#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL
# This program is used to replace the command "dpkg-reconfigure console-data" because console-data is in the process of being obsoleted by console-setup. For more info, check:
# http://bugs.debian.org/570223

#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
[ -e /etc/drbl/drbl-ocs.conf ] && . /etc/drbl/drbl-ocs.conf
[ -e $DRBL_SCRIPT_PATH/sbin/ocs-functions ] && . $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Loading settings 
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf

# Settings:
# Before we used "console_data", however, there are some issues sometimes:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=570223
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=893612
# 2018/03/21 we switch to "keyboard_configuration" which is actively developed.
preferred_configure="keyboard_configuration"

#
run_config_from_keyboard_configuration() {
  ask_and_load_lang_set
  TMP="$(mktemp /tmp/keymap_mode.XXXXXX)"
  ASK_KEYMAP=1
  while [ "$ASK_KEYMAP" -ne 0 ]; do
    $DIA --nocancel --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_keyboard_configuration" --menu "$msg_change_keyboard_layout?" \
    0 0 0 \
    Keep "$msg_keep_the_default_US_keymap" \
    Change "$msg_change_keyboard_layout" \
    2> $TMP
    keymap_mode="$(cat $TMP)"
    if [ -z "$keymap_mode" ]; then
      ASK_KEYMAP=1
    else
      ASK_KEYMAP=0
    fi
  done
  [ -f "$TMP" ] && rm -f $TMP
  
  #
  if [ "$keymap_mode" = "Change" ]; then
    dpkg-reconfigure keyboard-configuration
    rc=$?
    if [ "$rc" -eq 0 ]; then
      service keyboard-setup restart
      setupcon -k
      # Read the settings. Its ccontents are like:
      # XKBMODEL="pc105"
      # XKBLAYOUT="us"
      # XKBVARIANT=""
      # XKBOPTIONS="ctrl:nocaps"
      # BACKSPACE="bs"
      . /etc/default/keyboard
      # Put the keyboard layout setting so that later program can reuse
      if [ -z "$(grep -E "^[[:space:]]*live_keyboard_layouts=" /etc/ocs/ocs-live.conf 2>/dev/null)" ]; then
        # Append it
        echo "live_keyboard_layouts=$XKBLAYOUT" >> /etc/ocs/ocs-live.conf
      else
        # Modify it
        perl -pi -e "s|^[[:space:]]*live_keyboard_layouts=.*|live_keyboard_layouts=\"$XKBLAYOUT\"|g" /etc/ocs/ocs-live.conf
      fi
    fi
  fi
} # end of run_config_from_keyboard_configuration

#
run_config_from_console_data() {
  dpkg-reconfigure console-data
} # end of run_config_from_console_data

#
case $preferred_configure in
  "console_data") run_config_from_console_data ;;
  "keyboard_configuration") run_config_from_keyboard_configuration ;;
esac
