#!/bin/bash
# $Id: sign 35 2009-03-15 16:07:53Z lrupp $
#

GPG_OPTS="--armor --detach-sign"
VERBOSE="no"
EXPORT="no"
RPMSIGN="no"

function usage (){
    echo
    echo "usage: $0 [OPTIONS] <file>"
    echo "       -c       : clearsign (inline ascii armored - usefull for SLES9 patches and scripts)"
    echo "       -d       : detach sign the file"
    echo "       -e       : export GPG key"
    echo "       -k <key> : GPG Key"
    echo "       -r       : sign rpms"
    echo "       -v       : verbose"
    exit $1
}

if [ ! $1 ]; then
    usage 1
fi

while getopts 'cdehk:rv' OPTION; do
    case $OPTION in
        h)
            usage 0
        ;;
        v)
            VERBOSE="true"
        ;;
        d)
            GPG_OPTS="--armor --detach-sign"
        ;;
        c)
            GPG_OPTS="--armor --clearsign"
        ;;
        e)
            EXPORT="true"
        ;;
        k)
            KEY=$OPTARG
        ;;
        r)
            RPMSIGN="true"
        ;;
        *)
            usage 1
        ;;
    esac
done
shift $(( OPTIND - 1 ))
FILES="$@"

if [ -f $KEY ]; then
    if [ "$VERBOSE" == "true" ]; then
        echo "using $KEY for signing"
    fi
fi
gpg-agent || eval $(gpg-agent --daemon)

if [ "$RPMSIGN" == "true" ]; then
    if [ "$VERBOSE" == "true" ]; then
        rpm --resign $FILES 2> >(grep -v skip | grep -v reopened 1>&2)
    else
        rpm -v --resign $FILES 2> >(grep -v skip | grep -v reopened 1>&2)
    fi
    if [ "$EXPORT" == "true" ]; then
        echo "Export doesn't make sence whith RPMs"
    fi
else
    for file in $FILES; do
        if [ "$VERBOSE" == "true" ]; then
            echo "signing $file"
        fi
        gpg $GPG_OPTS $file
        if [ "$EXPORT" == "true" ]; then
            gpg --armor --export $KEY > ${file}.key
        fi
    done
fi
exit 0 

