#!/bin/bash

# Description:       The purpose of fll-locales is to calculate required
#                    strings to configure the locale settings of system
#                    according to given lang= string.

###
# F.U.L.L.S.T.O.R.Y
#
# Copyright: (C) 2007 - 2008 Kel Modderman <kel@otaku42.de>
#            (C) 2008 Michael Deelwater <michael.deelwater@googlemail.com>
#            (C) 2016 Niall Walsh <niallwalsh@celtux.org>
# License:   GPLv2
#
# F.U.L.L.S.T.O.R.Y Project Homepage:
# https://github.com/fullstory
###

PATH=/sbin:/usr/sbin:/bin:/usr/bin
NAME="fll-locales"

if [ "${1}" = "list" ]; then
	sed -n 's![ \t]\+\([a-z-]\+\)|\?\([a-z]\+\)\?).*### [A-Z][A-Z] \(.\+\) kb:\(.\+\) ###!\1, \3,\4!p' "${0}"
	exit 0
fi

###
# source distro-defaults, no-op unless in live mode
###
FLL_DISTRO_MODE="installed"
FLL_DISTRO_NAME="tebian"

if [ -r /etc/default/distro ]; then
	. /etc/default/distro
fi

if [ "${FLL_DISTRO_MODE}" != "live" ]; then
	[ -n "${FLL_LANG}" ] || exit 0
fi

###
# source fll functions
###
. /lib/init/fll

###
# source LANG functions
###
. /usr/share/fll-live-initscripts/locales

###
# some console-setup defaults
###
CHARMAP="UTF-8"
CODESET="Uni2"
# Debian agrees that Terminus doesn't look great enough to be default
# http://bugs.debian.org/497331
FONTFACE="VGA"
# Keep the default size of 16 here to avoid clearing VT 1/2 way through
# bootup sequence
FONTSIZE="16"

###
# some configuration defaults
###
XKBMODEL="linux"
XKBLAYOUT="de"
XKBVARIANT=""
XKBOPTIONS="lv3:ralt_switch"
LANGUAGE="de_de"
NOBLOB=""
###
# cheatcode handling
###
if [ -f /proc/cmdline ]; then
	for param in $(cat /proc/cmdline); do
		case "${param}" in
			lang=*)
				LANGUAGE=$(awk 'BEGIN{ print tolower("'"${param#lang=}"'") }')
				;;
			utc=yes)
				UTC="yes"
				;;
			utc|gmt)
				CUSTOM_TZ="Etc/UTC"
				;;
			tz=*)
				CUSTOM_TZ="${param#tz=}"
				;;
			noaptlang)
				NOAPTLANG="yes"
				;;
			xkboptions=*)
				KBOPTIONS="${param#xkboptions=}"
				;;
			keytable=*)
				KEYTABLE="${param#keytable=}"
				;;
			xkbmodel=*)
				KBMODEL="${param#xkbmodel=}"
				;;
			xkbvariant=*)
				KBVARIANT="${param#xkbvariant=}"
				;;
			noblob)
				NOBLOB="yes"
				;;
		esac
	done
fi

###
# allow FLL_LANG environment variable to trump
###
if [ -n "${FLL_LANG}" ]; then
	LANGUAGE="${FLL_LANG}"
fi

###
# lang cheatcode can optionally be made of two dash-separated parts ll-cc
# ll -> language code
# cc -> demographic code
###
LANG_CODE=${LANGUAGE%%[-_]*}
DEMO_CODE="$(echo ${LANGUAGE##*[-_]} | awk '{print toupper($1)}')"

LANGS=$(locale -a)
LANG=""

# First check if they entered a built in lang
for LOCALE in ${LANGS}; do
	[ "${LOCALE}" = "${LANG_CODE}_${DEMO_CODE}.utf8" ] && LANG="${LOCALE}" && break

	# match the language to find the default and possible locales
	case "${LOCALE}" in
		${LANG_CODE}_*)
			[ -z "${LANG_POSS}" ] && LANG_POSS="${LOCALE}"
			fll_locale_default ${LOCALE} && LANG_DEF="${LOCALE}"
			;;
	esac
