#!/bin/bash
### dpkg-usels.sh  -*- Sh -*-
## List files belonging to Debian packages, and the processes using them.

### 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:47Z
##      Now a separate program (was: a function in .bash.func.)

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

### Commentary:

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

##  This program relies on dpkg-qls(1); refer to the documentation for
##  the latter for the details.

### 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

## NB: using Bash-specific <(command...) construct
## .
LC_ALL=C join -22 -- \
    <(LC_ALL=C gawk  'BEGINFILE {
                          if (ERRNO != "") { nextfile; }
                          pid =  gensub(/.*\<([0-9]+)\>.*/, \
                                        "\\1", 1, FILENAME)
                      }
                      ! seen_p[pid, k = $6] && k ~ /^\// {
                          pids[k] = pids[k] " " pid; seen_p[pid, k] = 1;
                      }
                      END {
                          PROCINFO["sorted_in"] = "@ind_str_asc";
                          for (k in pids) { print k "\t" pids[k]; }
                      }'  /proc/*[0-9]/maps) \
    <(dpkg-qls  "$@" | LC_ALL=C sort -sk2)

### dpkg-usels.sh ends here
