#! /bin/sh

# tracks file descriptors given SELinux enhanced strace output

prefix=/usr
exec_prefix=${prefix}
bindir=${exec_prefix}/bin

PROG=`basename "$0"`

usage()
{
  echo "Usage: $PROG [OPTIONS] [INPUT-FILE]"
  echo
  echo "Options:"
  echo "  -o FILE, --output=FILE"
  echo "         send output to FILE instead of stdout"
  echo "  -h, --help"
  echo "         display this help and exit"
  echo "  -v, --version"
  echo "         output version information and exit"
}

OPTS=`getopt -o hvo: --long help,version,output: -n "$PROG" -- "$@"`

if [ $? -ne 0 ]
then
  echo
  usage
  exit 1
fi

eval set -- "$OPTS"

for o
do
  case "$o" in
    -h|--help)
      usage
      exit 0;;
    -v|--version)
      echo polgen 1.3
      exit 0;;
    -o|--output)
      option=-o
      output="$2"
      shift 2;;
    --)
      shift
      break;;
  esac
done

if [ $# -gt 1 ]
then
  echo Too many arguments
  echo
  usage
  exit 1
fi

# this AWK script handles unfinished system calls
mawk '
  { if (sub(/ <unfinished \.\.\.>$/, "") > 0)
      table[$1] = $0
    else if ($2 != "---" && $2 != "+++" && $1 in table) {
      printf("%s", table[$1])
      delete table[$1]
      sub(/^.*resumed> /, "")
      print
    }
    else
      print
  }' "$@" \
  | $bindir/strace2tsv \
  | sed 's/ <<\([^>]*\)>>\t/\t\1\t/g;s/ <<\([^>]*\)>>$/\t\1/' \
  | $bindir/trackfd $option "$output"
