#!/bin/bash
### BEGIN INIT INFO
# Description: StarWind Virtual SAN Service
# Required-Start: networking $remote_fs $local_fs
# Default-Start: 2 3 4 5
# Default-Stop:
# chkconfig: 345 20 80
### END INIT INFO

lrbc="\e[91m\e[1m"
lgbc="\e[92m\e[1m"
rc="\e[0m"

WINEDEBUG=-all
WINEPREFIX=/opt/starwind/starwind-virtual-san
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
WINE=/usr/bin/wine64
SW_PATH=/opt/starwind/starwind-virtual-san/drive_c/starwind
SW=StarWindService.exe
SWARGS='--console -o -lpStarWindVSA'
EVENTS=/var/starwind/starwind-virtual-san/events/StarWindVSA-Events.log

start() {
if pgrep StarWindService > /dev/null 2>&1
 then
 echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"running"$rc
    else
cd $SW_PATH
logrotate -f /etc/logrotate.d/starwind-virtual-san
sleep 5
screen -dmS "StarWindVSA" /bin/bash -c "WINEDEBUG=$WINEDEBUG WINEPREFIX=$WINEPREFIX $WINE $SW $SWARGS" > /dev/null 2>&1
touch "$EVENTS" >/dev/null 2>&1
logwatcher "$EVENTS"& >/dev/null 2>&1
echo -e $lgbc"StarWind Logwatcher:"$rc $lrbc"started"$rc
echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"started"$rc
fi
}

stop() {
cd $SW_PATH
if pgrep StarWindService > /dev/null 2>&1
    then
	/bin/kill -SIGINT ` pgrep StarWindService`
	killcount=0
        while  pgrep StarWindService > /dev/null 2>&1
	do sleep 1
	(( killcount++ ))
	    if [ killcount == 300 ]
		then /bin/kill -SIGKILL ` pgrep StarWindService`
	    fi
        done
        sleep 5
        wineserver -k9
        kill -9 `pgrep inotifywait`
	echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"stopped"$rc
    else
	echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"not running"$rc
    fi
}

status() {
if pgrep StarWindService > /dev/null 2>&1
    then
	echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"running"$rc
    else
	echo -e $lgbc"StarWind Virtual SAN Service:"$rc $lrbc"not running"$rc
    fi
}
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 5
        start
        ;;
    status)
        status
        ;;
    *)
    echo -e $lgbc"Usage: $0 {start|stop|restart|status}"$rc
esac

exit 0
