#!/bin/bash
#
#
# Uninstall script for Sentinel LDK Runtime Environment
#
# return codes:
#   0 - success
#   1 - missing permissions (must be run as root)
#   4 - unrecognized system
#   6 - uninstall aksusbd RPM/DEB failed

# check for root user
if [ `id -u` -ne 0 ]; then
    echo "Installer must be run as root" 1>&2
    echo "Aborting..." 1>&2
    exit 1
fi

# check for Linux
if [ `uname -s` != "Linux" ]; then
    echo "Not running on Linux!" 1>&2
    echo "Aborting..." 1>&2
    exit 4
fi

# destination directory
dest_dir=/usr/sbin

# detect the init system
if [ -d /etc/init.d ]; then
    init_system=sysv
    script_dir=/etc/init.d
elif [ -d /usr/lib/systemd/system ]; then
    init_system=systemd
    script_dir=/etc/systemd/system
elif [ -d /etc/rc.d ]; then
    init_system=BSD
    script_dir=/etc/rc.d
else
    echo "Unsupported init script system!" 1>&2
    echo "Aborting..." 1>&2
    exit 4
fi

# check if a DEB is already installed
dpkg --help > /dev/null 2>&1
if [ $? -ne 127 ]
then
    dpkg -l aksusbd 2> /dev/null | grep "^ii" > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        echo "The aksusbd DEB is installed on this system." 1>&2
        dpkg -r aksusbd
        if [ $? -ne 0 ]
        then 
            echo "Uninstall aksusbd DEB failed"
            exit 6
        fi
        exit 0
    fi
fi

# check if a RPM is already installed
rpm --help > /dev/null 2>&1
if [ $? -ne 127 ]
then
    rpm_name=`rpm -qa 2>/dev/null | grep ^aksusbd | head -1`
    if [ ! -z "$rpm_name" ]
    then
        echo "The $rpm_name RPM is installed on this system." 1>&2
        rpm -e aksusbd
        if [ $? -ne 0 ]
        then 
            echo "Uninstall aksusbd RPM failed"
            exit 6
        fi
        exit 0
    fi
fi

echo "Stopping Sentinel LDK Runtime Environment..."
case $init_system in
sysv|BSD)
    # if not installed, we cannot stop it
    if [ -e $script_dir/aksusbd ]; then
        sh $script_dir/aksusbd stop
    fi
    ;;
systemd)
    # if not installed, we cannot stop it
    if [ -e $script_dir/aksusbd.service ]; then
        systemctl stop aksusbd
    fi
    ;;
esac

echo "Removing files ..."
rm -f $dest_dir/aksusbd
rm -f $dest_dir/winehasp
rm -f $dest_dir/hasplmd
rm -f /etc/udev/rules.d/80-hasp.rules

case $init_system in
sysv|BSD)
    # startup directory
    if [ -d /etc/rc.d ]; then
        startup_dir=/etc/rc.d
    else
        startup_dir=/etc
    fi
    rm -f $startup_dir/rc2.d/S23aksusbd
    rm -f $startup_dir/rc3.d/S23aksusbd
    rm -f $startup_dir/rc4.d/S23aksusbd
    rm -f $startup_dir/rc5.d/S23aksusbd

    rm -f $script_dir/aksusbd
    ;;
systemd)
    systemctl disable aksusbd
    systemctl disable winehasp
    systemctl disable hasplmd

    rm -f $script_dir/aksusbd.service
    rm -f $script_dir/winehasp.service
    rm -f $script_dir/hasplmd.service
    ;;
esac

echo "Done"

