#!/usr/bin/env sh

set -e

version=0.2.2
command="$1"

if [ "$(id -u)" -ne 0 ]; then
    echo 'This script must be run as root!'
    exit 1
fi

if [ "$command" == "install" ] || [ "$command" == "force-install" ] ; then
       if [ -n "$(dkms status universal-pidff)" ] && [ "$command" != "force-install" ] ; then
        echo 'Driver is already installed!'
        echo 'Use: "universal-pidff force-install" for reinstall.'
        exit 1
    fi

    # add kernel headers to install
    update-kernel -H

    echo "Installing universal-pidff $version..."

    if dkms install -m universal-pidff -v "$version"; then
        echo "Installed. Please restart the system."
    else
        echo "Error. Please restart the system with new kernel, and restart universal-pidff install."
        exit 1
    fi
elif [ "$command" == "uninstall" ] ; then
    modules=$(lsmod | grep 'universal-pidff' | cut -d ' ' -f 1 | tr '\n' ' ')
    if [ -n "$modules" ]; then
        echo "Unloading modules: $modules..."
        # shellcheck disable=SC2086
        modprobe -r -a $modules
    fi
    if [ -n "$version" ]; then
        echo "Uninstalling universal-pidff $version..."
        dkms remove -m universal-pidff -v "$version" --all
    else
        echo ""
        echo 'Driver is not installed!'
    fi
else
    echo ""
    echo "Usage: universal-pidff <install | force-install | uninstall>."
    exit 0
fi
