#!/usr/bin/env bash

# Arguments
ACTION="$1"
SUBVOLUME="$2"
#FS_TYPE="$3" # Optional: Btrfs or bcachefs
SNAP_ID="$4"

# Command to run sync
SYNC_CMD=(limine-snapper-sync --no-force-save)

# Only act on the root subvolume
[[ "$SUBVOLUME" != "/" ]] && exit 0

# Snapshot ID is mandatory
if [ -z "$SNAP_ID" ]; then
	echo "Error: Snapshot ID not set" >&2
	exit 1
fi

# Function to run limine-snapper-sync
function run_sync() {
	local op="$1" # add / delete / modify

	if [[ "$op" != "modify" ]]; then
		# Skip if service is running
		if command -v systemctl &>/dev/null && systemctl is-active --quiet limine-snapper-sync.service; then
			#echo "Sync skipped: limine-snapper-sync.service is already running."
			return 0
		fi

		# For non-systemd distro: skip if watcher is running
		if command -v pgrep &>/dev/null && pgrep -f "limine-snapper-watcher" &>/dev/null; then
			#echo "Sync skipped: limine-snapper-watcher is already running."
			return 0
		fi
	fi

	# Run sync depending on environment
	if command -v systemd-run &>/dev/null; then
		# Run inside a transient systemd unit
		systemd-run \
			--unit="limine-snapper-${op}-${SNAP_ID}" \
			--description="Run limine-snapper-sync for $op $SNAP_ID" \
			--quiet --collect \
			"${SYNC_CMD[@]}"
	elif command -v setsid &>/dev/null; then
		# run detached from shell/session
		setsid "${SYNC_CMD[@]}" &>/dev/null &
	else
		# Fallback
		"${SYNC_CMD[@]}" &>/dev/null &
	fi
}

case "$ACTION" in
create-snapshot-post)
	run_sync add
	;;
delete-snapshot-post)
	run_sync delete
	;;
modify-snapshot-post)
	run_sync modify
	;;
*)
	# Ignore any unknown action
	exit 0
	;;
esac
