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

/*-------------------------*/
int main(int argc, char *argv[])
{
  unsigned char dbuf[4096], *bp, pp[256] = "";
  int cnt, halg = 2, salg;
  keyid_t keyid = 0;
  void *signkey, *hctx;
  extern char *optarg;
  FILE *inf = stdin, *outf = stdout;

  while ((cnt = getopt(argc, argv, "i:o:k:p:d:r:")) != -1) {
    if (cnt == 'k')
      sscanf(optarg, "%qx", &keyid);
    else if (cnt == 'd')
      halg = atoi(optarg);
    else if (cnt == 'p')        /* password */
      strncpy(pp, optarg, 255);
    else if (cnt == 'r')
      PGP_kring(optarg, 0);
    else if (cnt == 'i') {
      if (NULL == (inf = fopen(optarg, "r")))
        exit(-1);
    } else if (cnt == 'o') {
      if (NULL == (outf = fopen(optarg, "w")))
        exit(-1);
    } else {
      fprintf(stderr, "Usage: clearsig [-i inf] [-o outf] options...\n"
              "Options: [-k key] [-d hash] [-p passph] [-r skr]\n"
              "Clearsigns text from stdin to stdout (if -i/-o not used)\n");
    }
  }
  if (NULL == (hctx = PGP_hini(halg)))
    return -4;
  if (0 >= (salg = PGP_gtkey(&signkey, pp, &keyid))) {
    fprintf(stderr, "No Secret key found %d\n", salg);
    return -5;
  }
  fputs(SMHEAD, outf);
  if (halg != 1)
    fprintf(outf, "\nHash: %s\n\n", PGP_hbnr[halg - 2]);
  else
    fprintf(outf, "\n\n");
  bp = dbuf;
  while (!feof(inf)) {          /* dashesc plain, canonical to hash */
    if (NULL == fgets(bp, 4095, inf))
      break;
    if (*bp == '-')
      memmove(&bp[2], bp, strlen(bp) + 1), bp[1] = ' ';
    PGP_ctln(bp);
    PGP_hblk(hctx, bp, strlen(bp));
    bp[strlen(bp) - 1] = 0;
    bp[strlen(bp) - 1] = '\n';
    fputs(bp, outf);
  }
  fputs("\n", outf);
  cnt = PGP_sigmk(signkey, hctx, dbuf, keyid, 2, halg, salg, NULL);
  fclose(inf), inf = tmpfile();
  fwrite(dbuf, 1, cnt, inf), fflush(inf), fseek(inf, 0, SEEK_SET);
  return (PGP_armor(inf, outf, "SIGNATURE", NULL));
}
