/*  $Revision: 1.6 $
**
**  Trap C News relaynews options, then call inews.
*/
#include "configdata.h"
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include "paths.h"
#include "libinn.h"
#include "clibrary.h"
#include "macros.h"


static char	LOG[] = _PATH_LOGFILE;
static char	ERRLOG[] = _PATH_ERRLOG;
static char	*Program;


/*
**  Print a usage message and exit.
*/
STATIC NORETURN
Usage()
{
    (void)fprintf(stderr,
	"usage: %s [-inrs] [-d fhlmt] [-x site] [-o days] [input]\n", Program);
    exit(1);
}


int
main(ac, av)
    int			ac;
    char		*av[];
{
    register int	i;
    register char	*p;
    register STRING	*vp;
    STRING		*vec;
    BOOL		DoStdout;
    BOOL		DoStderr;

    /* Set program name. */
    if ((p = strrchr(av[0], '/')) != NULL)
	Program = p + 1;
    else
	Program = av[0];

    /* Set up new calling vector with worst-case space allocation. */
    vec = NEW(STRING, 1 + ac * 2 + 1);
    vp = vec;
    *vp++ = _PATH_INEWS;
    *vp++ = "-h";

    /* Parse JCL. */
    DoStdout = FALSE;
    DoStderr = FALSE;
    while ((i = getopt(ac, av, "d:no:suirx:")) != EOF)
	switch (i) {
	default:
	    Usage();
	    /* NOTREACHED */
	case 'd':		/* Debugging				*/
	    for (p = optarg; *p; p++)
		switch (*p) {
		default:
		    Usage();
		    /* NOTREACHED */
		case 'f':
		case 'h':
		case 'l':
		case 'm':
		case 't':
		    break;
		}
	    break;
	case 'n':		/* "NNTP" mode -- log rejections	*/
	case 'o':		/* Reject old articles			*/
	case 's':		/* Serious -- exit non-zero on failure	*/
	case 'u':		/* Unlink input file			*/
	    break;
	case 'r':		/* Redirect stderr and stdout		*/
	    DoStderr = TRUE;
	    /* FALLTHROUGH */
	case 'i':		/* Redirect stdout			*/
	    DoStdout = TRUE;
	    break;
	case 'x':		/* Exclude site				*/
	    *vp++ = "x";
	    *vp++ = optarg;
	    break;
	}

    /* Parse arguments -- at most one, an input file. */
    ac -= optind;
    av += optind;
    switch (ac) {
    default:
	Usage();
	/* NOTREACHED */
    case 0:
	break;
    case 1:
	*vp++ = av[0];
	break;
    }
    *vp = NULL;

    /* Handle redirection. */
    if (DoStdout && freopen(LOG, "a", stdout) == NULL) {
	(void)fprintf(stderr, "Can't redirect stdout, %s.\n", strerror(errno));
	exit(1);
    }
    if (DoStderr && freopen(ERRLOG, "a", stderr) == NULL) {
	(void)fprintf(stderr, "Can't redirect stderr, %s.\n", strerror(errno));
	exit(1);
    }

    (void)execv(vec[0], vec);
    (void)fprintf(stderr, "Can't exec \"%s\", %s.\n",
	    vec[0], strerror(errno));
    exit(1);
    /* NOTREACHED */
}
