#!/bin/bash
#
# Copyright (c) 2008 by Jose V Beneyto, sepen at users dot sourceforge dot net
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

msgUsage() {
  echo "Usage: $APPNAME [options] <path1> [<path2> ...]"
  echo "Where options are:"
  echo "  -h        Show this help information"
  echo "  -wl file  Use whitelist file"
  echo "Read $APPNAME(1) for more info"
  exit 0
}

msgError() {
  echo "Error, $*" 2>&1
  exit 1
}

findPathNot() {
  if [ -e "$WLFILE" ] || [ -L "$WLFILE" ]; then 
    FILTER="| grep -v -F -f '$WLFILE'"
  fi
  eval comm -23 <(find "$@" | sed 's|^/||' | sort -u) \
    <(awk -v FS='\n' -v RS='' '{ for (i=2;i<=NF;++i) {print $i} }' $PKGDB \
    | sed 's|/$||' | sort -u) $FILTER
}

main() {
  declare -a tree_roots
  while [ "$1" ]; do
      case "$1" in
        -wl) 
           shift
	   [ -f "$1" -a -r "$1" ] || msgError "can't read whitelist file '$1'"
           WLFILE="$1"
           ;;
        -*)
           msgUsage
           ;;
         *)
           [ -d "$1" ] || msgError "can't open directory '$1'"
           tree_roots+=("$(cd "$1" || exit; pwd)")
           ;;
      esac
      shift
  done
  [ "${#tree_roots[@]}" -gt 0 ] || msgUsage
  findPathNot "${tree_roots[@]}"
} 

APPNAME="$(basename "$0")"
PKGDB="/var/lib/pkg/db"
WLFILE=""
FILTER=""

[ -r "$PKGDB" ] || msgError "can't open pkg database '$PKGDB'"

main "$@"

# End of File
