#!/bin/sh
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: oneshot; invoke with: sv once vdev-settle-sync.sh-stop
#Comment: stop companion for vdev-settle-sync.sh

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return "$r"; }

: "${VDEV_STATE_DIR:=/run/vdev}"
_json="${VDEV_GLOBALS_JSON:-/etc/vdev/vdevd.globals.json}"
if [ -r "${_json}" ] && command -v jq >/dev/null 2>&1; then
	VDEV_JSON_DATA="$(sed -E 's|//.*||g' "${_json}" |
		sed 's|/\*.*\*/||g' |
		grep -v '^$' |
		jq -r .)"
	_state_dir="$(printf '%s' "${VDEV_JSON_DATA}" | jq -r '.globals["states-stamp-dir"] // .globals["stamp_dir"] // empty' 2>/dev/null)"
	VDEV_STATE_DIR="${_state_dir:-/run/vdev}"
fi

ebegin "Stopping vdev settle helper"
if [ -f "${VDEV_STATE_DIR}/vdev-settle.pid" ]; then
	read -r _vs_pid < "${VDEV_STATE_DIR}/vdev-settle.pid" 2>/dev/null || _vs_pid=""
	[ -n "${_vs_pid}" ] && kill -TERM "${_vs_pid}" 2>/dev/null || true
	rm -f "${VDEV_STATE_DIR}/vdev-settle.pid"
fi
eend 0
exit 0
