#!/bin/sh
glideusdCommand="glideusd"
pidFile="$HOME/.glideusd.pid"
daemonuser=$HOME
maxShutdownTime=15
glideusdDir="/usr/bin"
PIDFILE=".glideusd.pid"

glideusdPid=0

#input field seperator
IFS=":"

#make file $1 writeable by the user
makeFileWritable() 
{
    local filename="$1"
    echo "\n create new file $filename"
    touch $filename || return 1
    chmod u+w $filename || return 1
    return 0
}


#return 0 if the process with PID $1 is running
checkGlideusdIsRunning() 
{
    local pid="$1"
    echo "\n inside of checkGlideusdIsRunning(): pid is: $pid"
    if [ -z "pid" -o "pid" == " " ] glideusdPid
    then 
        echo "pid is null"
        return 1
    fi
  
    return 0
}


#return 0 if the process with PID $1 is our glideusd process
checkProcessIsOurGlideusd() 
{
     local pid="$1"
     local cmd="$(ps -p $pid --no-headers -o comm)"
     echo "\n inside of checkProcessIsOurGlideusd(): cmd is: "
     echo $cmd  
     if [ "$cmd" != $glideusdCommand ]
     then 
         return 1
     fi

     return 0
}


#return 0 if the process with PID $1 is running
checkOurGlideusdIsRunning() 
{
    local pid="$1"
    #echo "\n inside of checkOurGlideusdIsRunning(): pid is: $pid"
    if [ -z "pid" -o "pid" == " " ] 
    then 
        echo "pid is null"
        return 1
    fi
   
     local cmd="$(ps -p $pid --no-headers -o comm)"
     echo "\n inside of checkOurGlideusdIsRunning(): cmd is: "
     echo $cmd  
     if [ "$cmd" != $glideusdCommand ]
     then 
         echo "Oops. This is NOT our glideusd\n"
         return 1
     fi
     
     echo "This is our glideusd and it is running\n"
    return 0
}


#return 0 when glideusd is running and sets the variable $glideusdPid to the $PID
getGlideusdPid() 
{

	#glideusdPid="$(ps -C "glideusd" --no-headers -o pid)"
        #only check my glideusd
	username=$(whoami)
	glideusdPid="$(ps -U $username | grep glideusd | cut -c1-6 | xargs)"
	echo "\n glideusdPid is: " $glideusdPid

        if [ $glideusdPid ] && [ $glideusdPid -ne 0 ]
        then
            echo "\n glideusd is found, its PID = $glideusdPid \n "
            return $glideusdPid
        else
 	    echo "\n glideusd is NOT found\n "
            return 0
        fi      
}


#stop gildeusd
stopGlideusd() 
{
    getGlideusdPid
    if [ $? -eq 0 ]
    then 
      echo -n "glideusd is not running"
      return 0
    fi
    
    stopGlideusdProcess

    # checkGlideusdStatus

    if [ $? -ne 0 ]
    then 
      echo -n "stopping glideusd failed"
      return 1
    fi   

    return 0   
}


#stop glideusdProcess
stopGlideusdProcess() 
{
   
    echo "\n sending SIGKILL to kill glideusd: $glideusdPid...."
    kill -s KILL $glideusdPid || return 1
    #sudo kill -9 $glideusdPid || return 1
    
    #wait 10 seconds at most 
    local killWaitTime=100 
    #for((i=0; i<killWaitTime*10; i++))
    i=0
    while [ $i -lt $killWaitTime ]
    do
       echo "check glideusd:  $glideusdPid"
       #checkOurGlideusdIsRunning $glideusdPid
       getGlideusdPid
       if [ $? -eq 0 ]
       then 
           #echo  "remove $pidFile"
           ##rm -f $pidFile
           #sudo rm -f $pidFile
           return 0
       fi
       i=i+1
       sleep 0.1
    done
    echo "Error: glideusd could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
    return 1
}

#get PID and check it is our daemon and if it is, check its status

#return 0 when glideusd is running and sets the variable $glideusdPid to the $PID
checkGlideusdStatus() 
{ 
    while read account password uid gid name directory shell
	do
                #echo "$account:$uid:$gid:$name:$directory:$shell"
		if ( [ $uid -eq 0 ] && [ -d $directory ] && [ $directory = "/root" ] ) || 
                   ( [ $uid -gt 0 ] && [ -d $directory ] && [ $directory = "/home/$account" ] )
		then
			   if [ -f $directory/$PIDFILE ]
                           then 
                                    pidFile=$directory/$PIDFILE
				    
				    getGlideusdPid
				    if [ $? -eq 0 ]
				    then 
                                        echo "Need to stop the existing glideusd from user: $directory \n"
					stopGlideusdProcess
				    fi                                    

    		           fi

	 	fi
    done < /etc/passwd

    
    return 0
}


 
#start glideusd daemon
startGlideusd() 
{
    #checkGlideusdStatus
    getGlideusdPid
    if [ $? -ne 0 ]
    then 
        stopGlideusdProcess
    fi
    echo "starting glideusd ..."
    startGlideusdProcess
}


#start glideusd process
startGlideusdProcess() 
{
   # cd $glideusdDir || return 1
   
   # if [ -f $pidFile ]
   # then 
         #echo "\n ready to remove $pidFile"
         #rm -f $pidFile
   	 #sudo rm -f $pidFile
         #if [ -f $pidFile]
         #then
         #     echo "\n $pidFile still exists"
         #else
         #     echo "\n $pidFile is removed"
         #fi

	 #could be issue makeFileWritable $pidFile
	 #makeFileWritable $pidFile || return 1  
    #fi
   #$SHELL -c ./$glideusdCommand || return 1

   /usr/bin/glideusd
   sleep 1
  # read glideusdPid < $pidFile
  # echo $glideusdPid

   #checkOurGlideusdIsRunning $glideusdPid

   getGlideusdPid
   if [ $? -eq 0 ]
   then 
       echo "\n glideusd start failed"
       return 1
   fi

   echo "\n glideusd start sucessfully"
   return 0
}


#main function
main() {
#deleted rc_reset and rc_exit, could be an issue

case "$1" in
	start)
		  #start glideusd as a user session daemon
		  startGlideusd
                  exit 0
		  ;;
	stop)
           	  #stop glideusd
                  stopGlideusd
		   exit 0
                  ;;
	*)	
	          echo "\n Usage: glideusd {start|stop} "
                  exit 1
	          ;;
esac
}

main $1
