/*	Copyright (c) 1988 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.	*/
/* $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.
 */

#ident	"$Header: srchtxt.c 1.5 90/10/23 $@(#)srchtxt:srchtxt.c 1.0 AT&T-UP"

#include	<stdio.h>
#include	<regexpr.h>
#include	<string.h>
#include	<locale.h>
#include	<sys/types.h>
#include	<dirent.h>

#define	P_locale	"/usr/lib/locale/"
#define	L_locale	(sizeof(P_locale))
#define	MESSAGES	"/LC_MESSAGES/"
#define	ESIZE		BUFSIZ

/* External functions */

extern	int	msgattach();
extern	void	msgdetach();
extern	int	getopt();
extern	void	exit();
/* extern	char	*strecpy();	*/
extern	char	*strrchr();
extern	char	*strchr();


/* External variables */

extern	char	*optarg;
extern	int	optind;
extern	int	errno;
extern	int	sys_nerr;
extern	char	*sys_errlist[];

/* Internal functions */

static	void	usage();
static	void	prnt_str();
static	int	attach();
static	void	detach();
static	void	find_msgs();
static	char	*syserr();
/* add */
static	unsigned char	*strecpy();
static	unsigned char	*streadd();
/* end */

/* Internal variables */

static	char	*cmdname; 	/* points to the name of the command */
static	int	lflg;		/* set if locale is specified on command line */
static	int	mflg;		/* set if message file is specified on command line */
static	char	locale[15];	/* save name of current locale */
static  char	*msgfile;       /* points to the argument immediately following the m option */
static	char	*text;		/* pointer to search pattern */
static	int	textflg;	/* set if text pattern is specified on command line */
static	int	sflg;		/* set if the s option is specified */
static	char	*fname;		/* points to message file name */
static	int	msgnum;		/* message number */

/*	add for 8th bit through		*/
static	int	pflg;		/* set if current locale(LC_MESSAGES) is differnce from environment(LC_CTYPE) */


main(argc, argv)
int	argc;
char	*argv[];
{
	int	ch;
	char	*end;
	int	addr;
	int	len, rlen;
	char	pathname[128];
	char	*cp;
	char	ebuf[ESIZE];
	DIR	*dirp;
	struct	dirent	*dp;

	/* find last level of path in command name */
	if (cmdname = strrchr(*argv, '/'))
		++cmdname;
	else
		cmdname = *argv;

	/* parse command line */
	while ((ch = getopt(argc, argv, "sl:m:")) != -1)
		switch(ch) {
			case	'l':
				lflg++;
				(void)strcpy(locale, optarg);
				continue;
			case	'm':
				mflg++;
				msgfile = optarg;
				continue;
			case	's':
				sflg++;
				continue;
			default:
				usage();
			}
	if (mflg && optind < argc) {
		text = argv[optind++];
		textflg++;
	}
	if (optind != argc )
		usage();

	/* create full path name to message files */
	if (!lflg)
		(void)strcpy(locale, setlocale(LC_MESSAGES, (char *)0));
	/*	add for 8th bit through		*/
	else
		if(!strcmp(locale, setlocale(LC_CTYPE, (char *)0)))
			pflg++;
	/*	end	*/
	(void)strcpy(pathname, P_locale);
	(void)strcpy(&pathname[L_locale - 1], locale);
	(void)strcat(pathname, MESSAGES);
	len = strlen(pathname);

	if (textflg) {
			/* compile regular expression */
		if (compile(text, &ebuf[0], &ebuf[ESIZE]) == (char *)NULL) {
			(void)fprintf(stderr, "%s: ERROR: regular expression compile failed\n", cmdname);
			(void)exit(1);
		}
	}

	/* access message files */ 
	if (mflg) {
		end = msgfile + strlen(msgfile) + 1;
		if (*msgfile == ',' || *(end - 2) == ',')
			usage();
		while ((fname = strtok(msgfile, ",\0")) != NULL) {
			if (strchr(fname, '/') != (char *)NULL) {
				cp = fname;
				rlen = 0;
			} else {
				cp = pathname;
				rlen = len;
			}
			msgfile = msgfile + strlen(fname) + 1;
			if ((addr = attach(cp, rlen)) == -1) {
				(void)fprintf(stderr, "%s: ERROR: failed to access message file '%s'\n",cmdname, cp);
				if (end != msgfile)
					continue;
				else
					break;
			}
			find_msgs(addr, ebuf);
			(void)detach(addr);
			if  (end == msgfile)
				break;
		}
	} /* end if (mflg) */
	else { 
		if((dirp = opendir(pathname)) == (DIR *) NULL) {
			(void)fprintf(stderr, "%s: ERROR: %s %s\n", cmdname, pathname, syserr());
			(void)exit(1);
		}
		while( (dp = readdir(dirp)) != NULL ) {
			if (dp->d_name[0] == '.')
				continue;
			fname = dp->d_name;
			if ((addr = attach(pathname, len)) == -1) {
				(void)fprintf(stderr, "%s: ERROR: failed to access message file '%s'\n",cmdname, pathname);
				continue;
			}
			find_msgs(addr, ebuf);
			(void)detach(addr);
		}
		closedir(dirp);
	}
(void)exit(0);
}


