#!/bin/sh
# This script is called from the postinst of all xserver-xorg-video-nvidia* packages.
set -e

. /usr/share/debconf/confmodule

package="nvidia-support"
templates="$(dpkg-query --control-path "$package" templates)"
if [ -n "$templates" ]; then
	db_x_loadtemplatefile "$templates" "$package"
fi


# If we already created our config file, don't try again.
if [ -f "/etc/X11/nvidia.conf" ]
then
       exit 0
fi

# If nvidia is already configured, don't change this.
if grep -qi '^\s*driver\s*"nvidia"' /etc/X11/xorg.conf /etc/X11/xorg.conf.d/*.conf 2>/dev/null
then
	exit 0
fi

# If a different driver is already configured, print a warning, but don't change the current configuration.
if grep -qi '^\s*driver\s*"' /etc/X11/xorg.conf /etc/X11/xorg.conf.d/*.conf 2>/dev/null
then
	echo "WARNING: *** A different Xorg driver is already configured." >&2
	echo "         *** Configuration of the NVIDIA driver will be skipped." >&2
	grep -Hin '^\s*driver\s*"' /etc/X11/xorg.conf /etc/X11/xorg.conf.d/*.conf >&2 2>/dev/null
	exit 0
fi

# If something else is already configured in xorg.conf, don't change the current configuration.
if [ -f "/etc/X11/xorg.conf" ]
then
       exit 0
fi

db_input high nvidia-support/create-nvidia-conf || true
db_go
db_get nvidia-support/create-nvidia-conf
if [ "$RET" != "true" ]; then
	exit 0
fi

cat > /etc/X11/nvidia.conf << EOF
# This file (/etc/X11/nvidia.conf) was created by the nvidia-support package.
# At the location /etc/X11/nvidia.conf this config file is inactive.  It will
# be activated when the 'glx' alternative is set to 'nvidia' by creating a
# slave alternative link in /etc/X11/xorg.conf.d.  The alternative can be
# reconfigured with the command
#    update-alternatives --config glx

# The configuration created by nvidia-support is only the bare minimum needed
# to enable the nvidia driver.  It may be customized with additional
# settings, the nvidia-support package will not modify this file again as
# long as it exists.

# For information about the format of this file and general settings, see the
# xorg.conf(5) manual page.  For information about nvidia specific settings
# please read /usr/share/doc/xserver-xorg-video-nvidia*/README.txt.gz

# The nvidia-settings and nvidia-xconfig programs (which can be found in
# packages of the same names) are also capable of creating more complex
# Xorg configurations for the NVIDIA driver.

Section "Device"
	Identifier	"GPU"
	Driver		"nvidia"
EndSection

Section "Screen"
	Identifier	"Screens"
	Option		"TwinView" "1"
EndSection

# NVIDIA_SUPPORT_X11_NVIDIA_CONF_TEMPLATE_VERSION=1.0
EOF

echo "Created minimal Xorg configuration for NVIDIA in /etc/X11/nvidia.conf."

dpkg-trigger register-alternative-glx-nvidia


exit 0
