#!/usr/bin/env bash
set -e

REPO_PATH="$(/usr/bin/dirname $([ -L $0 ] && /bin/readlink -f $0 || echo $0))"
source "${REPO_PATH}/install.common"

check_if_installed
check_module_options "$1" "$2"
check_if_loaded

echo "Building $V4L2_LOOPBACK_KO"
make -C $V4L2_LOOPBACK_DIR

if [ ! -e "$V4L2_LOOPBACK_DIR/$V4L2_LOOPBACK_KO" ]
then
	echo "$V4L2_LOOPBACK_KO not built.. Failure"
	exit 1;
fi

set +e
if mokutil --sb-state | grep -qF enabled; then
	echo "Secure Boot is enabled, attempting to sign the driver"
	PRIV="/var/lib/shim-signed/mok/MOK.priv"
	PUB="/var/lib/shim-signed/mok/MOK.der"
	if [[ ! -e "$PRIV" || ! -e "$PUB" ]]
	then
		echo "please specify signing key location (or leave empty to sign manually later)"
		echo "You can Google 'secure boot' for your distro"
		echo ""
		read -rp "Enter the path of the public key: " PUB
		read -rp "Enter the path of the private key: " PRIV
	fi

	SIGNER_BIN="/usr/src/linux-headers-`uname -r`/scripts/sign-file"
	[ -e "$SIGNER_BIN" ] || SIGNER_BIN="/usr/src/kernels/`uname -r`/scripts/sign-file"
	[ -e "$SIGNER_BIN" ] || SIGNER_BIN="kmodsign"
	if [[ -e "$PRIV" && -e "$PUB" ]]
	then
		$SIGNER_BIN sha512 "$PRIV" "$PUB" "$V4L2_LOOPBACK_DIR/$V4L2_LOOPBACK_KO" \
			|| echo "warning: device signing failed."
	fi
fi
set -e

mkdir -p $DRIVER_LOCATION || true

echo "Copying file"
set -x
cp "$V4L2_LOOPBACK_DIR/$V4L2_LOOPBACK_KO" $DRIVER_LOCATION
set +x

echo "Registering webcam device"
modprobe videodev
insmod $DRIVER_LOCATION$V4L2_LOOPBACK_KO width=$WIDTH height=$HEIGHT || echo "warning: insmod failed"

echo "Running depmod"
depmod -a
make -C $V4L2_LOOPBACK_DIR clean

register_video_module_at_boot_time

echo "Done"
