#!/bin/bash
### dpkg-qls.sh  -*- Sh -*-
## List files belonging to Debian packages, similar to $ dpkg -L.

### Ivan Shmakov, 2019

## To the extent possible under law, the author(s) have dedicated
## all copyright and related and neighboring rights to this software
## to the public domain worldwide.  This software is distributed
## without any warranty.

## You should have received a copy of the CC0 Public Domain Dedication
## along with this software.  If not, see
## <http://creativecommons.org/publicdomain/zero/1.0/>.

### History:

## 0.2  2019-09-15 18:35Z
##      Now a separate program (was: a function in .bash.func.)
##      Print package name before file name (was: vice versa.)
##      If ambiguous, try package that matches the dpkg(1) native
##      architecture (as per --print-architecture) first.

## 0.1  2019-09-14 21:37:19Z
##      (sfn.c7oWKXP38sf68oLSA-eUFQllTbbHHPm_56nEbl3cqC4.sh)
##      Initial revision.

### Commentary:

##  Example:
##    # dpkg-qls  libbz2-1.0 libtinfo6:amd64 | less 

### Code:

set -e
set -C -u

if ! test "$#" -ge 1 ; then
    printf %s\\n \
        "Usage: ${SHELL##*/} ${0##*/}  FILE.LIST|PACKAGE|PKG:BINARCH..." >&2
    ## .
    exit 1
fi

declare -a -- a=dummy
# arch d f1 f
arch=$(dpkg --print-architecture || : FAIL\?)
d=${DPKG_ADMINDIR:-/var/lib/dpkg}/info
for f1 ; do
    case "$f1" in
        (/*)    f=${f1} ;;
        (*:*)   f=${d}/${f1}.list ;;
        (*)     for f in "${d}/${f1}".list \
                        "${d}/${f1}:${arch}".list "${d}/${f1}":*.list ; do
                    test -e "$f" && break
                done ;;
    esac
    a[${#a[@]}]=${f}
done

set -- "${a[@]}"
shift
## .
gawk 'BEGINFILE { pkg = gensub(/.*\//, "", 1, FILENAME); }
      ! seen_p[$0] {
          print pkg "\t" $0;
          seen_p[$0] = 1;
      }'  "$@"

### dpkg-qls.sh ends here
