#!/bin/bash

ENABLED=yes
[ "$ENABLED" != "yes" ] && exit 0
DEBUGMODE=no

STEAMNODPMS=yes

. /usr/lib/ublinux/functions
. /usr/lib/ublinux/os-config
debug_mode "$0" "$@"

#. $HARDCONF
#echo "$XDRIVER" | grep -q "nvidia" || rmmod nvidia

[ -f ${SYSCONF}/config ] && . ${SYSCONF}/config
[ -f ${SYSCONF}/desktop ] && . ${SYSCONF}/desktop
[ -f ${SYSCONF}/keyboard ] && . ${SYSCONF}/keyboard

[[ ${DISPLAYMANAGER} == "none" ]] && exit


# Auto driver loader
if [[ ${AUTO_VGA_DRV} != "no" ]]; then
    for KERNEL_MODULE in $(lspci -k | egrep -i -A 3 'VGA|3D' | grep 'Kernel modules:' | cut -d: -f2 | tr -d ' ' | tr ',' '\n' | tac); do
	modprobe ${KERNEL_MODULE} 2>/dev/null && break
    done
fi

if lsmod | grep nvidia; then
    [[ -e /etc/X11/xorg.conf.d/20-nvidia.conf ]] || ln -sf /usr/lib/ublinux/xorg.conf.d/20-nvidia.conf /etc/X11/xorg.conf.d/
#    [[ -e /etc/udev/rules.d/70-nvidia.rules ]] || ln -sf /usr/lib/ublinux/udev/70-nvidia.rules /etc/udev/rules.d/
    /usr/bin/nvidia-modprobe -c0 -umsl
    modprobe nvidia_drm
    modprobe nvidia_uvm
    modprobe nvidia_modeset
#    modprobe drm_kms_helper
#    modprobe drm
fi


#[ ! -z "$VGAID" ] && grep -q $VGAID /usr/share/ublinux/hwdata/deleteconf && rm -f /etc/X11/xorg.conf
[ "$DELETE_XORG_CONF" = "yes" ] && rm -f /etc/X11/xorg.conf

grep -q xres= /proc/cmdline && XORG_RES=$(cat /proc/cmdline | awk -F xres= '{print $2}' | awk '{print $1}')
if [ "$SETXORGRES" != "no" ] ;then
  if ! [ -z "$XORG_RES" ] ;then 
     XCF=/etc/X11/xorg.conf
     grep -qi modes $XCF 2>/dev/null || XCF=/etc/X11/xorg.conf.d/00-modes.conf
     if grep -qi modes $XCF 2>/dev/null ;then
        sed -i 's|^[[:space:]]*Modes.*|        Modes "'$XORG_RES'"|' $XCF
     else
        cat >$XCF <<EOF
Section "Screen"
   Identifier "Screen"
   SubSection "Display"
        Modes "$XORG_RES"
   EndSubSection
EndSection
EOF
     fi
  fi
fi

echo $DPMS | egrep -qi 'no|off|false' && DPMS=no
[ "$STEAMNODPMS" = "yes" -a "$DESKTOP" = "Steam" ] && DPMS=no

if [ "$DPMS" = "no" ] ;then
     sed -i s/'.*Option .DPMS..*'/'    Option "DPMS" "false"'/ /etc/X11/xorg.conf
fi

if [ "$MKKBDFXORG" != "no" ] ;then
  if ! grep -sqi XkbOptions /etc/X11/xorg.conf ;then
     cat > /etc/X11/xorg.conf.d/00-keyboard.conf <<EOF
Section "InputClass"
        Identifier "system-keyboard"
        MatchIsKeyboard "on"
        Option "XkbLayout" "$XkbLayout"
        Option "XkbModel" "$XkbModel"
        Option "XkbVariant" "$KEYBOARD"
        Option "XkbOptions" "$XkbOptions"
EndSection
EOF
  fi
fi

# Блок простого MultiSeat
I=1
SIMPLEMULTISEAT="SIMPLEMULTISEAT${I}"
while [[ ${!SIMPLEMULTISEAT} ]]; do
    MULTISEATCOMMAND="$(echo ${!SIMPLEMULTISEAT} | cut -d " " -f1)"
    if [[ "${MULTISEATCOMMAND}" == "attach" ]]; then
#	SEATN="$(echo ${!SIMPLEMULTISEAT} | cut -d " " -f2)"
#        DEVICE="$(echo ${!SIMPLEMULTISEAT} | cut -d "" -f3)"
#	loginctl "${MULTISEATCOMMAND}" "${SEATN}" "${DEVICE}"
	loginctl "${!SIMPLEMULTISEAT}"
    fi
    SIMPLEMULTISEAT="SIMPLEMULTISEAT$((++I))"
done

