#!/bin/bash

set -e

module=nano-xilinx-drv/rhel-1.0.0

uninstall_obsolete=false

while getopts 'ho' opt; do
    case "$opt" in
        o)
            uninstall_obsolete=true
            ;;
        h)
            printf "%s: [-h]\n" "$0"
            printf "See man page\n"
            exit 0
            ;;
    esac
done

wait_for_death () {
    local timeout_s=5
    while [ "$((timeout_s -= 1))" -ne 0 ] && [ -n "$(lsof /dev/enyx_hfp_*)" ]; do
        sleep 1
    done
}

# Retrieve the list of processes with currently using a HFP device.
readonly hfp_devices_pids=$(lsof -Fp -- /dev/enyx_hfp_* 2>/dev/null | sed s/p//g)
if [ -n "${hfp_devices_pids}" ]; then
    # Gently ask for any process using the devices to terminate.
    kill -TERM "${hfp_devices_pids}" 1>/dev/null 2>&1 || :
    wait_for_death

    # Kill any remainder.
    kill -KILL "${hfp_devices_pids}" 1>/dev/null 2>&1 || :
    wait_for_death
fi

# Unload modules in the correct order.
modprobe -r enyx_hfp{_mm,_net,_rx,_tx,_id,_pci,} || :

if $uninstall_obsolete; then
    # This argument is now a no-op as previous
    # installation cleaning is perfomed
    # by enyx-hfp-kmod-install script.
    exit 0
fi

dkms remove $module --all

exit 0
