#!/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/proxy.pid
  LOGDIR=/var/log/
fi

# Read configuration variable file if it is present
[ -e /etc/sysconfig/xpra ] && . /etc/sysconfig/xpra
[ -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.
if [ -f /etc/init.d/functions ]; then
  # Red Hat
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
  # Red Hat
  . /etc/rc.d/init.d/functions
elif [ -f /etc/rc.status ]; then
  # SUSE
  . /etc/rc.status
  rc_reset
  LC_ALL=en_US.UTF-8
elif [ -f /lib/lsb/init-functions ]; then
  # Debian
  . /lib/lsb/init-functions
else
  exit 1
fi

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`
  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
