#! /bin/sh

## "@(#) $Id: uves.chkVNCserver,v 1.3 2007/08/07 13:24:00 jpritcha Exp $"

################################################################################
## Definition of functions
usage() {
  printf "\
Usage: ${execName} [-h|Dvnq] -n <number>

Check VNC server :<number> is running, if not start it.

  -h|--help: help
  -D|--debug: debug
  -n|--dryRun: dry-run
  -q|--quiet: quiet
     -q Only Warnings and Errors are written out (to stderr)
     -q -q increases quietness, only Errors are written out (to stderr)
     -q -q -q increases quietness, NO output to stdout or stderr
  -v|--verbose: verbose

  -N|--number <number>: multiple can be given, each one will be checked
     for and started if necessary
  -d|--depth <depth>: Color depth, default is ${depth}.
  -g|--geom <XxY>: desktop geometry, default is ${geom}
  --RESTART: Stop then restart each server
  --STOP: stop each server
"
  exit ${exstat:-0}
}

verboseLog() {
  [ ! -z "${vbose}" ] && echo "${execName}:: $1" > ${2:-/dev/stdout}
}

debugLog() {
  [ ! -z "${debug}" ] && echo "${execName}::debug:: $1" > ${2:-/dev/stdout}
}

notQuietLog() {
  [ -z "${quiet}" ] && echo "${execName}:: $1" > ${2:-/dev/stdout}
}

errorLog() {
  [ ${quietLevel:-0} -lt 3 ] && echo "${execName}::Error:: $1" > ${2:-/dev/stderr}
}

warningLog() {
  [ ${quietLevel:-0} -lt 2 ] && echo "${execName}::Warning:: $1" > ${2:-/dev/stderr}
}

execCmd() {
  [ ! -z "${debug}" ] || [ ! -z ${dryRun} ] && echo "${execName}::execCmd:: $1"
  [ -z "${dryRun}"  ] && eval ${1}
}

################################################################################
## Usage:
## checkVarIsSet <VAR-NAME> <level> [error-message] [exit-status]
##      <VAR-NAME>: name of variable to check for, no '$'
##         <level>: fatal|fatalNoExit|warn
## [error-message]: Optional Error/Warning message to print
##   [exit-status]: Optional exit status value
##
checkVarIsSet(){
  v1="$`echo $1`"
  v2="`eval echo $v1`"
  debugLog "Variable $1 is set to $v2"
  if [ -z "${v2}" ]; then
    debugLog "Variable $1 is not set"
    case $2 in
      fatal)       errorLog   "${3:-Variable $1 not set}"; exstat=${4:-1} ; usage ;;
      fatalNoExit) errorLog   "${3:-Variable $1 not set}"; (( exstat=${exstat-0}+${4:-1} ));;
      warn)        warningLog "${3:-Variable $1 not set}";;
      *)           errorLog   "*** Coding error:: error-level not recognised"; exit 1
    esac
  else
    debugLog "Variable $1 is set to $v2"
  fi
}
################################################################################

################################################################################
## Definition of variable who need default values
execName="`basename ${0}`"
quietLevel=0
depth=24
geom=1280x1024

################################################################################
## Command line options
while [ ! -z "${1}" ]; do

  case $1 in
    -h|--help)    usage ; shift;;
    -D|--debug)   debug="-D"; quiet=""; vbose="-v";  quietLevel=0 ; shift;;
    -n|--dryRun)  dryRun="-n"; shift;;
    -q|--quiet)   quiet="-q"; vbose=""; debug=""; (( quietLevel++ )) ; shift;;
    -v|--verbose) vbose="-v"; quiet="";  quietLevel=0 ; shift;;
    -N|--number)  Nums="${Nums} ${2}"; shift; shift;;
    -d|--depth)   depth="${2}"; shift; shift;;
    -g|--geom)    geom="${2}"; shift; shift;;
    --RESTART)    RESTART="--RESTART" ; shift ;;
    --STOP)       STOP="--STOP" ; shift ;;
    *)            exstat=1; usage; shift;;
  esac
done

################################################################################
## Main loop starts...

exstat=0
checkVarIsSet Nums fatal

for N in $Nums ; do
  AllProc="`ps axf | grep "Xvnc :${N} " | grep -v grep | cut -d: -f3- | awk '{print $3,$4}'`"
  debugLog "AllProc ::"
  debugLog "${AllProc}"
  MyProc="`ps xf | grep "Xvnc :${N} " | grep -v grep | cut -d: -f3- | awk '{print $3,$4}'`"
  debugLog "MyProc ::"
  debugLog "${MyProc}"
  if [ ! -z "${AllProc}" ]; then
    if [ -z "${MyProc}" ]; then
      errorLog "VNC server with number $N already running, but not owned by ${USER}"
      exstat=1
    else
      if [ ! -z "${STOP}" ] || [ ! -z "${RESTART}" ]; then
        verboseLog "Stopping VNC server $N"
        vncserver -kill :$N
      else
        verboseLog "VNC server with number $N already running."
      fi
    fi
  fi
  if [ -z "${STOP}" ]; then
    AllProc="`ps axf | grep "Xvnc :${N} " | grep -v grep | cut -d: -f3- | awk '{print $3,$4}'`"
    debugLog "AllProc ::"
    debugLog "${AllProc}"
    MyProc="`ps xf | grep "Xvnc :${N} " | grep -v grep | cut -d: -f3- | awk '{print $3,$4}'`"
    debugLog "MyProc ::"
    debugLog "${MyProc}"
    if [ -z "${AllProc}" ]; then
      execCmd "vncserver :${N} -depth ${depth} -geometry ${geom}"
    fi
  fi
done

exit ${exstat:-0}
