#!/bin/bash

DOCKER="/usr/bin/docker"
LOGGER="/usr/bin/logger"
SYSTEMCTL="/usr/bin/systemctl"

function log() {
	if [ ! -x $LOGGER ]; then
		echo $*
	fi
	$LOGGER "$0: $*"
}

function stop_containers() {
	local cts ct_list
	cts=0

	# list command may timeout too
	ct_list=`$DOCKER container list -q 2>/dev/null`
	if [ $? -ne 0 ]; then
		log "Failed to get docker containers list"
		return 1
	fi

	for ct in $ct_list; do
		$DOCKER container stop $ct >/dev/null 2>&1 &
		[ $? -ne 0 ] && log "Failed to stop docker container $ct" || log "Stopping docker container $ct"
		cts=$((cts+1))
	done

	# Wait for docker container stop processes
	wait

	return $cts
}

if [ ! -x $DOCKER -o ! -x $SYSTEMCTL ]; then
	log "Some binaries not found, nothing to do."
	exit 0
fi

$SYSTEMCTL -q --no-legend list-jobs 2>/dev/null | grep -E '(shutdown|reboot).target' >/dev/null

if [ $? -ne 0 -a -z "$DOCKER_CONTAINERS_STOP_FORCE" ]; then
	log "Not on reboot or shutdown state, nothing to do."
	exit 0
fi

while [ 1 -eq 1 ]; do
	# On huge HN load docker-containerd daemon can lock, so will stop until we success
	stop_containers
	[ $? -eq 0 ] && break
done

log "All docker container stopped"
/usr/bin/vcmmdctl deactivate vstorage.slice/vstorage-compute.slice/vstorage-compute-storage.slice || :
/usr/bin/vcmmdctl deactivate vstorage.slice/vstorage-compute.slice || :

exit 0
