+ done
+ if [[ ! $root_dir ]]; then
+ echo "$0: error could not find root subvol mount for $dev" >&2
+ exit 1
+ fi
+ svp=$root_dir/$subvol_dir # subvolume path
+ d "svp=$svp # subvolume path"
+
+ snaps=($root_dir/btrbk/$subvol_dir.20*) # Assumes we are in the 21st century.
+ if [[ ! ${snaps[*]} ]]; then
+ # no snapshots yet
+ # TODO: make this an error and override with a cli flag
+ echo "$0: warning: no snapshots found at $root_dir/btrbk/$subvol_dir.20*. this is expected for a brand new volume"
+ continue
+ fi
+
+ # get info on last received sub
+ last_received=
+ last_received_cgen=0
+ for f in ${snaps[@]}; do
+ show="$(btrfs sub show $f)"
+ if echo "$show" | grep -E "Received UUID:\s+[[:alnum:]]" &>/dev/null; then
+ d found received uuid in $f
+ cgen=$(echo "$show" | sed -rn 's,^\s*Gen at creation:\s+([0-9]+).*,\1,p')
+ if [[ $cgen -gt $last_received_cgen ]]; then
+ last_received_cgen=$cgen
+ last_received=$f
+ fi
+ fi
+ done
+ d last_received_cgen=$last_received_cgen
+ d last_received=$last_received
+
+ # Get last_snap by date.
+ # when a btrbk bugfix makes it into the distro,
+ # we might replace this with btrbk list latest /mnt/root/$vol | ...
+ last_snap=$(
+ for s in ${snaps[@]}; do
+ f=${s##*/}
+ unix_time=$(date -d $(sed -r 's/(.{4})(..)(.{5})(..)(.*)/\1-\2-\3:\4:\5/' <<<${f#$vol.}) +%s)
+ printf "%s %s\n" $unix_time $s
+ # sort will fail
+ done | sort -r | head -n 1 | awk '{print $2}' || [[ ${PIPESTATUS[1]} == 2 ]]
+ )
+ if [[ ! $last_snap ]]; then
+ # should not happen.
+ echo "$0: error: could not find latest snapshot for $svp among ${snaps[*]}" >&2
+ exit 1
+ fi
+ d last_snap=$last_snap
+
+ if [[ ! -e $svp ]]; then
+ echo "$0: warning: subvol does not exist: $svp"
+ echo "$0 assuming this host was just for receiving and latest snap is freshest"