1/*	$OpenBSD: getoldopt.c,v 1.9 2009/10/27 23:59:22 deraadt Exp $	*/
2/*	$NetBSD: getoldopt.c,v 1.3 1995/03/21 09:07:28 cgd Exp $	*/
3
4/*-
5 * Plug-compatible replacement for getopt() for parsing tar-like
6 * arguments.  If the first argument begins with "-", it uses getopt;
7 * otherwise, it uses the old rules used by tar, dump, and ps.
8 *
9 * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed
10 * in the Public Domain for your edification and enjoyment.
11 */
12
13#include <sys/cdefs.h>
14__FBSDID("$FreeBSD$");
15
16#include <sys/types.h>
17#include <sys/stat.h>
18#include <stdio.h>
19#include <string.h>
20#include <unistd.h>
21
22int getoldopt(int, char **, const char *);
23
24int
25getoldopt(int argc, char **argv, const char *optstring)
26{
27	static char	*key;		/* Points to next keyletter */
28	static char	use_getopt;	/* !=0 if argv[1][0] was '-' */
29	char		c;
30	char		*place;
31
32	optarg = NULL;
33
34	if (key == NULL) {		/* First time */
35		if (argc < 2)
36			return (-1);
37		key = argv[1];
38		if (*key == '-')
39			use_getopt++;
40		else
41			optind = 2;
42	}
43
44	if (use_getopt)
45		return (getopt(argc, argv, optstring));
46
47	c = *key++;
48	if (c == '\0') {
49		key--;
50		return (-1);
51	}
52	place = strchr(optstring, c);
53
54	if (place == NULL || c == ':') {
55		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
56		return ('?');
57	}
58
59	place++;
60	if (*place == ':') {
61		if (optind < argc) {
62			optarg = argv[optind];
63			optind++;
64		} else {
65			fprintf(stderr, "%s: %c argument missing\n",
66				argv[0], c);
67			return ('?');
68		}
69	}
70
71	return (c);
72}
73