/*
 * $Id: checkattr.c,v 1.1 1994/03/14 12:48:33 casper Exp $
 *
 * Check file attributes.
 *
 * Usage: program file owner group mode.
 *
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>

#define MODE_BITS (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX)

main(int argc, char **argv)
{

    char *file;
    uid_t uid;
    struct passwd *pwd;
    gid_t gid;
    struct group *grp;
    mode_t mode;
    struct stat buf;
    char *p;

    if (argc != 5) {
	fprintf(stderr,"Usage: %s file owner group mode\n", *argv);
	exit(2);
    }

    file = argv[1];

    pwd = getpwnam(argv[2]);
    if (pwd == 0) {
	uid = (uid_t) strtol(argv[2], &p, 0);
	if (p == argv[2] || *p != 0) {
	    fprintf(stderr,"%s: %s is not a valid user name or number\n",
		*argv, argv[2]);
	    exit(2);
	}
    } else
	uid = pwd->pw_uid;

    grp = getgrnam(argv[3]);
    if (grp == 0) {
	gid = (gid_t) strtol(argv[3], &p, 0);
	if (p == argv[3] || *p != 0) {
	    fprintf(stderr,"%s: %s is not a valid group name or number\n",
		*argv, argv[3]);
	    exit(2);
	}
    } else
	gid = grp->gr_gid;

    mode = (mode_t) strtol(argv[4], &p, 8);
    if (p == argv[4] || *p != 0) {
	fprintf(stderr,"%s: %s is not a valid octal file mode\n",
	    *argv, argv[4]);
	exit(2);
    }

    if (lstat(file, &buf) == -1) {
	perror(file);
	exit(2);
    }
    if (buf.st_uid != uid || buf.st_gid != gid ||
	(buf.st_mode & MODE_BITS) != mode) {
	exit(1);
    }
    return 0;
}
