#!/bin/sh
#
# Function that loads the kernel modules and starts the daemon/service
#
do_start()
{
    echo "Making sure drivers are up to date..."
    /usr/local/natinst/nikal/bin/updateNIDrivers --no-prompt --fast || exit 1
    echo -n "Loading: "
    echo -n "NiRioSrv "
    modprobe NiRioSrv || exit 1
    echo -n "niusrpriok "
    modprobe niusrpriok || exit 1
    echo ""
    #TODO: Remove this when permission issues are resolved in RIO
    if [ -d /dev/ni ];
    then
        chmod +x /dev/ni
    fi
    echo "Starting: niusrpriorpc"
    if [ -z $(ps -a | grep -o niusrpriorpc) ]; then
        export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
        ldconfig
        if [ -e /usr/local/natinst/niusrp/bin/niusrpriorpc ]; then
           chmod +x /usr/local/natinst/niusrp/bin/niusrpriorpc
           /usr/local/natinst/niusrp/bin/niusrpriorpc &
        else
           if [ -e /usr/sbin/niusrpriorpc ]; then
              chmod +x /usr/sbin/niusrpriorpc
              /usr/sbin/niusrpriorpc &
           else
              echo "ERROR: niusrprorpc not found"
           fi
        fi
    fi
}

#
# Function that stops the daemon/service and unloads the kernel modules
#
do_stop()
{
    echo "Stopping: niusrpriorpc"
    pkill niusrpriorpc
    echo -n "Unloading: "
    echo -n "niusrpriok "
    modprobe -r niusrpriok
    echo -n "NiRioSrv "
    modprobe -r NiRioSrv
    echo ""
}

#
# Function that gets the status of loaded kernel modules and daemon/service
#
get_status()
{
    echo -n "Modules Loaded: "
    echo -n "`lsmod | grep -o "nikal "`"
    echo -n "`lsmod | grep -o "nibds "`"
    echo -n "`lsmod | grep -o "nistreamk "`"
    echo -n "`lsmod | grep -o "NiRioSrv "`"
    echo -n "`lsmod | grep -o "niusrpriok "`"
    echo ""
    echo "Server: "`ps -a | grep -o niusrpriorpc`
}

check_root()
{
    if [ $(id -u) -ne 0 ]
    then
        echo "This script must be run as root." >&2
        exit 1
    fi
}

case "$1" in
  start)
    check_root
    do_start
    ;;
  stop)
    check_root
    do_stop
    ;;
  restart|condrestart)
    check_root
    do_stop
    do_start
    ;;
  status)
    get_status
    ;;
  *)
    echo "Usage: $N {start|stop|restart|condrestart|status}" >&2
    exit 1
    ;;
esac

exit 0
