#!/usr/sbin/openrc-run

description="fast remote file copy program daemon"

command="/usr/bin/rsync"
pidfile="/var/run/rsync.pid"
RSYNC_CONFIG_FILE=/etc/rsyncd.conf
RSYNC_ENABLE=false
RSYNC_OPTS=''
RSYNC_NICE_PARM=''
RSYNC_IONICE_PARM=''

extra_started_commands="reload"

depend() {
	use logger net
	after rsyslog
}

load_defaults() {
	RSYNC_ENABLE=false
	RSYNC_OPTS=''
	RSYNC_NICE_PARM=''
	RSYNC_IONICE_PARM=''

	if [ -s /etc/default/rsync ]; then
		. /etc/default/rsync
		case "x${RSYNC_ENABLE}" in
		xtrue|xfalse) ;;
		xinetd) return 2 ;;
		*)
			ewarn "Value of RSYNC_ENABLE in /etc/default/rsync must be 'true' or 'false'"
			return 1
			;;
		esac
		case "x${RSYNC_NICE:-}" in
		x[0-9]|x1[0-9]) RSYNC_NICE_PARM="-N ${RSYNC_NICE}" ;;
		x) ;;
		*)
			ewarn "Value of RSYNC_NICE in /etc/default/rsync must be between 0 and 19"
			;;
		esac
		case "x${RSYNC_IONICE:-}" in
		x-c[123]*) RSYNC_IONICE_PARM="${RSYNC_IONICE}" ;;
		x) ;;
		*)
			ewarn "Value of RSYNC_IONICE in /etc/default/rsync must be -c1, -c2 or -c3"
			;;
		esac
	fi
	return 0
}

rsync_should_start() {
	load_defaults
	case $? in
	2) return 2 ;;
	1) return 1 ;;
	esac
	[ "$RSYNC_ENABLE" = true ]
    return 0
}

start() {
	rsync_should_start
	case $? in
	2) return 0 ;;
	1) return 1 ;;
	0) ;;
	*) return 1 ;;
	esac

	[ -x "$command" ] || return 1

	if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
		ewarn "missing or empty config file ${RSYNC_CONFIG_FILE}"
		return 0
	fi

	if [ -s "$pidfile" ] && start-stop-daemon -K -t -p "$pidfile" >/dev/null 2>&1; then
		einfo "rsync daemon apparently already running"
		return 0
	fi

	ebegin "Starting rsync daemon"
	start-stop-daemon -S ${RSYNC_NICE_PARM} -p "$pidfile" \
		-x "$command" -- --daemon --config "${RSYNC_CONFIG_FILE}" ${RSYNC_OPTS}
	eend $?
}

stop() {
	ebegin "Stopping rsync daemon"
	start-stop-daemon -K -p "$pidfile"
	local rc=$?
	[ "$rc" -ne 0 ] && rm -f "$pidfile"
	eend "$rc"
}

reload() {
	ewarn "Reloading rsync daemon: not needed; config is re-read on client connect"
}
