
/* pinched from pwcheck, pinched from cyrus imap */
/* written over a crate of beer by Keith Lewis  */

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <syslog.h>
#include "config.h"

#define STATEDIR        "/var"
#define SMBUF 64
#define DEBUG 0

extern int errno;

int main(int argc, char *argv[])
{
    extern int optind;
    extern char *optarg;
    int opt;
    char *ldapserver;
    char uname[SMBUF], pass[SMBUF];
    char buff[SMBUF];

    while ((opt = getopt(argc, argv, "s:")) != -1) {

        /* only allow one of the three possibilities */
        switch (opt) {
          case 's':
            ldapserver = optarg;
            break;
        }
    }
    if (argc != optind){
	exit(2);
    }

    uname[0] = '\0';
    pass[0] = '\0';
    /* get the username and password from stdin */
    while (fgets(buff, sizeof(buff), stdin) != (char*) 0) {
        /* strip '\r\n' */
        buff[strlen(buff)-1] = '\0';
        if (strlen(buff) && (buff[strlen(buff)-1] == '\r'))
            buff[strlen(buff)-1] = '\0';

        if (!strncmp(buff, NAMESTR, strlen(NAMESTR)))
            strcpy(uname, buff+sizeof(NAMESTR)-1);
        if (!strncmp(buff, PASSSTR, strlen(PASSSTR)))
            strcpy(pass, buff+sizeof(PASSSTR)-1);
    }

	if(DEBUG) printf("user: %s, pass: %s\n",uname,pass);
    if (!uname[0] || !pass[0]){
        exit(3);
    }

    if(ldap_pwd_ok(ldapserver, uname, pass)) {
      fprintf(stderr, "valid passwd\n");
      printf("User:%s\n", uname);
      exit(0);
    }else{
      exit(1);
    }
}
