#!/bin/bash
if [ "$EUID" -ne 0 ]; then
	echo "To autoload kernel modules, you have to run this script with superuser"
	exit 1
fi

set -e

MODULE_CONF=${MODULE_DIR:="/usr/lib/modules-load.d"}"/openrgb.conf"
autoload() {
	mkdir -p $MODULE_DIR
	echo -ne "i2c-dev\n" > $MODULE_CONF
}
autoload_amd() {
	mkdir -p $MODULE_DIR
	echo -ne "i2c-dev\ni2c-piix4\n" > $MODULE_CONF
}
autoload_intel() {
	mkdir -p $MODULE_DIR
	echo -ne "i2c-dev\ni2c-i801\ni2c-nct6775\n" > $MODULE_CONF
}

case $1 in
	amd)
		echo "running amd install"
		autoload_amd
		printf "please reboot your computer and check if the i2c modules are loaded"
		;;
	intel)
		echo "running intel install"
		autoload_intel
		echo "please reboot your computer and check of the i2c modules are loaded"
		;;
	other)
		echo "We'll add i2c-dev to the autoload modules, but that might not be enough. Please check the documentation of you Motherboard/Instruction-set on how to access i2c"
		autoload
		echo "please reboot your computer and check if the i2c modules are loaded"
		;;
	auto)
		case $(grep "^vendor_id" /proc/cpuinfo | head -1 | awk '{print $3}') in
			AuthenticAMD)
				echo "Detected AMD processor"
				autoload_amd
				echo "please reboot your computer and check if the i2c modules are loaded"
				;;
			GenuineIntel)
				echo "Detected Intel processor"
				autoload_intel
				echo "please reboot your computer and check if the i2c modules are loaded"
				;;
			*)
				echo "Did not detect known processor, we'll add i2c-dev to the autoload modules, but that might not be enough. Please check the documentation of you Motherboard/Instruction-set on how to access i2c"
				autoload
				echo "please reboot your computer and check if the i2c modules are loaded"
				;;
		esac
		;;
	help)
		echo -ne "openrgb-modules is a shell script to automatically load modules required for i2c lightning control via OpenRGB.
		
		Usage:
		openrgb-modules auto: Try to automatically detect CPU vendor and load
		openrgb-modules amd: Add required modules for Advanced Micro Devices, Inc. Processors
		openrgb-modules intel: Add required modules for Intel(R) Corporation Processors
		openrgb-modules other: Only load the basic i2c module\n"
		;;
	*)
		echo "Usage: openrgb-modules [help/auto/amd/intel/other]"
esac
