#!/bin/bash

usage() {
    cat <<EOF
Usage: $PROG --mode|--reset|--help
  --mode powersaving|performance
    powersaving: shutdown dGPU, only use iGPU
    performance: use dGPU for rendering, iGPU and dGPU for display
  --reset
    reset the script changes
  --ispx
    echo "true" if the platform can enable PX, otherwise echo "false"
EOF
}

powersaving_conf() {
    cat <<EOF
Section "ServerFlags"
        Option  "AutoAddGPU" "off"
EndSection

Section "Device"
        Identifier "Intel"
        Driver "intel"
EndSection

Section "Files"
    ModulePath "/usr/lib/xorg/modules"
EndSection
EOF
}

performance_conf() {
    cat <<EOF
Section "Device"
        Identifier "Intel"
        Driver "modesetting"
        Option "AllInOne" "true"
        Option "RenderName" "amdgpu"
EndSection

Section "Device"
        Identifier "Amd"
        Driver "modesetting"
        Option "AllInOne" "true"
        Option "RenderName" "amdgpu"
EndSection

Section "Screen"
        Identifier "Screen0"
        Device "Intel"
        GPUDevice "Amd"
EndSection
EOF
}

ld_so_conf() {
    cat <<EOF
/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/mesa
/usr/lib/x86_64-linux-gnu/mesa-egl

/lib/i386-linux-gnu
/usr/lib/i386-linux-gnu
/usr/lib/i386-linux-gnu/mesa
/usr/lib/i386-linux-gnu/mesa-egl
EOF
}

set_mode() {
    if [ x$1 = xpowersaving ]; then
	mkdir -p $X11_CONFDIR
	powersaving_conf > $X11_CONFDIR/$X11_CONFFILE
	ld_so_conf > $LD_SO_CONFDIR/$LD_SO_CONFFILE
    elif [ x$1 = xperformance ]; then
	mkdir -p $X11_CONFDIR
	performance_conf > $X11_CONFDIR/$X11_CONFFILE
	rm -f $LD_SO_CONFDIR/$LD_SO_CONFFILE
    else
	usage
	exit
    fi

    ldconfig

    echo "Switch to $1 mode success, please re-login to make settings take effect"
}

reset() {
    rm -f $LD_SO_CONFDIR/$LD_SO_CONFFILE $X11_CONFDIR/$X11_CONFFILE
    ldconfig

    echo "Reset success, please re-login to make settings take effect"
}

ispx() {
    local vga=0300
    local display=0380
    local amd=1002
    local intel=8086

    if ([[ -n "$(lspci -d $amd::$vga)" ]] || [[ -n "$(lspci -d $amd::$display)" ]]) && \
       [[ -n "$(lspci -d $intel::$vga)" ]]; then
	echo true
    else
	echo false
    fi
}

need_root() {
    if [ "$EUID" -ne 0 ]; then
	echo "Please run as root"
	exit 1
    fi
}

X11_CONFDIR="/etc/X11/xorg.conf.d"
X11_CONFFILE="01-amdgpu-pro-px.conf"
LD_SO_CONFDIR="/etc/ld.so.conf.d"
LD_SO_CONFFILE="10-amdgpu-pro-px.conf"

PROG=${0##*/}
case "$1" in
    --help)
	usage; exit 0;;
    --mode)
	need_root
	set_mode $2
	exit $?
	;;
    --reset)
	need_root
	reset
	exit $?
	;;
    --ispx)
	ispx
	exit $?
	;;
    *)    usage >&2; exit 1;;
esac

