#!/bin/sh

LOOKUP=./lookup5
touch keys.out pubring.ckp secring.ckp

while read i ; do
    if (echo $i | grep PUBKEY >/dev/null) ; then
#pubring, see if new, add to ring; either way, resort keylist
        $LOOKUP -r $i >keyline
        if (grep `cut -c 18-33 <keyline` keys.out >/dev/null) ; then
            echo `cat keyline` `date +%s` >keyline2
            rm $i;
        else
#new key, add to top
            wc $i | cut -c 19-24 >ckp.tmp
            cat pubring.ckp >>ckp.tmp
            mv ckp.tmp pubring.ckp

            if [ -s pubring.pkr ]; then cat pubring.pkr >>$i; fi
            mv $i pubring.pkr
#initially stale - wait for second clear broadcast (so it will have keys)
            echo `cat keyline` $[`date +%s` - 1200 ] >keyline2
        fi
        rm keyline
#Sort, removing later duplicate keyids
        cat keyline2 keys.out | awk '{if(!x[$2]){x[$2]=$2;print $0}}' >actv.new
        sort +3 -n -r <actv.new >actv.pre
        mv actv.pre keys.out
        rm -f keyline2 actv.new

    elif (echo $i | grep SECKEY >/dev/null) ; then
#add to secring
        wc $i | cut -c 19-24 >ckp.tmp
        cat secring.ckp >>ckp.tmp
        mv ckp.tmp secring.ckp

        if [ -s secring.skr ]; then cat secring.skr >>$i; fi
        mv $i secring.skr
    elif (echo $i | grep INTERN >/dev/null) ; then
        (
        mv $i $i.gz
        gzip -d $i.gz;
        geturl `cat $i` -t 180 | gzip -9 >>$i.tag
        ./athmsg $i.tag `cat $i.key`
        rm $i $i.tag $i.key
        )&
    elif (echo $i | grep LOCAL >/dev/null) ; then
        (
        mv $i $i.gz
        gzip -d $i;
        )&
    else
        echo Returned: $i
    fi

done

#the first awk script returns only the first line with a unique entry (field 2)
#in the stream so it sorts the keys in order of the most recently received.
