#!/bin/bash
# ssrconfig - Configures host to use server-side OpenGL rendering.
#
# Copyright (c) Open Text. All Rights Reserved. Trademarks owned by OpenText.
#

basename=$(basename $0)
basedir="$(dirname $(readlink -nf $0))"

setvgldir()
{
	vgldirs=( 
	 "$basedir/../3rdparty/virtualgl" #v10
	 "$basedir/3rdparty/virtualgl"    #v8
	 "$basedir/gl"                    #v7
	 )
	vgldir=UNKNOWN

	for dir in "${vgldirs[@]}"; do
		if [ -d "$dir" ]; then
			vgldir="$(readlink -nf $dir)"
			break
		fi
	done
}

# NVIDIA 4xx series drivers added a HardDPMS option that causes the GPU to render at 1fps
# after DPMS mode kicks in, killing server-side rendering.  We want to disable it.
handleDPMS()
{
	confdir=/etc/X11/xorg.conf.d
	if [ ! -d "$confdir" ]; then
		mkdir "$confdir"
	fi
	if [ ! -d "$confdir" ]; then
		echo "${basename}: WARNING: Could not find xorg.conf.d, to disable DPMS."
		return
	fi
	
	conf=$confdir/12-opentext-etx-ssr-disable-dpms.conf
	if [ "$1" = "config" ]; then
		echo "${basename}: Disabling DPMS."
		cat << 'EOF' > "$conf"
# NVIDIA HardDPMS option must be in a Device section which requires knowing
# the device Identifier, so disable the entire extension instead.
Section "Extensions"
        Option  "DPMS" "Disable"
EndSection
EOF
	else
		if [ -f "$conf" ]; then
			echo "${basename}: Enabling DPMS."
			rm -f "$conf"
		fi
	fi
}

setvgldir

if [ ! "${EUID}" -eq 0 ]; then
	echo "${basename}: ERROR: This script must be run as root."
	exit 1
fi

vglconfig="${vgldir}/bin/vglserver_config"
if [ "$1" != "config" -a "$1" != "unconfig" ]; then
	echo "Usage: ${basename} [config | unconfig]"
elif [ ! -e "${vglconfig}" ]; then
	echo "${basename} error: Invalid install directory."
else
	"${vglconfig}" +f +s -$1
	handleDPMS $1
	if [ "$1" = "config" -a -x "$basedir/copyssrtosyslib" ] ; then
		"$basedir/copyssrtosyslib"
	fi
fi
