#!/usr/bin/bash

usage() {
    local msg=$1
    {
        echo "usage: $Self [-p DENY_PATH].. [-r DENY_PACKAGE].. BUILD_ROOT"
        echo ""
        echo "Will generate RPM %files listiong from sandbox-installed tree"
        echo "under BUILD_ROOT, removing any paths that belong to 'filesystem'"
        echo "package."
        echo ""
        echo "To extend the denial list, use -p to specify extra absolute"
        echo "paths."
        echo ""
        echo "To extend own list of packages to exclude paths from, use -r."
        echo "Packages specified this way musty be installed."
    } >&2
    test -n "$msg" || return
    echo >&2 ""
    warn "$msg"
    exit 2
}

warn() {
    echo >&2 "$Self: $1"
}

die() {
    echo >&2 "$Self:fatal: $1"
    exit 3
}

deny_list() {
    #
    # Produce list of abs paths which may never be owned
    #
    local deny_path
    local deny_package
    for deny_package in "${DenyPackages[@]}"; do
        rpm -ql "$deny_package" || warn "failed to list '$deny_package' package contents"
    done
    for deny_path in "${DenyPaths[@]}"; do
        echo "$deny_path"
    done
}

main() {
    local Self=${0##*/}
    local build_root
    local DenyPaths=();
    local DenyPackages=(filesystem);
    command -v rpm >/dev/null || die "rpm not present; is this a rpm-based system?"
    while true; do case "$1" in
        -p) DenyPaths+=("$2"); shift 2      || usage "missing DENY_PATH after -p" ;;
        -r) DenyPackages+=("$2"); shift 2   || usage "missing DENY_PACKAGE after -r" ;;
        --) shift 1; break ;;
        -*) usage "unknown argument: $1" ;;
        *) break ;;
    esac done
    build_root=$1; shift
    test -n "$1"          && usage "too many arguments"
    test -n "$build_root" || usage "no BUILD_ROOT?"
    test -d "$build_root" || die "no such directory: $build_root"
    deny_list > "$Self.deny.list"
    find "$build_root" -type d -printf '/%P\n' \
      | grep -vxF -f "$Self.deny.list" \
      | sed 's:^:%dir :' \
      | sort
    find "$build_root" -type f -printf '/%P\n' \
      | grep -vxF -f "$Self.deny.list" \
      | sort
}

main "$@"
