#!/bin/ash -euf
# -*- mode: Ksh; tab-width: 8; fill-column: 70; -*- 
# $Id: getowner,v 0.0.1 2006/03/13 17:44:45 legion Exp $ 

export LC_ALL=C LANG=C LANGUAGE=C

PROG="${0##*/}"
owner=
rname=

def_owner="legion"
def_rname="Alexey Gladkov"
no_defaults=
no_changelog=
no_signature=
gnupghome=

error() {
    printf %s\\n "$PROG: ERROR: $*" >&2
}

usage() {
    [ "$1" = 0 ] || exec >&2
    cat << EOF
Usage: $PROG [options] <file>

Options:
  --no-defaults           #
  --no-chnagelog          #
  --no-signature          #
  -o,--def-owner=NAME     #
  -r,--def-realname=NAME  #
  -h,--help               show this message.

EOF
    [ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o o:,r:,h -l no-defaults,no-changelog,no-signature,def-owner:,def-realname:,gnupghome:,help -- "$@"` || usage 1
eval set -- "$TEMP"

while :; do
    case $1 in
      -o|--def-owner) shift; def_owner="$1"
	;;
      -r|--def-realname) shift; def_rname="$1"
	;;
      --gnupghome) shift; gnupghome="$1"
	;;
      --no-defaults) no_defaults=1
	;;
      --no-changelog) no_changelog=1
	;;
      --no-signature) no_signature=1
	;;
      -h|--help) usage 0
	;;
      --) shift; break
	;;
      *) error "unrecognized option: $1" >&2; exit 1
	;;
    esac
    shift
done

[ "$#" -eq 1 ] || { error "More arguments required. Try \`$PROG --help' for more information." >&2; exit 1; }
[ -f "$1" ] || { error "Not file: $f"; exit 1; }
f="$1"

signature() {
  info="$(GNUPGHOME="${gnupghome:-/usr/lib/alt-gpgkeys}" rpmsign -Kv "$f" 2>/dev/null)" || { error "rpmsign failed"; return 0; }
  printf %s "$info" |grep -qs '^gpg: Good signature' || { error "Good signature not found"; return 0; }
  info="$(printf %s\\n "$info" |
  	sed -ne 's,^.* \(signature from\|aka\) \"\([^<]\+\) <\([^@]\+\)@altlinux\.\(org\|ru\|net\|com\)>\".*$,\2\t\3,p' |
  	grep -v '\(security\|incominger\)' |uniq)"
  [ -n "$info" ] || return 0
  owner="$(printf %s\\n "$info" |head -n1 |cut -f2)"
  rname="$(printf %s\\n "$info" |head -n1 |cut -f1)"
  [ -n "$owner" ] && printf '%s\t%s\n' "$rname" "$owner" && exit ||:
}

changelog() {
  info="$(rpmquery -p --qf='%{changelogname}\n' "$f" 2>/dev/null)" || { error "rpmquery failed"; return 0; }
  [ -n "$info" ] || return 0
  owner="$(printf %s\\n "$info" |sed -ne 's,^.*<\([^@>]\+\)\(@\| at \)altlinux\(\.\| dot \)\(ru\|com\|net\|org\)>.*$,\1,p')"
  rname="$(printf %s\\n "$info" |sed -ne 's,^\(.*\)[[:space:]]\+<\([^@>]\+\)\(@\| at \)altlinux\(\.\| dot \)\(ru\|com\|net\|org\)>.*$,\1,p')"
  [ -n "$owner" ] && printf '%s\t%s\n' "$rname" "$owner" && exit ||:
}

[ -n "$no_signature" ] || signature
[ -n "$no_changelog" ] || changelog
if [ -z "$no_defaults" ]; then
  [ -z "$def_owner" ] || printf '%s\t%s\n' "$def_rname" "$def_owner"
fi
