#!/usr/bin/env bash
# aufs-list
# Author: lcpterid, 2026
# License: GPL v3

prog_name="$(basename "$0")"
help_text="Syntax: $prog_name path_to_check

Checks for multiple versions of a path in different AUFS branches.
If path_to_check is '/' then list all branches and their
source root directories.
"

script_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &>/dev/null && pwd )"
lib_path="$(realpath -m "${script_dir}/../lib/libaufs-dir-tools")"
if ! [ -x "$lib_path" ]; then
       echo "Couldn't find library file!" >&2
       exit 1
fi
. "$lib_path"

[ "$#" -ne 1 ] && error_quit 1 ""

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	show_help
	exit 0
fi

mount_check || error_quit 2 "AUFS mounts do not match requirements. This tool requires one AUFS branch system, mounted on root (/) and optionally sub-mounted elsewhere."
branch_files_check || error_quit 2 "could not find AUFS branch files in /sys/fs/. Are you on an AUFS file system?"

path_to_check=$(realpath -m -s "$1" | aufs_real_path)
parent_dir=$(dirname "$path_to_check")
file_to_check=$(basename "$path_to_check")

branch_list="$(find /sys/fs/aufs/si*/ -name 'br[[:digit:]]*' 2>/dev/null)"
branch_list_sorted="$(echo "$branch_list" | 
	while read -r brf; do printf "%d\t%s\n" "${brf##*br}" "$brf"; done |
		sort -n |
		cut -f 2)"

all_image_folders="$(echo "$branch_list_sorted" | xargs cat | sed 's/=..\(+[a-z_]*\)\?$//')"

aufs_folder_check "$path_to_check" || error_quit 3 "Path $path_to_check (or its parent directory) is not in the AUFS filesystem"

file_exists="no"
while read -r imf; do
	[ -e "${imf}${path_to_check}" ] && file_exists="yes"
done < <(echo "$all_image_folders")

[ "$file_exists" = "no" ] && error_quit 2 "could not find path $1 in any branch"

while read -r brf; do
	br_num="${brf##*br}"
		# e.g. /sys/fs/aufs/si_90b4d2ac53cb2be0/br5
	br_raw="$(cat "$brf")"
		# e.g. /mnt/live/memory/images/firefox-147.0.1-x86_64-en-US.xzm=rr
	br_read_mode="$(echo "$br_raw" | rev | cut -d '=' -f 1 | rev)"
		# e.g. rr
	br_root="$(echo "$br_raw" | sed 's/=[^=]*$//')"
		# e.g. /mnt/live/memory/images/firefox-147.0.1-x86_64-en-US.xzm
	br_name=$(basename "$br_root")
		# e.g. firefox-147.0.1-x86_64-en-US.xzm
	br_fullpath="${br_root}${path_to_check}"
	br_whiteout_path="${br_root}${parent_dir}/.wh.${file_to_check}"

	if [ -e "$br_fullpath" ] || [ -h "$br_fullpath" ]; then
		printf "%3d\t%s\t%s\t%s\n" "$br_num" "$br_name" "$br_fullpath" "$br_read_mode"
	elif [ -e "$br_whiteout_path" ]; then
		printf "%3d\t%s\t%s\t%s\n" "$br_num" "$br_name" "[WHITEOUT]" "$br_read_mode"
	fi

done < <(echo "$branch_list_sorted")

