#include <stdio.h>
#include <rpc/rpc.h>
#include <rpcsvc/ypclnt.h>
#ifndef LINUX
#include <pwd.h>
#endif
#include <rpcsvc/yppasswd.h>


/*
 * Invoke the rpc call to argv[1]. Stdin should be, on separate lines,
 * the cleartext passwd, followed by the elements of the new passwd
 * struct.
 */

#define LINE_CLEAR 	0
#define LINE_NAME 	1
#define LINE_PASSWD 	2
#define LINE_UID 	3
#define LINE_GID 	4
#define LINE_AGE 	5
#define LINE_COMMENT 	6
#define LINE_GECOS 	7
#define LINE_DIR 	8
#define LINE_SHELL 	9

typedef char Line[100];

main(argc, argv)
int argc;
char **argv;
{
    int rc, why;
    char *host, *s;
    Line lines[10];
    int i;
    int ypport;
    struct yppasswd ypp;
    
    if (argc != 2)
    {
	printf("ERROR: args\n");
	exit(1);
    }

    host = argv[1];

    for (i = 0; i < 10; i++)
    {
	if (fgets(lines[i], sizeof(lines[i]), stdin) == NULL)
	{
	    printf("ERROR: Short input\n");
	    exit(1);
	}
	if ((s = (char *) index(lines[i], '\n')) != NULL)
	    *s = 0;
    }

    ypp.oldpass = lines[LINE_CLEAR];

    ypp.newpw.pw_name = lines[LINE_NAME];
    ypp.newpw.pw_passwd = lines[LINE_PASSWD];
    ypp.newpw.pw_uid = atoi(lines[LINE_UID]);
    ypp.newpw.pw_gid = atoi(lines[LINE_GID]);
#ifdef sun
    ypp.newpw.pw_age = lines[LINE_AGE];
#else
#ifndef AIX 
#ifndef LINUX
    ypp.newpw.pw_quota = atoi(lines[LINE_AGE]);
#endif
#endif
#endif    
#ifndef AIX
#ifndef LINUX
    ypp.newpw.pw_comment = lines[LINE_COMMENT];
#endif
#endif
    ypp.newpw.pw_gecos = lines[LINE_GECOS];
    ypp.newpw.pw_dir = lines[LINE_DIR];
    ypp.newpw.pw_shell = lines[LINE_SHELL];

    if ((ypport = getrpcport(host, YPPASSWDPROG,
			     YPPASSWDPROC_UPDATE, IPPROTO_UDP)) == 0)
    {
	printf("ERROR: %s is not running ypassswdd.\n", host);
	exit(1);
    }
    
    if (ypport >= IPPORT_RESERVED)
    {
	printf("ERROR: yppasswdd on %s not privleged.\n", host);
	exit(1);
    }
    
    rc = callrpc(host, YPPASSWDPROG, YPPASSWDVERS,
		 YPPASSWDPROC_UPDATE,
		 xdr_yppasswd, &ypp, xdr_int, &why);

    if (rc > 0)
    {
#ifdef dynix
	printf("ERROR: callrpc failed: rc=%d Dynix won't decode\n", rc);
#else 
	printf("ERROR: callrpc failed: rc=%d %s\n", rc,clnt_sperrno(rc));
#endif
	exit(1);
    }

    if (why > 0)
    {
	printf("ERROR: callrpc failed: why=%d\n", why);
	exit(1);
    }

    printf("SUCCESS\n");
	
    exit(0);
}
