/* mgid.c - simple GID changer
 */

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "getopt.h"


void display_version(void);


/* Display command-line help for mgid.
 */
void display_help(void)
{
	printf("\
Usage: mgid [OPTIONS] [FILE]...\n\
Set the group ID of all FILEs specified to that of the bulletin board system\n\
mbbs (1).\n\
\n\
      --help            show this help and exit\n\
  -V, --version         show version information and exit\n\
\n\
Report bugs to <mconv@ivarch.com>.\n\
");
}


/* Process command-line arguments, and set the GID of all given files.
 */
int main(int argc, char *argv[])
{
	struct option long_options[] = {
		{"help", 0, 0, '!'},
		{"version", 0, 0, 'V'},
		{0, 0, 0, 0}
	};
	char *short_options = "V";
	int option_index = 0;
	int read_something = 0;
	char *file;
	char *pn;
	int c;

	pn = strrchr(argv[0], '/');
	if (pn)
		pn++;
	else
		pn = argv[0];

	do {				    /* read options */
		c = getopt_long(argc, argv, short_options, long_options,
				&option_index);
		if (c < 0)
			continue;
		switch (c) {
		case 'V':
			display_version();
			return (0);
			break;
		case '!':
			display_help();
			return (0);
			break;
		default:
			fprintf(stderr,
				"Try `%s --help' for more information.\n\r",
				pn);
			return (1);
			break;
		}
	} while (c != -1);

	c = 0;				    /* exit status */

	while (optind < argc) {		    /* process each file in turn */

		file = argv[optind];

		if (chown(file, -1, getegid())) {
			fprintf(stderr, "%s: %s: %s\n\r", pn, file,
				strerror(errno));
			c = 1;
		}

		read_something = 1;
		optind++;
	}

	if (!read_something) {		    /* no valid files specified */
		fprintf(stderr, "%s: no valid files specified\n\r", pn);
		c = 1;
	}

	return (c);
}

/* EOF */
