+# Delete any subvols on the receiving host that don't exist on the
+# sending host. Otherwise, the receiving host could have snapshots that
+# aren't on the sending side, and thus become odd leaf subvols, and then
+# btrbk could try to use them when we sync back, creating a weird tree
+# instead of linear parent/child relationship. Maybe this could lead to
+# a missing source subvol error, so lets avoid it.
+
+get-orphan-tg-snaps() {
+ orphan_tg_snaps=()
+ for (( i=0; i < ${#mountpoints[@]}; i++ )); do
+ orphan_start_count=${#orphan_tg_snaps[@]}
+ tg_snap_count=0
+ for tg_snap in ${tg_snaps[$i]}; do
+ tg_snap_count=$(( tg_snap_count + 1 ))
+ if [[ ! ${source_snaps[$tg_snap]} ]]; then
+ orphan_tg_snaps+=("$tg_snap")
+ fi
+ done
+ orphan_mp_count=$(( ${#orphan_tg_snaps[@]} - orphan_start_count ))
+ # sanity checking
+ tmp=$(( tg_snap_count > 1 && tg_snap_count == orphan_mp_count ))
+ if (( tmp )) ; then
+ die "something went wrong checking orphans on $tg: for mountpoint ${mountpoints[$i]}, $orphan_mp_count"
+ fi
+ done
+}
+
+if [[ $source ]]; then
+ for snap in $(ssh root@$source "shopt -s nullglob; ${snap_list_cmds[*]}"); do
+ source_snaps[$snap]=t
+ done
+ get-orphan-tg-snaps
+ tmp=$(( ${#orphan_tg_snaps[*]} >= 1 ))
+ if (( tmp )); then
+ d btrfs sub del ${orphan_tg_snaps[*]}
+ fi
+else # we have targets
+ for tg in ${targets[@]}; do
+ tmp_str=$(ssh root@$tg "shopt -s nullglob; ${snap_list_cmds[*]}")
+ mapfile -t tg_snaps <<<"$tmp_str"
+ get-orphan-tg-snaps
+ tmp=$(( ${#orphan_tg_snaps[*]} >= 1 ))
+ if (( tmp )); then
+ d ssh root@$tg "btrfs sub del ${orphan_tg_snaps[*]}"
+ fi
+ done
+fi
+