#include <stdio.h>
#include <string.h>
#include "libopgp.h"
#define SMHEAD "-----BEGIN PGP SIGNED MESSAGE-----"

static char msg[][64] =
{"+++ Good Signature +++\n", "!!! BAD SIGNATURE\n", "*** BAD ARMOR\n",
 "*** BAD HALG\n", "*** SIG ERROR\n", "--- No Sig Key\n"};
/*-------------------------*/
int main(int argc, char *argv[])
{
  unsigned char dbuf[1024], xbuf[1024], *bp;
  int cnt, halg = 1, ret = 0;
  void *hctx;
  FILE *inf = stdin, *outf = stdout;

  if (argc > 1) {
    if (argv[1][0] != '-' && !(inf = fopen(argv[1], "r")))
      exit(-1);
    else
      outf = NULL;
  }
  while (!feof(inf)) {
    for (;;)
      if (!fgets(dbuf, 1023, inf) || !strncmp(dbuf, SMHEAD, 34))
        break;
      else if (outf)
        fputs(dbuf, outf);
    if (feof(inf))
      break;
    while (dbuf[0] != '\n' && dbuf[0] != '\r') {
      fgets(dbuf, 1023, inf);
      if (!strstr(dbuf, "Hash:"))
        continue;
      for (cnt = 0; cnt < 4; cnt++)
        if (strstr(dbuf, PGP_hbnr[cnt]))
          halg = cnt + 2;
    }
    cnt = -3;
    if (NULL != (hctx = PGP_hini(halg))) {
      xbuf[0] = 0, cnt = 0, bp = dbuf;
      while (!feof(inf)) {      /* doubled - don't hash last TWO lines */
        fgets(bp, 1023, inf);
        if (!strncmp(bp, "-----BEGIN PGP SIGNATURE-----", 29))
          break;
        PGP_ctln(bp);
        bp = cnt++ & 1 ? xbuf : dbuf;
        PGP_hblk(hctx, bp, strlen(bp));
        if (*bp && outf)
          bp[strlen(bp) - 1] = 0, bp[strlen(bp) - 1] = '\n', fputs(bp, outf);
      }
      while (bp[0] != '\n' && bp[0] != '\r')
        fgets(bp, 1023, inf);
      cnt = -2;
      if (!PGP_um2b(inf, xbuf)) {
        cnt = PGP_sigck(&xbuf[1 + (1 << (xbuf[0] & 3))], hctx);
        if (cnt && cnt != -1 && cnt != -5)
          cnt = -4;
      }
    }
    if (cnt)
      fputs(msg[-cnt], stderr);
    fputs(msg[-cnt], stdout);
    while (!feof(inf) && fgets(xbuf, 1023, inf)
           && strncmp(xbuf, "-----END PGP SIGNATURE-----", 27));
    ret |= cnt;
  }
  return ret;
}
