#!/bin/sh
### BEGIN INIT INFO
# Provides:          xpra
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Xpra proxy server
# Description:       Xpra proxy server
### END INIT INFO

VIRTUAL_DISPLAY=:14500
PORT=14500
LOGFILE=xpra.log
if [ "$(id -u)" != "0" ]; then
	PIDFILE=$HOME/.xpra/proxy.pid
	LOGDIR=$HOME/.xpra
else
	PIDFILE=/run/xpra.pid
	LOGDIR=/var/log/
fi

# Read configuration variable file if it is present
[ -e /etc/default/xpra ] && . /etc/default/xpra
# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
. /lib/lsb/init-functions || exit 1

start() {
  echo 'Starting service…' >&2
  xpra proxy $VIRTUAL_DISPLAY \
	--bind=/run/xpra/system --auth=$AUTH \
	--bind-tcp=0.0.0.0:$PORT --tcp-auth=$TCP_AUTH --ssl-cert=/etc/xpra/ssl-cert.pem \
	--socket-permissions=666 --debug=$DEBUG \
	--daemon=yes --log-file=$LOGFILE --log-dir=$LOGDIR --pidfile=$PIDFILE
  if [ "$?" = "0" ];then
	echo 'Service started' >&2
  else
  	echo 'Service failed to start' >&2
  	exit 1
  fi
}

stop() {
  PID=`cat $PIDFILE 2> /dev/null`
  if [ -z "$PID" ]; then
	echo "Service not started, pidfile not found"
  else
	echo "Stopping service with pid $PID…" >&2
  	kill $PID
  	echo 'Service stopped' >&2
  fi
}

status() {
  # No pidfile, probably no daemon present
  [ ! -f "$PIDFILE" ] && return 1
  PID=`cat $PIDFILE 2> /dev/null`
  #[ ! -d /proc/$PID ] &&  return 1
  #cmd=`cat /proc/$PID/cmdline | tr "\000" "\n"|head -n 1 |cut -d : -f 1`
  #[ "$cmd" != "xpra" ] &&  return 1
  if [ -z "$PID" ]; then
  	echo "Service not started"
  else
	  echo "Service running with pid $PID…" >&2
  fi
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status
    ;;
  restart|force-reload)
    stop
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|force-reload}"
esac
