/*
 * $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 *
 */

/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

#ident	"$Header: chown.c 1.9 89/11/09 $@(#)chown:chown.c	1.4"
/*
 * chown uid file ...
 */

#ifdef CCS
/*
 * if we are building cross tools, we don't care to use gettxt()
 */
#define gettxt(a,b)	b
#endif

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <pwd.h>

struct	passwd	*pwd,*getpwnam();
ushort	uid;
int	status;

main(argc, argv)
char *argv[];
{
	register c;
	ushort atoushort();

	if(argc < 3) {
		fprintf(stderr,
		    gettxt("chown:1", "usage: chown uid file ...\n"));
		exit(4);
	}
	if(isnumber(argv[1])) {
		uid = atoushort(argv[1]); /* uid is unsigned short */
		goto cho;
	}
	if((pwd=getpwnam(argv[1])) == NULL) {
		fprintf(stderr,
		    gettxt("chown:2", "chown: unknown user id %s\n"),
		    argv[1]);
		exit(4);
	}
	uid = pwd->pw_uid;

cho:
#ifdef	CCS
	/*
	 * This change allows developers to do makes which
	 * include chown without make complaining.
	 */
	if (geteuid() != 0)
		exit(0);
#endif	/* CCS */
	for(c=2; c<argc; c++) {
#ifdef	CCS
		if(chown(argv[c], uid, (int)-1) < 0) {
#else 
		if(chown(argv[c], uid, (gid_t)-1) < 0) {
#endif	/* CCS */
			perror(argv[c]);
			status = 1;
		}
	}
	exit(status);
}

isnumber(s)
char *s;
{
	register c;

	while(c = *s++)
		if(!isdigit(c))
			return(0);
	return(1);
}

ushort
atoushort(s)
register char *s;
{
	register char c;
	register int i = 0 ;
	register ushort maxushort = ((ushort) ~0) ;

	while(c = *s++) {
		i = c - '0' + 10 * i;
		if(i > maxushort) {
			fprintf(stderr,
		    gettxt("chown:3", "chown: numeric user id too large\n"));
			exit(4);
    		}
	}
	return (ushort) i ;
}
