#!/bin/bash
# Copyright © 2019-2026 Collabora Ltd.
# SPDX-License-Identifier: MIT

# Assert that the contents of the filesystem are such that it could
# easily be /usr-merged later.

set -eu -o pipefail

tmpdir="$(mktemp -d)"
cleanup () {
    rm -fr "$tmpdir"
}
trap cleanup 0 INT QUIT ABRT PIPE TERM

find /bin /sbin /lib* > "$tmpdir/rootfs.list"

i=0
failed=
IFS='
'

for path in $(< "$tmpdir/rootfs.list"); do
    i=$(( i+1 ))
    echo "# $path"
    ( ls -dl "$path" 2>&1 || true ) | sed -e 's/^/# /'
    ( ls -dl "/usr$path" 2>&1 || true ) | sed -e 's/^/# /'

    if ! [ -e "/usr$path" ] && ! [ -L "/usr$path" ]; then
        echo "ok $i - $path exists only in the root, not in /usr"
        continue
    fi

    if [ -d "$path" ] && [ -d "/usr$path" ]; then
        echo "ok $i - $path and /usr/$path are directories"
        continue
    fi

    if ! [ "$path" -ef "/usr$path" ]; then
        echo "not ok $i - $path and /usr$path are not the same file"
        failed=yes
        continue
    fi

    if [ -L "$path" ]; then
        case "$(readlink "$path")" in
            ("/usr$path")       # e.g. /bin -> /usr/bin
                echo "ok $i - $path is a Policy 10.5 symlink to /usr$path"
                continue
                ;;

            ("usr$path")        # e.g. /bin -> usr/bin
                echo "ok $i - $path is a non-Policy symlink to usr$path"
                continue
                ;;
        esac
    fi

    if [ -L "/usr$path" ]; then
        case "$(readlink "/usr$path")" in
            ("$path")           # e.g. /usr/bin -> /bin
                echo "ok $i - $path is a Policy 10.5 symlink to $path"
                continue
                ;;

            ("..$path")         # e.g. /usr/bin -> ../bin
                echo "ok $i - $path is a non-Policy symlink to ..$path"
                continue
                ;;
        esac
    fi

    echo "not ok $i - $path and /usr$path are not as expected"
    failed=yes
done

echo "1..$i"

if [ -n "$failed" ]; then
    exit 1
fi

# vim:set sw=4 sts=4 et ft=sh:
