#!/usr/bin/bash

DOCKER="/usr/bin/docker"
LOGGER="/usr/bin/logger"
SYSTEMCTL="/usr/bin/systemctl"
TIMEOUT=$((10*60)) # 10 min, thus backend inside use 1 hour timeout
TIMEOUT_MULT=4 # Looks like 25% is enough

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

function stop_containers() {
	local cts ct_list ct_list_debug timeout ct_id
	cts=0
	timeout=$1
	declare -A pids_cts

	if [ -z "${CT_NAME}" ]; then
		# VSTOR-27415
		ct_list_debug=`$DOCKER container ls -a --format '{{.ID}}:{{.Names}}:{{.Status}}' 2>/dev/null`
		if [ $? -ne 0 ]; then
			log "Failed to get docker containers list"
			return 1
		fi
		log "Container list: ${ct_list_debug}"

		# list command may timeout too
		ct_list=`$DOCKER container ls -q 2>/dev/null`
		if [ $? -ne 0 ]; then
			log "Failed to get docker containers list"
			return 1
		fi
	else
		ct_id=`$DOCKER container  ls -q -f name=${CT_NAME}`
		if [ $? -ne 0 ]; then
			log "Failed to get ${CT_NAME} container ID"
			return 1
		fi
		ct_list=${ct_id}
	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 pid $!"
		pids_cts[$!]="$ct"
		cts=$((cts+1))
	done

	# Wait for docker container stop processes
	while [ $timeout -ne 0 ]; do
		[ ${#pids_cts[@]} -eq 0 ] && break
		sleep 1
		timeout=$((timeout -1))
		for pid in "${!pids_cts[@]}"; do
			[ -d /proc/$pid ] && continue
			wait $pid > /dev/null 2>&1
			log "$DOCKER container stop ${pids_cts[$pid]} pid $pid finished"
			unset pids_cts[$pid]
		done
	done

	for pid in "${!pids_cts[@]}"; do
		log "Remaining container ${pids_cts[$pid]} $DOCKER container stop pid $pid still running"
	done

	return $cts
}

function get_clock_monotonic() {
	cat /proc/uptime 2>/dev/null | sed "s,\..*,,g"
}

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

START=`get_clock_monotonic`
END=$((START+TIMEOUT))
while [ 1 -eq 1 ]; do
	# Check that dockerd runned
	$DOCKER ps > /dev/null 2>&1
	[ $? -ne 0 ] && break
	# On huge HN load docker-containerd daemon can lock, so will stop until we success
	stop_containers $((TIMEOUT/TIMEOUT_MULT))
	[ $? -eq 0 ] && log "All docker container(s) stopped" && break
	# Or timeout reached
	[ `get_clock_monotonic` -lt $END ] && continue
	log "Timeout $TIMEOUT sec to stop docker containers"
	break
done

if [ -z "${CT_NAME}" ]; then
	/usr/bin/vcmmdctl deactivate vstorage.slice/vstorage-compute.slice/vstorage-compute-storage.slice || :
	/usr/bin/vcmmdctl deactivate vstorage.slice/vstorage-compute.slice || :
	/usr/bin/vcmmdctl unregister vstorage.slice/vstorage-compute.slice || :
	/usr/bin/vcmmdctl unregister vstorage.slice/vstorage-compute.slice/vstorage-compute-storage.slice || :
fi

exit 0
