#!/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
# 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

[ -e /etc/sysconfig/xpra ] && . /etc/sysconfig/xpra
[ -e /etc/default/xpra ] && . /etc/default/xpra

start() {
  echo 'Starting service…' >&2
  xpra proxy $VIRTUAL_DISPLAY \
	--bind-tcp=0.0.0.0:$PORT --auth=$AUTH --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
}

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