#!/bin/bash
#
# xvfb	Startup script for Xvfb virtual framebuffer X server
#
# chkconfig: 	35 90 10
# description: 	Xvfb is an X server that can run on machines with no display 
# 		hardware and no physical input devices.
# processname: 	xvfb
# config: 	/etc/X11
# pidfile: 	/var/run/xvfb${display}.pid

name=Xvfb
desc="Virtual framebuffer X server"
daemon=/usr/bin/${name}
display=99
pidfile=/var/run/xvfb${display}.pid
lockfile=/var/lock/${name}
options=":${display} -screen 0 1900x1280x24 -fbdir /var/run -ac -nolisten tcp"
RETVAL=0


# check existence of a command
command_exists()
{
        if command -v $1 &>/dev/null;
        then
                return 0
        else
                return 1
        fi
}

# Generate platform dependent start/stop/reload commands
make_commands()
{
	if command_exists start-stop-daemon;
	then
		# debian/ubuntu
		. /lib/lsb/init-functions
		_cmd="start-stop-daemon"
		_opts="--quiet --pidfile $pidfile --exec $daemon"
		start_command="$_cmd  $_opts --background  --make-pidfile --start -- $options"
		stop_command="$_cmd --stop $_opts"
		reload_command="$_cmd --stop --signal 1 --oknodo $_opts"
		status_command="status_of_proc -p ${pidfile} $daemon $name"
	elif [ -f "/etc/init.d/functions" ];
	then
		# fedora/RHEL/centos
		# Get function from functions library
		. /etc/init.d/functions 
		# note: no pidfile used in RHEL configuration
		start_command="daemon setsid sh -c 'cd / && $daemon $options &' >/dev/null 2>&1 </dev/null"
		stop_command="killproc -d 10 $daemon"
		reload_command="killproc $daemon -HUP"
		status_command="status $daemon"
	else
		start_command="echo not supported"
		stop_command="echo not supported"
		reload_command="echo not supported"
	fi
}

# Start the service
start() {
    echo -n "Starting $desc ($name): "
    echo ${start_command}
    ${start_command}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch ${lockfile}
    return $RETVAL
}

# Stop the service 
stop() {
	echo -n "Stopping $desc ($name): "
    echo ${stop_command}
    ${stop_command}
    RETVAL=$?
    echo
  [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

# Reload configuration 
reload() {
	echo -n "Reloading $name configuration: "
	command ${reload_command}
	RETVAL=$?
	echo
}

### main logic ###

make_commands

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
   	${status_command}
   	RETVAL=$?
	;;
  restart)
	stop
	start
	;;
  reload)
	reload
	;;
  condrestart)
	if [ -f ${pidfile} ] ; then
		stop
		start
	fi
	;;
  help)
	$daemon --help $@
	RETVAL=$?
	;;
  *)
	echo $"Usage: $prog {start|stop|restart|condrestart|reload|status|help|}"
	exit 1
esac

exit $RETVAL

