#!/bin/sh
set -e

ALTDIR="/etc/alternatives"

update-alternatives --root "$CRUFT_ROOT" --get-selections | while read -r alternative _y current
do
    case "$current" in
        /usr/share/desktop-base/active-theme*)
            # we are not recursive
            theme=$(realpath /usr/share/desktop-base/active-theme)
            echo "@$theme"
            ;;
        /usr/bin/fpc|/etc/fpc-*.cfg)
            # we are not recursive
            fpc=$(realpath /usr/bin/fpc)
            echo "@$fpc"
            ;;
        /bin/*|/sbin/*|/lib/*)
            # this namespace was not fully UsrMerge'd
            echo "@/usr${current}"
            ;;
        *)
            echo "@$current"
            ;;
    esac
    update-alternatives --root "$CRUFT_ROOT" --query "$alternative" 2>/dev/null | while read -r line
    do
        case "$line" in
            Name:*|Slaves:*|Status:*|Best:*)
                ;;
            Link:*)
                link="${line#* }"
                ;;
            Value:*)
                test -e "${line#* }" && printf "%s\n%s\n" "$ALTDIR/$alternative" "$link" || true
                ;;
            '')
                break
                ;;
            *)
                alt="$ALTDIR/${line% *}"
                test -e "$alt" && echo "$alt" || true

                target="${line#* }"
                test -e "$target" && echo "$target" || true
                ;;
        esac
    done
done

exit 0
