#!/bin/sh

LOCKFILE=/tmp/$(basename $0).lock

usage() {
	echo "This script is for monitoring AD client 'winbindd'."
	echo "It can be called:"
	echo " - from wbwait service with 2 arguments (username, number of attempts);"
	echo " - from crontab without any argument;"
	echo " - from crontab with --force argument;"
	echo " - from command line with --force or --help arguments."
	echo "The logic is:"
	echo "    check AD client && exit 0"
	echo "    wbwait running -or --force && hard-restart AD client without touching dependenties"
	echo "    check AD client"
}

. /opt/etc/functions.openrc

FORCE=""

load_wbwait_rc_config() {
	# Source config of 'wbwait' service
	[ -r /etc/conf.d/wbwait ] || return 1
	. /etc/conf.d/wbwait
	_du=${DOMAIN_USER}
	_timeout=5
	. /opt/etc/functions.noopenrc
}

case $# in
	0)
		load_wbwait_rc_config
		;;
	1)
		if [ "$1" == "--force" ]; then
			FORCE="Y"
		else
			usage
			exit 0
		fi
		load_wbwait_rc_config
		;;
	2)
		_du=$1
		_timeout=$2
		;;
	*)
		usage
		exit 0
		;;	
esac

rc-service wbwait status > /dev/null 2>&1
_wbwait_status=$?
rc-service winbindd status > /dev/null 2>&1
_winbindd_status=$?

# Assume no winbindd-dependent service are running if wbwait is
# stopped; thus, we just report failure if both winbindd and wbwait
# are stopped. This path will be also chosen if we are called
# from wbwait itself.

[ ${_winbindd_status} -eq 3 -a ${_wbwait_status} -eq 3 -a -z "${FORCE}" ] && exit 3

enter_lock ${LOCKFILE} || exit 1

# Fast path: if AD client is operational, exit 0
wait_for_user ${_du} ${_timeout} && unlock_exit ${LOCKFILE} 0

# Cleanup, but don't touch dependencies
update_me
echo "${ME}: recovering AD from status: wbwait ${_wbwait_status}, winbindd ${_winbindd_status}."

killem winbindd
rc-service winbindd zap
service winbindd start
wait_for_user ${_du} ${_timeout}
unlock_exit ${LOCKFILE} $?
