#!/bin/bash

if ! grep -qs purism,librem5 /sys/firmware/devicetree/base/compatible; then
  echo "Not a Librem5. Skipping."
  exit 0
fi

# modules to be loaded when LSM9DS1 becomes active ordered how to load them
MODULES=( 'st_lsm6dsx' 'st_lsm6dsx_spi' 'st_lsm6dsx_i2c' 'st_magn' 'st_magn_i2c')

# modules already loaded in the order needed to unload them
LOADED=( `lsmod | grep -E "^st_lsm6dsx|^st_magn" | cut -f1 -d' ' | sort -r` )

if [[ `cat /sys/devices/platform/rfkill-hks/rfkill/*/hard | uniq` == '1' ]]; then
	# all hks are enabled, LSM9DS1 is disabled

	# unload any st_lsm6dsx module that is loaded in the correct order
	for M in ${LOADED[@]}; do
		rmmod "$M"
	done

	# unbind vcnl4000 driver if bound
	if [ -h /sys/bus/i2c/drivers/vcnl4000/1-0060 ]; then
		echo 1-0060 > "/sys/bus/i2c/drivers/vcnl4000/unbind"
	fi

else
	# any hks is disabled, LSM9DS1 is enabled

	# load any module from $MODULES not yet loaded
	for M in ${MODULES[@]}; do
		# iter over indices of $LOADED...
		for L in "${!LOADED[@]}"; do
			# ...to check whether the module to be loaded $M
			# is already loaded (and thereby in array LOADED)
			if [[ "${LOADED[$L]}" == "$M" ]]; then
				# if $M already is loaded try next M out of MODULES
				break
			fi
		done
		# if not yet loaded, load $M
		modprobe "$M"
	done

	# bind vcnl4000 driver if unbound
	if ! [ -h /sys/bus/i2c/drivers/vcnl4000/1-0060 ]; then
		echo 1-0060 > "/sys/bus/i2c/drivers/vcnl4000/bind"
	fi
fi
