#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <termios.h>
#include "scfs.h"

char *getpin(const char *termname, const char *prompt)
{
  static char buf[MaxPINLen + 1];
  char *ptr;
  sigset_t sig, sigsave;
  struct termios term, termsave;
  FILE *fp;
  int c, i;

  for (i=0; i<MaxPINLen+1; i++) buf[i] = 0xff;
  
  if ((fp = fopen(termname, "r+")) == NULL) return NULL;
  setbuf(fp, NULL);

  sigemptyset(&sig);
  sigaddset(&sig, SIGINT);
  sigaddset(&sig, SIGTSTP);
  sigprocmask(SIG_BLOCK, &sig, &sigsave);

  tcgetattr(fileno(fp), &termsave);
  term = termsave;

  term.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);

  tcsetattr(fileno(fp), TCSANOW, &term);
  fputs(prompt,fp);

  ptr = buf;

  while ((c=getc(fp)) != EOF && c != '\n') {
    if (ptr < &buf[MaxPINLen]) *ptr++ = c;
  }
  *ptr = 0xff;
  putc('\n', fp);

  tcsetattr(fileno(fp), TCSANOW, &termsave);

  sigprocmask(SIG_SETMASK, &sigsave, NULL);
  fclose(fp);

  return (buf);
}