done

# See if we have some knowledge on how to setup the requested locale
if [ -z "${LANG}" ]; then
	for LOCALE in fll_locale_cheats; do
		[ "${LOCALE}" = "${LANG_CODE}_${DEMO_CODE}.utf8" ] && \
			fll_locale_lang ${LOCALE} && break
	done
fi

# Ok just fallback to the default language, or whatever we know about or en_US
if [ -z "$LANG" ]; then
	if [ -n "${LANG_DEF}" ]; then
		LANG="${LANG_DEF}"
	else
		if [ -n "${LANG_POSS}" ]; then
			LANG="${LANG_POSS}"
		else
			LANG="de_DE.utf8"
		fi
	fi
fi
export LANG

###
# if demographic code was ommitted, extract default demo_code from LANG
###
if [ -z "${DEMO_CODE}" ]; then
	LANG_CHECK="${LANG%%.*}"
	DEMO_CODE="${LANG_CHECK##*_}"
fi

#set tz, mirror, xkb via fll_locale_demo
if [ "${LANG}" = "${LANG_CODE}_${DEMO_CODE}.utf8" ]; then
	fll_locale_demo ${LANG}
else
	# We altered their LANG
	fll_locale_cheats
	for LOCALE in ${FLL_LOCALE_CHEATS}; do
		# if we have their locale
		if [ "${LOCALE}" = "${LANG_CODE}_${DEMO_CODE}.utf8" ]; then
			DEMO="${LOCALE}"
			break
		fi

		# if we have a locale in their country
		if [ "${LOCALE#*_}" = "${DEMO_CODE}.utf8" ]; then
			[ -z "${DEMO_POSS}" ] && DEMO_POSS="${LOCALE}"
		fi
	done

	# if it's not a country we know about fallback to default 00_00
	if [ -z "${DEMO}" ]; then
		if [ -n "${DEMO_POSS}" ]; then
			DEMO="${DEMO_POSS}"
		else
			DEMO="00_00.utf8"
		fi
	fi

	fll_locale_demo ${DEMO}
fi

###
# allow CUSTOM_TZ to override above TZ definitions
###
if [ -n "${CUSTOM_TZ}" ]; then
	case "${CUSTOM_TZ}" in
		utc|UTC)
			CUSTOM_TZ="Etc/UTC"
			;;
	esac
	[ -f "/usr/share/zoneinfo/${CUSTOM_TZ}" ] && TZ="${CUSTOM_TZ}"
fi

###
# allow KEYTABLE to update above XKBLAYOUT settings
###
if [ -n "${KEYTABLE}" ]; then
	XKBLAYOUT="${KEYTABLE}"
fi

###
# allow KBOPTIONS to update above XKBOPTIONS settings
###
if [ -n "${KBOPTIONS}" ]; then
	XKBOPTIONS="${KBOPTIONS}"
fi

###
# allow KBMODEL to update above XKBMODEL settings
###
if [ -n "${KBMODEL}" ]; then
	XKBMODEL="${KBMODEL}"
fi

###
# allow KBVARIANT to update above XKBVARIANT settings
###
if [ -n "${KBVARIANT}" ]; then
	XKBVARIANT="${KBVARIANT}"
fi

