#!/usr/bin/openrc-run

LOGFILE=${LOGFILE-"/var/log/transmission.log"}
PIDFILE=${PIDFILE-"/var/run/transmission.pid"}

RUNAS_DEFAULT=${RUNAS_DEFAULT-"nobody"}
EXEC=${EXEC-"$(which transmission-daemon)"}

depend()
{
	need net
	[ -n "${AD_SERVICE}" ] && need ${AD_SERVICE} # fixme use rc_need in config!
	provide ${SVCNAME}
}


start()
{
	local _rc=0
	local _orcconf="/opt/etc/conf.d/transmission"
	_ee() {
		eerror $1
		_rc=1
	}
	ebegin "Starting \"${SVCNAME}\""
	eindent
	[ -z "${DOWNLOAD_DIR}" ] && _ee "DOWNLOAD_DIR must be specified in ${_orcconf}"
	[ -z "${WATCH_DIR}" ] && _ee "WATCH_DIR must be specified in ${_orcconf}"
	[ -z "${CONFIG_DIR}" ] && _ee "CONFIG_DIR must be specified in ${_orcconf}"
	[ -z "${WWWUSER}" ] && _ee "WWWUSER must be specified in ${_orcconf} for remote control"
	[ -z "${WWWPASS}" ] && _ee "WWWPASS must be specified in ${_orcconf} for remote control"
	if [ -z "${RUNAS}" ]; then
		RUNAS=${RUNAS_DEFAULT}
		ewarn "Warning: starting transmission from \"${RUNAS}\" user."
		ewarn "This is probably not what you want."
	fi
	if [ ${_rc} -eq 0 ]; then
		if [ -x ${EXEC} ]; then
			start-stop-daemon --start --exec ${EXEC} \
				--user ${RUNAS} --make-pidfile --pidfile ${PIDFILE} --background -- \
				--foreground --config-dir ${CONFIG_DIR} --download-dir ${DOWNLOAD_DIR} \
				-c ${WATCH_DIR} --auth --username ${WWWUSER} --password ${WWWPASS} \
				--allowed *.*.*.*,*.*.*.* --dht --no-blocklist \
				--logfile ${LOGFILE}
			_rc=$?
		else
			update_me
			eerror "${ME}: transmission executable not found."
			_rc=1
		fi
	fi
	eoutdent
	eend ${_rc}
	return ${_rc}
}

stop()
{
	ebegin "Stopping \"${SVCNAME}\""
	start-stop-daemon --stop --exec ${EXEC} --retry SIGTERM/10 --pidfile ${PIDFILE}
	eend 0
	return 0
}
