/*
 * pgpglue.c -- 
 *
 * This is a bunch of glue routines to PGP.  In this implementation
 * it just forks and calls the PGP executable.  In future versions
 * this code can call a PGP library instead.
 *
 * Created by:	Derek Atkins <warlord@MIT.EDU>
 *
 * Copyright 1994 Derek A. Atkins and the Massachusetts Institute of
 * Technology
 *
 * For copying and distribution information, please see the file
 * <warlord-copyright.h>.
 *
 * $Source: /mit/warlord/C/pgpsign/src/RCS/pgpglue.c,v $
 * $Author: warlord $
 *
 */

#include "warlord-copyright.h"
#include "pgpsign.h"

/* add a key of length keylen to the keyring, and put the output generated
 * by PGP into the file keyout.
 */
int
add_key_to_keyring(char *key, int keylen, char *keyring, char *keyout, 
		   char **error_msg)
{
  char command[BUFSIZ];
  FILE *pgp;
  
  sprintf(command, "%s -kaf +batchmode %s > %s 2>&1", PGPPROG, 
	  keyring, keyout);

  if ((pgp = popen(command, "w")) == NULL) {
    *error_msg = "Error adding user key to keyring:  popen failed";
    return -1;
  }
  writekeytofile(key, keylen, pgp);
  pclose(pgp);

  return 0;
}

/* Extract the key for user in the keyring, and put that key into 
 * key, returning that and the key length, and possbily an error message.
 * Key is alloc'ed, and should be freed by the caller.
 */
int
extract_key_from_keyring(char *user, char *keyring, char **key, int *keylen)
{
  char command[BUFSIZ];
  FILE *pgp;

  sprintf(command, "%s -kxaf +batchmode '%s' %s 2>/dev/null", PGPPROG, 
	  user, keyring);

  if ((pgp = popen(command, "r")) == NULL) {
    return -1;
  }

  readkeyfromfile(key, keylen, pgp);
  pclose(pgp);

  return 0;
}

int
sign_key(char *user, char *keyring, char **error_msg)
{
  char command[BUFSIZ];
  char pass[BUFSIZ];
  FILE *pgp, *passphrase;

  sprintf(command, "PGPPASSFD=0 %s -ks +batchmode '%s' %s >/dev/null 2>&1", 
	  PGPPROG, user, keyring);

  if ((pgp = popen(command, "w")) == NULL) {
    *error_msg = "Error trying to sign key:  popen failed";
    return -1;
  }
  if ((passphrase = fopen(PASSFILE, "r")) == NULL) {
    pclose(pgp);
    *error_msg = "Error trying to sign key:  cannot read passphrase";
    return -1;
  }
  fgets(pass, BUFSIZ, passphrase);
  fputs(pass, pgp);
  bzero(pass, sizeof(pass));
  fclose(passphrase);
  fflush(pgp);
  pclose(pgp);

  return 0;
}
