#!/sbin/runscript
# Redmine initscript with Thin by Andrew Eigus (c) 2015 Ahlers

SERVER=${SERVER:-projects.ahlers.com}
CONFIG=${CONFIG:-/etc/thin/redmine.yml}
RUBY=${RUBY:-/usr/bin/ruby}
DO_BUNDLER=${DO_BUNDLER:-1}
CHDIR=${CHDIR:-/opt/www/projects.ahlers.com}
THIN_USER=${THIN_USER:-redmine}
THIN_GROUP=${THIN_GROUP:-redmine}
THIN_PID=${THIN_PID:-/var/run/thin/thin.pid}
THIN_OPTS=${THIN_OPTS:-}

extra_commands="depend"

depend() {
	need net
	use nginx apache2 mysql
}

checkconfig() {
	if [ -n ${CHDIR} ]; then
		cd "${CHDIR}"

		if [ $? -ne 0 ]; then
			eerror "Cannot cd into requested directory"
			return 1
		fi
	fi

	if [ ! -f ${CONFIG} ]; then
		eerror "Unable to find the server configuration."
		eerror "Please set the CONFIG variable in /etc/conf.d/${SVCNAME} or"
		eerror "set NOCONFIG there to 1 to disable looking for a config file."
		return 1
	fi
}

buildargs() {
        echo -n "-C ${CONFIG} "
	echo -n "${THIN_OPTS}"
}

action() {
	checkconfig || return 1

	[ ${DO_BUNDLER} -ne 0 ] && RUBY="${RUBY} /usr/bin/bundle exec"

	ebegin "$2 thin server ${SERVER}"
	${RUBY} /usr/bin/thin $(buildargs) --tag ${SERVER} $1
	eend $?
}

start() {
	action start 'Starting'
}

stop() {
	action stop 'Stopping'
}

restart() {
	action restart 'Restarting'
}

start_pre() {
	checkpath -d -m 0775 -o ${THIN_USER}:${THIN_GROUP} $(dirname ${THIN_PID})
}
