#!/bin/bash -e

# usage message
usage() {
	echo "
Change the 3D graphics acceleration mode
on the system with the Baikal-M processor.

Usage:
$(basename ${0}) --on
 Use panfrost driver to accelerate 3D graphics.
$(basename ${0}) --off
 Don't use panfrost driver to accelerate 3D graphics.
$(basename ${0}) --help
 Print this message.
"
}

# reboot after config change
needreboot() {
	echo "
After changing the configuration,
you must reboot the system
for the changes to take effect.
"
}

if [ "$1" == "--help" ]
then
	usage
	exit 0
fi

dtcompat="/sys/firmware/devicetree/base/compatible"
modcnf="/etc/modprobe.d/panfrost_enable.conf"
xorgcnf="/etc/X11/xorg.conf.d/50-baikal-vdu.conf"

# ensure sudo user
if [ "$(whoami)" != "root" ]
then
	echo "Error: This script requires 'sudo' privileges."
	exit 1
fi

if [ "$(cat $dtcompat 2> /dev/null | tr -d '\0')" != "baikal,baikal-m" ]
then
	echo "Error: This script is only for Baikal-M."
	exit 1
fi

if [ "$1" == "--on" ]
then
# panfrost on
	cat > $modcnf <<EOF
options panfrost enable_broken_machines=y
EOF

	cat > $xorgcnf <<EOF
Section "ServerFlags"
	Option	"AutoAddGPU" "off"
EndSection

Section "OutputClass"
	Identifier "BaikalM"
	MatchDriver "baikal_vdu_drm"
	Driver "modesetting"
	Option "PrimaryGPU" "true"
EndSection
EOF
	needreboot
	exit 0
fi

if [ "$1" == "--off" ]
then
# panfrost off
	rm -f $modcnf $xorgcnf
	needreboot
	exit 0
fi

echo "Error: Unknown option."
usage
exit 1
