#!/bin/sh

die_show_usage() {
	echo "Usage: $0 {start|stop}"
	exit 1
}

stratisd_running() {
	pidof stratisd >/dev/null 2>&1
}

start() {
	if stratisd_running ; then
		echo "Stratisd is already running"
		return 0
	fi
	echo "Starting stratisd"
	/bin/stratisd --debug >/tmp/stratisd.log 2>&1 &	
	return 0
}

stop_service() {
        if ! stratisd_running ; then
                echo "Stratisd is not running"
                return 0
        fi

	echo "Stoping stratisd"
	killall stratisd
	local kill9=0
	for i in `seq 1 50`; do
		if stratisd_running >/dev/null 2>&1; then
			kill9=1
			echo -n '.'
			sleep 1
		else
			kill9=0
			echo "Stopped"
			break
		fi
	done
	if [ $kill9 -ne 0 ] ; then
		killall -KILL stratisd
		echo "Forcibly killed"
	fi
}

get_stratis_devs() {
	dmsetup ls -o blkdevname --exec echo | grep stratis-1 2>/dev/null
}

has_stratis_devs() {
	local devs="`get_stratis_devs`"
	test -n "$devs"
}

deactivate_pools() {
	local stratis_devs="`get_stratis_devs`"
	if [ -z "$stratis_devs" ] ; then
		echo "No active stratis pools found"
		return 0
	fi
	echo "Deactivating stratis pools"
	dmsetup remove --deferred $stratis_devs
	for i in `seq 1 10`; do
		if has_stratis_devs >/dev/null 2>&1 ; then
			echo -n '.'
			sleep 1
		else
			echo "Deactivated"
			break
		fi
	done
	echo "Waiting for udev to settle"
	udevadm settle
	echo "Done"
}

stop() {
	stop_service
	deactivate_pools
}

test "$#" -eq 1 || die_show_usage
case "$1" in 
	start) start ;;
	stop)  stop  ;;
	*)     die_show_usage ;;
esac

