#!/bin/bash
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

is_innogpu_gpu() {
	local VID="1EC8"
	local ID0="1EA8"
	local ID1="9800"
	local ID2="8800"
	local ID3="1EB8"

	if is_pci_exists $VID:$ID0; then
		return 0
	elif is_pci_exists $VID:$ID1; then
		return 0
	elif is_pci_exists $VID:$ID2; then
		return 0
	elif is_pci_exists $VID:$ID3; then
		return 0
	fi

	return 1
}

fix_innogpu_gpudrv() {
	local rc0
	local rc1
	local rc2

	is_arch_x86_64
	rc0=$?
	is_arch_aarch64
	rc1=$?
	is_arch_loongarch
	rc2=$?

	if [[ $rc0 == 0 || $rc1 == 0 || $rc2 == 0 ]]; then
		is_innogpu_gpu
		rc=$?
		if [ $rc != 0 ]; then
			return
		fi

		msg "setup innogpu driver"

		local PACKAGE_NAME="innogpu-kernel"
		is_installed $PACKAGE_NAME
		rc=$?
		if [ $rc == 0 ]; then
			msg "$PACKAGE_NAME has been installed"
		fi

		safe_install $PACKAGE_NAME
	fi
}

fix_nvidia_gpudrv() {
	local step=${1}
	if lspci -n | grep -i 10de | egrep -i '.*03(80|0[0-2])' ;then
		msg "setup nvidia driver"
		if [ ${step} == "--first-boot" ]; then
			deepin-nvidia-installer autoinstall
		else
			deepin-nvidia-installer ${step} autoinstall
		fi
	fi
}

fix_zhaoxin_6000() {
	local rc

	is_arch_x86_64
	rc=$?
	if [ $rc != 0 ]; then
		msg "$FUNCNAME : unsupported arch"
		return
	fi

	if lspci -n | grep -i "1D17" | egrep -i '3A03|3A04'; then
		msg "setup zhaoxin 6000 driver"
		local PACKAGE_NAME="zhaoxin-linux-graphics-driver-dri"
		is_installed $PACKAGE_NAME
		rc=$?
		if [ $rc == 0 ]; then
			msg "$PACKAGE_NAME has been installed"
		fi
		safe_install $PACKAGE_NAME
	fi
}

fix_zhaoxin_6000G() {
	local rc

	is_arch_x86_64
	rc=$?
	if [ $rc != 0 ]; then
		msg "$FUNCNAME : unsupported arch"
		return
	fi

	if lspci -n | grep -i "1D17" | egrep -i '3D01'; then
		msg "setup zhaoxin 6000G driver"
		local PACKAGE_NAME="cx4-linux-graphics-driver-dri"
		is_installed $PACKAGE_NAME
		rc=$?
		if [ $rc == 0 ]; then
			msg "$PACKAGE_NAME has been installed"
		fi
		safe_install $PACKAGE_NAME
	fi
}

head "-- gpu device detect and driver adaptation"
#fix_innogpu_gpudrv  || true
fix_nvidia_gpudrv  $1 || true
#fix_zhaoxin_6000  || true
#fix_zhaoxin_6000G || true