/*-
 * Copyright (c) 1999 James Howard
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	$Id$
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <err.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "grep.h"

/* Flags passed to regcomp() and regexec() */
int cflags, eflags;

char *pattern;

int patterns;

regex_t *pat;

/* For regex errors  */
char re_error[RE_ERROR_BUF + 1];

/* Command-line flags */
int	 Eflag;		/* -E: interpret pattern as extended regexp */
int	 Fflag;		/* -F: interpret pattern as list of fixed strings */
int	 Gflag;		/* -G: interpret pattern as basic regexp */
int	 Lflag;		/* -L: only show names of files with no matches */
int	 Vflag;		/* -V: display version information */
int	 Zflag;		/* -Z: decompress input before processing */
int	 aflag;		/* -a: only search ascii files */
int	 bflag;		/* -b: show block numbers for each match */
int	 cflag;		/* -c: only show a count of matching lines */
int	 hflag;		/* -h: don't print filename headers */
int	 iflag;		/* -i: ignore case */
int	 lflag;		/* -l: only show names of files with matches */
int	 nflag;		/* -n: show line numbers in front of matching lines */
int	 oflag;		/* -o: always print file name */
int	 qflag;		/* -q: quiet mode (don't output anything) */
int	 sflag;		/* -s: silent mode (ignore errors) */
int	 vflag;		/* -v: only show non-matching lines */
int	 wflag;		/* -w: pattern must start and end on word boundaries */
int	 xflag;		/* -x: pattern must match entire line */
			  
char *__progname;

int
main(int argc, char *argv[])
{
    struct stat patternstat;
    int i, c;
    FILE *patternfile;
    char *tmp;

    __progname = basename(argv[0]);

    while ((c = getopt(argc, argv, "EFGLVZabce:f:hilnoqsvwx")) != -1) {
	switch(c) {
	case 'E':
	    Eflag++;
	    break;
	case 'F':
	    Fflag++;
	    break;
	case 'G':
	    Gflag++;
	    break;
	case 'L':
	    lflag = 0;
	    Lflag = qflag = 1;
	    break;
	case 'V':
	    fprintf(stderr, "Jamie's grep version %u.%u\n", VER_MAJ, VER_MIN);
	    fprintf(stderr, argv[0]);
	    usage();
	    break;
	case 'Z':
	    Zflag++;
	    break;
	case 'a':
	    aflag = 1;
	    break;
	case 'b':
	    bflag = 1;
	    break;
	case 'c':
	    cflag = 1;
	    break;
	case 'e':
	    pattern = optarg;
	    break;
	case 'f':
	    if (stat(optarg, &patternstat))
		err(2, "%s", optarg);
	    pattern = grep_malloc(patternstat.st_size + 1);
	    if ((patternfile = fopen(optarg, "r")) == NULL)
		err(2, "%s", optarg);
	    fread(pattern, patternstat.st_size, 1, patternfile);
	    pattern[patternstat.st_size] = 0;
	    break;
	case 'h':
	    oflag = 0;
	    hflag = 1;
	    break;
	case 'i':
	    cflags |= REG_ICASE;
	    break;
	case 'l':
	    Lflag = 0;
	    lflag = qflag = 1;
	    break;
	case 'n':
	    nflag = 1;
	    break;
	case 'o':
	    hflag = 0;
	    oflag = 1;
	    break;
	case 'q':
	    qflag = 1;
	    break;
	case 's':
	    sflag = 1;
	    break;
	case 'v':
	    vflag = 1;
	    break;
	case 'w':
	    wflag = 1;
	    break;
	case 'x':
	    xflag = 1;
	    break;
	default:
	    usage();
	}
    }

    argc -= optind;
    argv += optind;

    if (argc == 0 && !pattern)
	usage();
    
    if (!pattern) {
	pattern = argv[0];
	argc--;
	argv++;
    }    
    
    switch (__progname[0]) {
    case 'e':
	Eflag++;
	break;
    case 'f':
	Fflag++;
	break;
    case 'g':
	Gflag++;
	break;
    case 'z':
	Zflag++;
	break;
    }
	
    if (Fflag) {
	tmp = strsep(&pattern, "\n");
	patterns = 0;
	cflags |= REG_NOSPEC;
	while (tmp != NULL) {
	    patterns++;
	    pat = grep_realloc(pat, patterns * sizeof(regex_t));
	    if ((c = regcomp(&pat[patterns - 1], tmp, cflags))) {
		fprintf(stderr, "%s\n", tmp);
		regerror(c, pat, re_error, RE_ERROR_BUF);
		err(2, re_error);
	    }
	    tmp = strsep(&pattern, "\n");
	}
    } else {
	cflags |= Eflag ? REG_EXTENDED : REG_BASIC;
	pat = grep_malloc(sizeof(regex_t));
	if ((c = regcomp(pat, pattern, cflags))) {
	    regerror(c, pat, re_error, RE_ERROR_BUF);
	    err(2, re_error);
	}
	patterns = 1;
    }

    if ((argc == 0 || argc == 1) && !oflag)
	hflag = 1;
    if (argc == 0) 
	exit(!procfile(NULL));
    for (c = i = 0; i < argc; i++) {
	c += procfile(argv[i]);
    }
    if (Fflag)
	free(pat);

    exit(!c);
}

void
usage(void) {
    fprintf(stderr, "usage: %s [-EFGLVabchilnoqsvwx] [-e file] [-f file]\n", 
	    __progname);
    exit(2);
}
