#!/bin/bash /etc/rc.common

START=99
APP=seahub
EXTRA_HELP="	clearsessions	Clears expired sessions from database"
EXTRA_COMMANDS="clearsessions"

SEAHUB_FASTCGI=0
SEAHUB_PORT=8000
SEAHUB_METHOD=threaded
SEAHUB_WORKERS=3

[ -f /etc/config/seafile ] && \
	. /etc/config/seafile

INSTALLPATH=/usr/share/seafile/seafile-server
TOPDIR=$(dirname "${INSTALLPATH}")
default_ccnet_conf_dir=${TOPDIR}/ccnet
central_config_dir=${TOPDIR}/conf

manage_py=${INSTALLPATH}/seahub/manage.py
gunicorn_conf=${INSTALLPATH}/runtime/seahub.conf
pidfile=/var/run/seafile/seahub.pid
errorlog=${INSTALLPATH}/runtime/error.log
accesslog=${INSTALLPATH}/runtime/access.log
gunicorn_exe=/usr/bin/gunicorn

function check_python_executable() {
	if [[ "$PYTHON" != "" && -x $PYTHON ]]; then
		return 0
	fi

	if which python2.7 2>/dev/null 1>&2; then
		PYTHON=python2.7
	elif which python27 2>/dev/null 1>&2; then
		PYTHON=python27
	else
		echo
		echo "Can't find a python executable of version 2.7 or above in PATH"
		echo "Install python 2.7+ before continue."
		echo "Or if you installed it in a non-standard PATH, set the PYTHON enviroment varirable to it"
		echo
		exit 1
	fi
}

function validate_ccnet_conf_dir() {
	if [[ ! -d ${default_ccnet_conf_dir} ]]; then
		echo "Error: there is no ccnet config directory."
		echo "Have you run '/etc/init.d/seafile setup'?"
		echo ""
		exit 1
	fi
}

function read_seafile_data_dir() {
	seafile_ini=${default_ccnet_conf_dir}/seafile.ini
	if [[ ! -f ${seafile_ini} ]]; then
		echo "Error: ${seafile_ini} not found."
		exit 1
	fi
	seafile_data_dir=$(cat "${seafile_ini}")
	if [[ ! -d ${seafile_data_dir} ]]; then
		echo "Your seafile server data directory \"${seafile_data_dir}\" is invalid or doesn't exits."
		echo "Please check it first, or create this directory yourself."
		echo ""
		exit 1
	fi
}

function validate_seahub_running() {
	if pid=$(pgrep -f "${manage_py}" 2>/dev/null); then
		return 1
	elif pid=$(pgrep -f "seahub.wsgi:application" 2>/dev/null); then
		return 1
	fi
}

function validate_port() {
	if ! [[ ${SEAHUB_PORT} =~ ^[1-9][0-9]{1,4}$ ]] ; then
		printf "\033[033m${SEAHUB_PORT}\033[m is not a valid port number\n"
		exit 1
	fi
}

function warning_if_seafile_not_running() {
	if ! pgrep -f "seafile-controller -F ${central_config_dir}" 2>/dev/null 1>&2; then
		echo
		echo "Error: seafile-controller not running. Have you run \"/etc/init.d/seafile start\"?"
		echo
		exit 1
	fi
}

function prepare_seahub_log_dir() {
	logdir="${TOPDIR}/logs"
	if ! [[ -d "${logsdir}" ]]; then
		if ! mkdir -p "${logdir}"; then
		    echo "Error: failed to create log dir \"${logdir}\""
		    exit 1
		fi
	fi
	export SEAHUB_LOG_DIR="${logdir}"
}

function before_start() {
	prepare_env
	warning_if_seafile_not_running
	if ! validate_seahub_running; then
		echo "Seahub is already running."
		exit 1
	fi
	prepare_seahub_log_dir
	validate_port
}

function start_seahub() {
	before_start
	echo "Starting seahub at port ${SEAHUB_PORT} ..."
	check_init_admin
	$PYTHON $gunicorn_exe seahub.wsgi:application -c "${gunicorn_conf}" -b "0.0.0.0:${SEAHUB_PORT}" --preload

	# Ensure seahub is started successfully
	retry=1
	while ! validate_seahub_running && [[ ! -f "${pidfile}"  ]] && [[ $retry -lt 120 ]]; do sleep 1; ((retry++)); done
	if ! validate_seahub_running && [[ -f "${pidfile}" ]]; then
		echo
		echo "Seahub is started"
		echo
	else
		printf "\033[33mError: Seahub failed to start.\033[m\n"
		exit 1
	fi
}

function start_seahub_fastcgi() {
	before_start

	# Returns 127.0.0.1 if SEAFILE_FASTCGI_HOST is unset or hasn't got any value,
	# otherwise returns value of SEAFILE_FASTCGI_HOST environment variable
	address=`(test -z "$SEAFILE_FASTCGI_HOST" && echo "127.0.0.1") || echo $SEAFILE_FASTCGI_HOST`

	echo "Starting seahub (fastcgi) at ${address}:${SEAHUB_PORT} ..."
	check_init_admin
	$PYTHON "${manage_py}" runfcgi host=${address} port=${SEAHUB_PORT} pidfile=${pidfile} \
		outlog=${accesslog} errlog=${errorlog} maxchildren=${SEAHUB_WORKERS} method=${SEAHUB_METHOD}

	# Ensure seahub is started successfully
	retry=1
	while ! validate_seahub_running && [[ ! -f "${pidfile}"  ]] && [[ $retry -lt 120 ]]; do sleep 1; ((retry++)); done
	if ! validate_seahub_running && [[ -f "${pidfile}" ]]; then
		echo
		echo "Seahub is started"
		echo
	else
		printf "\033[33mError: Seahub failed to start.\033[m\n"
		exit 1
	fi
}

function prepare_env() {
	check_python_executable
	validate_ccnet_conf_dir
	read_seafile_data_dir

	export CCNET_CONF_DIR=${default_ccnet_conf_dir}
	export SEAFILE_CONF_DIR=${seafile_data_dir}
	export SEAFILE_CENTRAL_CONF_DIR=${central_config_dir}
	export PYTHONPATH="${INSTALLPATH}/seahub:${INSTALLPATH}/seahub/thirdpart:${PYTHONPATH}"
}

function clear_sessions() {
	prepare_env

	echo "Start clear expired session records ..."
	$PYTHON "${manage_py}" clearsessions

	echo
	echo "Done"
	echo
}

function stop_seahub() {
	if [[ -f ${pidfile} ]]; then
		pid=$(cat "${pidfile}")
		echo "Stopping seahub ..."
		kill ${pid}
		rm -f ${pidfile}
		retry=1
		while ! validate_seahub_running && [ $retry -lt 60 ]; do sleep 1; ((retry++)); done
		if ! validate_seahub_running; then
			echo "Error: seahub cannot be stopped. Please try stopping it manually by running \"kill $(echo "$pid" | tr '\n' ' ')\"."
			echo "To force killing the processes, use \"kill -9 $(echo "$pid" | tr '\n' ' ')\"."
		fi
	else
		echo "Seahub is not running"
	fi
}

function check_init_admin() {
	check_init_admin_script=${INSTALLPATH}/check_init_admin.py
	if ! $PYTHON $check_init_admin_script; then
		exit 1
	fi
}

function start() {
	if [ "$SEAHUB_FASTCGI" == "1" ]; then
		start_seahub_fastcgi
	else
		start_seahub
	fi
}

function stop() {
	stop_seahub
}

function restart() {
	stop
	start
}

function clearsessions() {
	clear_sessions
}