set_timezone()
{
	###
	# configure timezone, fallback to UTC
	###
	[ -f "/usr/share/zoneinfo/${TZ}" ] || TZ="Etc/UTC"
	echo "configuring timezone data for '${TZ}'"
	echo "${TZ}" > /etc/timezone
	rm -f /etc/localtime && ln -s "/usr/share/zoneinfo/${TZ}" /etc/localtime

	###
	# hack rcS, make localtime default, unless tz=Etc/UTC or utc=yes
	###
	if [ "${TZ}" = "Etc/UTC" ] || [ "${UTC}" = "yes" ]; then
		printf "0.000000 0 0.000000\n0\nUTC\n" > /etc/adjtime
	else
		# debian defaults to UTC=yes, which is rumored to be dual-boot unfriendly
		printf "0.000000 0 0.000000\n0\nUTC\n" > /etc/adjtime

		# update the system clock a'la /lib/udev/rules.d/85-hwclock.rules
		/sbin/hwclock --rtc=/dev/rtc0 --systz
		/sbin/hwclock --rtc=/dev/rtc0 --hctosys
	fi
}

set_locale()
{
	###
	# select default locale and configure console-data via debconf
	###
	echo "configuring locales for '${LANG}'"

	echo "locales locales/default_environment_locale select ${LANG}" | \
		debconf-set-selections
	update-locale "LANG=${LANG}"
}

hack_kde()
{
	if [ $LANG = "de_DE.UTF-8" ]; then
	    cat > /home/tux/.config/plasma-localerc <<EOF
[Formats]
LANG=de_DE.UTF-8

[Translations]
LANGUAGE=de:en_US
EOF
	fi
}
set_console()
{
	# write configuration: console-setup
	cat > /etc/default/console-setup <<EOF
ACTIVE_CONSOLES="/dev/tty[1-6]"
CHARMAP="${CHARMAP}"
CODESET="${CODESET}"
FONTFACE="${FONTFACE}"
FONTSIZE="${FONTSIZE}"
EOF

	# write configuration: keyboard-configuration
	# only set one layout
	# FIXME: investigate debconfsettings!
	sed -i	-e "s/^\(XKBMODEL\=\).*/\1\"${XKBMODEL}\"/" \
		-e "s/^\(XKBLAYOUT\=\).*/\1\"${XKBLAYOUT%%,*}\"/" \
		-e "s/^\(XKBVARIANT\=\).*/\1\"${XKBVARIANT}\"/" \
		-e "s/^\(XKBOPTIONS\=\).*/\1\"${XKBOPTIONS}\"/" \
			/etc/default/keyboard

#	setupcon --save-only
	setupcon --save

	udevadm trigger --property-match=ID_INPUT_KEYBOARD=1
}

apt_purge_blob() {
	#echo linux-tuxedo-22.04 1 yes yes yes 1 >> /etc/tomte/tomte.cfg
	i=$(lspci | egrep -i "vga|display|3d" | grep -i nvidia)
	if [ "x$i" = "x" ]; then
	    apt-get purge $(dpkg -l | grep -i nvidia | awk '{ print $2 }') glx-diversions --assume-yes || true
	    rm -f /etc/prime-discrete
	    rm -f /lib/modprobe.d/nvidia-graphics-drivers.conf
	    rm -f /lib/modprobe.d/nvidia-kms.conf
	else
	    if [ "$NOBLOB" = "yes" ]; then
		apt-get purge $(dpkg -l | grep -i nvidia | grep -v firmware-nvidia-graphics | awk '{ print $2 }') glx-diversions --assume-yes || true
		rm -f /etc/prime-discrete
		rm -f /lib/modprobe.d/nvidia-graphics-drivers.conf
		rm -f /lib/modprobe.d/nvidia-kms.conf
	    fi
	    #tomte block nvidia-driver
	    echo on-demand > /etc/prime-discrete
	fi
}

