#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include "readwrite.h"
#include "substdio.h"
#include "subfd.h"
#include "error.h"
#include "exit.h"
#include "byte.h"
#include "str.h"
#include "case.h"
#include "fmt.h"
#include "auto_usera.h"
#include "auto_break.h"
#include "qlx.h"
#include "stralloc.h"

#define GETPW_USERLEN 32

extern int getpw_mysql (char *username, int *UID, int *GID);
extern void disconnect_mysql();
extern int connect_mysql();

char *local;
struct passwd *pw;
char *dash;
char *extension;
int connection;

extern stralloc tmpname;
extern stralloc tmphome;
extern stralloc tmpshell;

int userext()
{
  char username[GETPW_USERLEN];
  struct stat st;
  int num, uid, gid;

  extension = local + str_len(local);
  for (;;) {
    if (extension - local < sizeof(username))
      if (!*extension || (*extension == *auto_break)) {
	byte_copy(username,extension - local,local);
	username[extension - local] = 0;
	case_lowers(username);
	errno = 0;
	if (errno == error_txtbsy) _exit(QLX_SYS);
	num = 0;
#ifdef SOLARIS_STUPIDITY
  substdio_put(subfderr,"",1);
#endif
	if (connection) num = getpw_mysql(username, &uid, &gid);
	if (num == -1) _exit(QLX_SYS);
	else if (num) {
	  pw = (struct passwd *) malloc(sizeof(struct passwd));
	  pw->pw_name = tmpname.s;
	  pw->pw_uid = uid;
	  pw->pw_gid = gid;
	  pw->pw_dir = tmphome.s;
	  pw->pw_shell = tmpshell.s;
	}
	if (! pw) pw = getpwnam(username);
	if (pw)
	  if (pw->pw_uid)
	    if (stat(pw->pw_dir,&st) == 0) {
	      if (st.st_uid == pw->pw_uid) {
		dash = "";
		if (*extension) { ++extension; dash = auto_break; }
		return 1;
	      }
	    }
	    else
	      if (error_temp(errno)) _exit(QLX_NFS);
      }
    if (extension == local) {
      /* we didn't find a system account */
      /* but the database is down */
      if (connection) return 0;
      disconnect_mysql();
      _exit(QLX_SYS);
    }
    --extension;
  }
}

char num[FMT_ULONG];

void main(argc,argv)
int argc;
char **argv;
{
  local = argv[1];
  if (!local) _exit(100);

  connection = connect_mysql();

  if (!userext()) {
    extension = local;
    dash = auto_break;
    pw = getpwnam(auto_usera);
  }

  if (connection) disconnect_mysql();

  if (!pw) _exit(QLX_NOALIAS);

  substdio_puts(subfdoutsmall,pw->pw_name);
  substdio_put(subfdoutsmall,"",1);
  substdio_put(subfdoutsmall,num,fmt_ulong(num,(long) pw->pw_uid));
  substdio_put(subfdoutsmall,"",1);
  substdio_put(subfdoutsmall,num,fmt_ulong(num,(long) pw->pw_gid));
  substdio_put(subfdoutsmall,"",1);
  substdio_puts(subfdoutsmall,pw->pw_dir);
  substdio_put(subfdoutsmall,"",1);
  substdio_puts(subfdoutsmall,dash);
  substdio_put(subfdoutsmall,"",1);
  substdio_puts(subfdoutsmall,extension);
  substdio_put(subfdoutsmall,"",1);
  substdio_flush(subfdoutsmall);

  _exit(0);
}


syntax highlighted by Code2HTML, v. 0.9.1