#
# This Upstart config expects that Sauce Connect (SC) is installed at
# /usr/local/bin/sc. Edit that path if it is installed somewhere else.
#
# Copy this file to /etc/init/sc.conf, and do:
#
# $ sudo initctl reload-configuration
#
# Then you can manage SC via the usual upstart tools, e.g.:
#
#   $ sudo start sc
#   $ sudo restart sc
#   $ sudo stop sc
#   $ sudo status sc
#

description "SauceLabs' Sauce Connect tunnel worker service"

instance $SE_PORT
usage "SE_PORT - selenium port"

stop on stopping sc

setuid nobody
setgid nogroup
chdir /tmp
# Restart Sauce Connect if it exits
respawn
# Sauce Connect output go to $logdir/sc.log.
console log
# Bump maximum number of open files/sockets.
limit nofile 8192 8192

# Sauce Connect will be killed if doesn't stop within 2 minutes. SC usually
# exits much faster than 2 minutes but it can occasionally get stuck if the
# connectivity between SC & Saucelabs is interupted.
kill timeout 120

script
        # Load configuration
        test -r /etc/default/sc || { stop; exit 0; }
        . /etc/default/sc

        # Temporary PID file since it's a required option for SauceConnect
        pidfile="/tmp/.sauceconnect_$SE_PORT.pid"
        exec \
        env \
           SAUCE_USERNAME="$SAUCE_USERNAME" \
           SAUCE_ACCESS_KEY="$SAUCE_ACCESS_KEY" \
        /usr/local/bin/sc \
                --logfile - \
                --pidfile "$pidfile" \
                --se-port "$SE_PORT" \
                --no-remove-colliding-tunnels \
                --wait-tunnel-shutdown
end script

# Remove PID file once we've started the service since it's not needed
post-start exec rm -f "/tmp/.sauceconnect_$SE_PORT.pid"