nvidia_switch() {
    REPO_PATH="/usr/share/tuxedo/nvidia"  # Lokaler Pfad auf dem ISO, anpassen falls anders
    PKG_CLOSED="nvidia-kernel-dkms"
    PKG_OPEN="nvidia-open-kernel-dkms"

    log() { echo "[nvidia-autoselect] $*" >&2; }

    # Prüfen, ob NVIDIA GPU erkannt wird
    if ! lspci | grep -qi "NVIDIA" || [ "$NOBLOB" = "yes" ]; then
        log "No NVIDIA GPU found or blob not whished  – cancel installation"
    else
        log "NVIDIA GPU found, check supported variant..."

        # Herausfinden, ob Open Kernel unterstützt wird (heuristisch)
        GPU_ID=$(lspci -n | grep -i "10de:" | head -n1 | awk '{print $3}' | cut -d: -f2)
        GPU_HEX="0x${GPU_ID}"

        USE_OPEN=0
        rm -f /usr/share/tuxedo/nv-open
        if [[ "$GPU_HEX" -ge 0x1E00 ]]; then
            USE_OPEN=1
            echo 1 > /usr/share/tuxedo/nv-open
        fi

        echo "blacklist nouveau" > /etc/modprobe.d/tuxedo-nv-blacklist.conf

        PKG_TO_INSTALL=$PKG_CLOSED
        if [[ "$USE_OPEN" -eq 1 ]]; then
            PKG_TO_INSTALL=$PKG_OPEN
            SRC_TO_INSTALL=$SRC_OPEN
            log "use package: $PKG_TO_INSTALL"
            # DEBIAN_FRONTEND=noninteractive apt-get --assume-yes install $(ls "$REPO_PATH"/*nvidia*open*.deb) || true
            cp -av /usr/share/tuxedo/nvidia-modules-open/*nvidia* /lib/modules/*/updates/dkms/
	    apt-get --assume-yes install /usr/share/tuxedo/nvidia-debs-open/nvidia-open-kernel-support*.deb
        else
            log "use package: $PKG_TO_INSTALL"
            # DEBIAN_FRONTEND=noninteractive apt-get --assume-yes install $(ls "$REPO_PATH"/*nvidia*.deb | grep -v open) || true
            cp -av /usr/share/tuxedo/nvidia-modules/*nvidia* /lib/modules/*/updates/dkms/
	    apt-get --assume-yes install /usr/share/tuxedo/nvidia-debs/nvidia-kernel-support*.deb
        fi

        log "Installation done. $PKG_TO_INSTALL is now active."
	log "write nvidia options"
	echo "options nvidia-drm modeset=1 fbdev=1" > /etc/modprobe.d/tuxedo-nvidia-kms.conf
	log "running depmod -a"
        depmod -a || true
	log "modprobing nvidia"
        modprobe nvidia-drm modeset=1 fbdev=1 || true
    fi
}

sources_list() {
# deploy tuxedo own mirrors

	rm -f /etc/apt/sources.list.d/*.list
	rm -r /etc/apt/keyrings
	rm -f /etc/apt/trusted.gpg.d/54840598*
	rm -f /etc/apt/trusted.gpg.d/8AA91DA6385AA480.asc
	rm -f /etc/apt/trusted.gpg.d/2836cb0a8ac93f7a.asc
	rm -f /etc/apt/preferences.d/10-tuxedo-pinning

	cp -af /usr/share/tuxedo/conf/apt/*.sources /etc/apt/sources.list.d/
}

save_locale_variables() {
	for var in FLL_MIRROR CHARMAP CODESET FONTFACE FONTSIZE \
		   XKBMODEL XKBLAYOUT XKBVARIANT XKBOPTIONS; do
		val=$(eval echo \$${var})
		echo "${var}=\"${val}\""
	done > "/etc/default/${NAME}"
}

case "${1}" in
	start)
		#nvidia_switch
		set_timezone
		set_locale
		set_console
		apt_purge_blob
		sources_list
		save_locale_variables
		hack_kde
		;;
	localize)
		# localize
		#nvidia_switch
		set_locale
		set_console
		apt_purge_blob
		sources_list
		save_locale_variables
		hack_kde
		;;
	*)
		echo "Usage: ${NAME} {start|localize}" >&2
		exit 3
		;;
esac

:
