#!/bin/bash
### BEGIN INIT INFO
# Provides:          seh-utn-srv
# Required-Start:    $syslog
# X-Start-Before:    
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start or stop utnservice.
# Description:       Starts or stops the utnservice program
#                    which provides USB devices from network.
### END INIT INFO

INSTALL_DIR=/usr/sbin
DRIVER_CHAR_DEV_NAME="seh_vhci_dev"
SERVICE_FILE_NAME="utnservice"
GUI_FILE_NAME="utnmanager"
CLI_FILE_NAME="utnm"
DRIVER_NAME="seh_vhcd"

# load the kernel module
load_kernel_module () {
	if [[ "$(lsmod | grep $DRIVER_NAME)" ]]; then
		return 0
	fi
	printf "Loading $DRIVER_NAME  in Kernel..."
	modprobe $DRIVER_NAME >/dev/null 2>&1
	if [ ! "$(lsmod | grep $DRIVER_NAME)" ]; then
		echo;echo "Fail to load $DRIVER_NAME"
		exit 1
	else
		echo "Done"
	fi
	major=$(awk "\$2 == \"$DRIVER_CHAR_DEV_NAME\" {print \$1}" /proc/devices)
	if [ ! -c /dev/$DRIVER_CHAR_DEV_NAME ]; then
		echo "Making /dev/$DRIVER_CHAR_DEV_NAME"
		mknod /dev/$DRIVER_CHAR_DEV_NAME c $major 0 >/dev/null 2>&1
		chmod 666 /dev/$DRIVER_CHAR_DEV_NAME >/dev/null 2>&1
	fi
	return 0
}
# start the service
load_service () {
	echo "Starting the Service daemon..."
	$INSTALL_DIR/$SERVICE_FILE_NAME >/dev/null 2>&1
	return 0
}
# stop the service
stop_service  () {
	PID="$(pidof -s $SERVICE_FILE_NAME)"
	if [ $PID ]; then
		kill -9 $PID
		echo "Kill service"
    fi
}
# delete char device and remove module
stop_module () {
	
    if [ -c /dev/$DRIVER_CHAR_DEV_NAME ]; then
		echo "remove  /dev/$DRIVER_CHAR_DEV_NAME"
		rm /dev/$DRIVER_CHAR_DEV_NAME
    fi
    
    if [ "$(lsmod | grep seh_vhcd)" ]; then
		rmmod seh_vhcd
		printf "Remove module..."
    fi
    
    echo "OK"
}
# utnservice creates the config dir with drwxr-x--- , so it is 
# unreadable and options seem not to be stored
# => workaround
check_config_perms () {
    if [ ! -d /etc/xdg/SEH\ Computertechnik\ GmbH/ ]; then
        mkdir -p -m 0775  /etc/xdg/SEH\ Computertechnik\ GmbH/
    else
        perm=`stat -c%A /etc/xdg/SEH\ Computertechnik\ GmbH/`
        if [ "$perm" == "drwxr-x---" ]; then
	        chmod g+w -R /etc/xdg/SEH\ Computertechnik\ GmbH/
	        chmod o+r -R /etc/xdg/SEH\ Computertechnik\ GmbH/
	        chmod o+x    /etc/xdg/SEH\ Computertechnik\ GmbH/
        fi
    fi
}
# Check for root rights
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Main

case "$1" in
  start)
	load_kernel_module
	load_service
	check_config_perms
    ;;
  stop)
	stop_service
	stop_module
    ;;
  restart|force-reload)
 	/etc/init.d/seh-utn-srv stop
 	/etc/init.d/seh-utn-srv start
    ;;
  *)
    echo "Usage: /etc/init.d/seh-utn-srv {start|stop|restart|force-reload}"
    exit 1
    ;;
esac		