/* print usage message */
static void
usage()
{
	(void)fprintf(stderr, "usage: srchtxt [-s]\n       srchtxt [-s] -l locale\n       srchtxt [-s] [-l locale] [[-m msgfile[,msgfile[,msgfile[,...]]] [text]]\n");
	(void)exit(1);
}

/* print string - non-graphic characters are printed as alphabetic
		  escape sequences
*/
static	void
prnt_str(instring)
char	*instring;
{
	char	outstring[1024];

	(void)strecpy(outstring, instring, (char *)NULL);
	if (sflg)
		(void)fprintf(stdout, "%s\n", outstring);
	else
		(void)fprintf(stdout, "<%s:%d>%s\n", fname, msgnum, outstring);
}

/*
 * Used to communicate the message file size between attach and detach.
 * Assumes that attach/detach will be called in "pairs", ie, no more than
 * one database attached at one time.
 */

/* attach message database file to process address space */
static int
attach(path, len)
char	*path;
int	len;
{
	(void)strcpy(&path[len], fname);
	return(msgattach(path));
}

static void
detach(addr)
int	addr;
{
	msgdetach(addr);
}


/* find messages in message files */
static void
find_msgs(addr, regexpr)
int	addr;
char	*regexpr;
{
	int	num_msgs;
	char	*msg;

	num_msgs = *(int *)addr; 
	for (msgnum = 1; msgnum<=num_msgs; msgnum++) {
		msg = (char *)(*(int *)(addr + sizeof(int) * msgnum) + addr);
		if (textflg)
			if (step(msg, regexpr)) {
				prnt_str(msg);
				continue;
			} else
				continue;
		prnt_str(msg);
	}
}

/* print description of error */ 
static char *
syserr()
{
	return (errno <= 0 ? "No error (?)"
	   : errno < sys_nerr ? sys_errlist[errno]
	   : "Unknown error (!)");
}

/* 
 *	changed: libgen:strecpy() -> Internal functions
 *		 and support 8th bit through
 */
#include	<ctype.h>

#define mbyte		(_ctype[520] > 1)
#define	ISASCII(c)	(!((c) & ~0177))
#define ISPRINT(c,flg)	(flg && (mbyte && !ISASCII(c)) || isprint(c))
		/*
		 * if locale LC_MESSAGES epual LC_CTYPE,
		 *	support 8th bit through
		 */

static unsigned char *
strecpy( pout, pin, except )
unsigned char	*pout;
unsigned char	*pin;
unsigned char	*except;
{
	(void)streadd( pout, pin, except );
	return  pout;
}


static unsigned char *
streadd( pout, pin, except )
register unsigned char	*pout;
register unsigned char	*pin;
unsigned char	*except;
{
	register unsigned	c;

	while( c = *pin++ ) {
		if( !ISPRINT(c,pflg) && ( !except || !strchr( except, c ) ) ) {
			*pout++ = '\\';
			switch( c ) {
			case '\n':
				*pout++ = 'n';
				continue;
			case '\t':
				*pout++ = 't';
				continue;
			case '\b':
				*pout++ = 'b';
				continue;
			case '\r':
				*pout++ = 'r';
				continue;
			case '\f':
				*pout++ = 'f';
				continue;
			case '\v':
				*pout++ = 'v';
				continue;
			case '\\':
				continue;
			default:
				sprintf( pout, "%.3o", c );
				pout += 3;
				continue;
			}
		}
		if( c == '\\'  &&  ( !except  ||  !strchr( except, c ) ) )
			*pout++ = '\\';
		*pout++ = c;
	}
	*pout = '\0';
	return  (pout);
}
