#!/bin/bash

lockdir=/var/run
pidfile=gpsinit.pid
lockfile=gpsinit.lock
dfile=/dev/gps
debug="1"
log="echo"

if test $debug = "1"
then log="logger" 
fi

check() {
if [ -f $lockdir/$lockfile ]; then
    find $lockdir -name $lockfile -cmin +1 -exec rm {} \;
     #$log "***************** GPSINIT: find old lockfile *********************"
fi
if [ -f $lockdir/$lockfile ]; then
    $log "***************** Already run GPSINIT    ***************************"
    sleep 10 && cleanlock
    $log "***************** RM old $lockdir/$lockfile *********************"
    exit
 else
    $log "***************** GPSINIT Start      *******************************"
    touch $lockdir/$lockfile
fi
devfile=`ls -lR /dev/gps`
ret=$?
if [ $ret = 0 ] ; then 
    $log "***************** GPSINIT DEV Found: `echo $devfile | awk  '{print $11}'` linked to /dev/gps ****"
    daemonize
 else
    $log "***************** GPSINIT DEV Not Found, wait..**********************"
    sleep 10
    contr
fi
}

cleanlock() {
    rm -f $lockdir/$lockfile
}

daemonize() {

AVA='/bin/ps -C gpsd --format args --noheaders'

if $AVA | grep '/dev/gps' > /dev/null 2>&1; then
    AVAR=`/bin/ps -C gpsd --format args --noheaders`    
    $log "***************** GPSINIT STOP      ********************************"
    bubblemsg other "GPS Device Detection" "This GPS device You are reconneted. (GPSD already running: $AVAR) 
    <i>Please waiting for device initializing..</i>"
    exit
 else
  if $AVA | grep gpsd > /dev/null 2>&1; then
    AVAR=`/bin/ps -C gpsd --format args --noheaders`    
    $log "***************** Killing GPSD ***********************************"
    bubblemsg other "GPS Daemon" "Already running bad path: $AVAR This change now to correct device.. (10 sec)"&
    pkill gpsd 
    sleep 20
    $log "***************** Killed OLD GPSD ********************************"
    chmod 777 $dfile
    gpsd -p $dfile 
    $log "***************** GPSD Restart ($AVAR) ***************************"
    sleep 25
    bubblemsg other "New GPS Device" "New GPS device connected in PC. GPSD now running on $dfile"
    cleanlock
    $log "***************** Remove lockfile:$lockdir$lockfile **************"
    exit
  fi
fi
$log "***************** GPSD Starting....  *******************************"
sleep 2
bubblemsg other "GPS Device Detected" "Initializing, please wait (10-20sec..)" &
#sleep 10
cat /dev/gps &
sleep 5
killall cat -KILL
sleep 10
gpsd -p $dfile
bubblemsg other "New GPS Device Detect" "New GPS device connected to PC port ($dfile)"
$log "***************** GPSD Running and use $dfile device  ************"
}

contr() {
devfile=`ls -lR /dev/gps`
ret=$?
if [ $ret = 0 ] ; then 
    $log "***************** GPSINIT DEV Now Found! *********************************"
    daemonize
 else
    $log "***************** GPSINIT ERROR! Device where found ? ****************************"
    bubblemsg other "New GPS Device Detect ERROR" "New GPS device connected but not found !"
    exit
fi
}
sleep 5
check
