#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>

#include <rand.h>
#include "libpgp5.h"
#include "athens.h"

/*--------------------------------------------------*/
static unsigned char msg[MAXUDP];
static int msglen;

/*--------------------------------------------------*/
int main(int argc, char *argv[])
{
  FILE *fp = NULL;
  unsigned char ockey[40], *bp, hashname[40];
  int len, n, mlen;
  unsigned long long keyid[64], kd, kx;
  unsigned char *cp, *pp = NULL;
  DH *dh_key = DH_new();

  if (argc == 1 || argc > 3) {
    fprintf(stderr, "Usage: %s [farlocal.key] file\n", argv[0]);
    exit(0);
  }
  /* create a random conventional key */
  ockey[0] = CPKE;
  ockey[1] = CYPHER;
  RAND_bytes(&ockey[2], 32);
  cfbinit(&ockey[2], &ockey[18], ockey[1]);
  for (len = 0, n = 0; len < 26; len++)
    n += ockey[len];
  ockey[26] = n & 0xff;
  msg[0] = LOCMSG;
  if (argc == 3)
    sscanf(argv[2], "%qx", &kd);
  else if (argc == 2) {
    /* get our keyid */
    setkeyring5("./pubtwo.pkr");
    kx = 0;
    getkey5(&dh_key, NULL, pp, &kx);
    DH_free(dh_key);
    /* pick random key on active list */
    if (NULL == (fp = fopen(RINGFILE, "rb")))
      return -1;
    for (n = 0, mlen = 0; n < 64 && !feof(fp); n++) {
      if (0 >= fscanf(fp, "%*x %qx %*s %*d\n", &keyid[n]))
        break;
      if (keyid[n] == kx)
        mlen++;
    }
    fclose(fp);
    if (!mlen || n < QUORUM)
      return -1;
    msg[0] = INTERN;
    kd = keyid[(ockey[30] * 256 + ockey[31]) % n];
  }
  setkeyring5("./pubring.pkr");
  bp = &msg[3];
  len = pkeenc5(kd, bp, ockey, 27, 0x10);
  msg[1] = len / 256;
  msg[2] = len & 255;
  bp += len;
  fp = fopen(argv[1], "rb");
  mlen = fread(&bp[2], 1, DSIZE, fp);
  fclose(fp);
  bp[0] = mlen / 256;
  bp[1] = mlen & 255;

  if (argc == 2) {              /* add tag and keyid */
    if (mlen > DSIZE - 12)
      mlen = DSIZE - 12;
    cp = bp + mlen + 2;
    RAND_bytes(cp, 4);
    memcpy(ockey, cp, 4);
    cp += 4;
    for (n = 56; n >= 0; n -= 8)
      *cp++ = 0xff & (kx >> n);
  }
  docfb(bp, DSIZE, 1);
  msglen = len + DSIZE + 3;

  /* and about 3375 bytes of junk */

  sprintf(hashname, "INBOX.%d", getpid());
  fp = fopen(hashname, "wb");
  fwrite(msg, 1, msglen, fp);
  fclose(fp);

  if (argc == 2)
    printf("%02X%02X%02X%02X\n", ockey[0], ockey[1], ockey[2], ockey[3]);
  exit(0);
}
