#!/usr/sbin/openrc-run
#
# Start the MD monitor daemon for all active MD arrays if desired.
#
# Copyright © 2001-2005 Mario Joußen <joussen@debian.org>
# Copyright © 2005-2009 Martin F. Krafft <madduck@debian.org>
# Distributable under the terms of the GNU GPL version 2.
#

description="MD monitoring daemon"

command="/sbin/mdadm"
pidfile="/run/mdadm/monitor.pid"
command_args="--monitor --pid-file ${pidfile} --daemonise --scan"

MDMON="/sbin/mdmon"
RUNDIR="/run/mdadm"
DEBIANCONFIG="/etc/default/mdadm"

depend() {
	need localmount
	use logger
	after bootmisc
}

is_true() {
	case "${1:-}" in
		[Yy]es|[Yy]|1|[Tt]|[Tt]rue) return 0 ;;
		*) return 1 ;;
	esac
}

start() {
	[ -x "$command" ] || return 0
	[ -f /proc/mdstat ] || return 0

	if command -v systemd-detect-virt >/dev/null 2>&1 \
		&& systemd-detect-virt --quiet --container; then
		ewarn "Not starting MD monitoring service in container"
		return 0
	fi

	START_DAEMON=true
	DAEMON_OPTIONS=
	[ -f "$DEBIANCONFIG" ] && . "$DEBIANCONFIG"

	if is_true "$START_DAEMON"; then
		checkpath -d -m 0755 "$RUNDIR"
		ebegin "Starting MD monitoring service"
		start-stop-daemon -S -p "$pidfile" -x "$command" -- \
			--monitor --pid-file "$pidfile" --daemonise --scan ${DAEMON_OPTIONS}
		eend $?
	fi

	# Take over external metadata monitors started from initramfs, if any.
	if [ "$(echo "$RUNDIR"/md[0-9]*.pid)" != "$RUNDIR/md[0-9]*.pid" ]; then
		ebegin "Restarting MD external metadata monitor"
		"$MDMON" --takeover --all
		eend $?
	fi
}

stop() {
	if [ -f "$pidfile" ]; then
		ebegin "Stopping MD monitoring service"
		start-stop-daemon -K -p "$pidfile" -x "$command"
		rm -f "$pidfile"
		eend $?
	fi

	# Keep mdmon processes alive across sendsigs during shutdown.
	for file in "$RUNDIR"/md[0-9]*.pid; do
		[ -f "$file" ] || continue
		ln -sf "$file" "/run/sendsigs.omit.d/mdmon-${file##*/}"
	done
}
