#!/usr/bin/env sh

set -e

version=0.3
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
    # download and unpack firmware for the wireless dongle
    /usr/sbin/xone-get-firmware

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

    # checking a conflicting package (could have been built from source):
    if which xow &>/dev/null ; then
        echo 'Please uninstall xow, before installing xone!'
        exit 1
    fi

    # add kernel headers to install
    update-kernel -H

    echo "Installing xone $version..."

    if dkms install -m xone -v "$version"; then
        # Avoid conflicts between xpad and xone
        if lsmod | grep -q '^xpad'; then
            modprobe -r xpad
        fi

        # Avoid conflicts between mt76x2u and xone
        if lsmod | grep -q '^mt76x2u'; then
            modprobe -r mt76x2u
        fi
        echo ""
        echo "Installed. Please restart the system."
    else
        echo "Error. Please restart the system with new kernel, and restart xone install."
        exit 1
    fi
elif [ "$command" == "uninstall" ] ; then
    modules=$(lsmod | grep '^xone_' | 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 xone $version..."
        dkms remove -m xone -v "$version" --all
    else
        echo ""
        echo 'Driver is not installed!'
    fi
else
    echo ""
    echo "Usage: xone <install | force-install | uninstall>."
    exit 0
fi
