/*
 * bb.c 
 *
 * BIG BROTHER CLIENT PROGRAM
 * Sean MacGuire
 * Version 1.9
 * Mar 13th, 2002
 *
 * (c) Copyright Quest Software, Inc.  1997-2002  All rights reserved.
 *
 * SENDS THE INPUT LINE TO THE DAEMON ON THE BIG BROTHER PORT
 * Format: bb IP-ADDR [<LINE>|-]
 *
 *	IP-ADDR:	IP-ADDR OF THE SERVER
 *	LINE:		<page|status|summary> <DATA>
 *		DATA:	for page:	<NUMERIC MESSAGE><status-msg>
 *			for status:	<machine><color-code><status-msg>
 *			for summary:	<summary name><color-code><http link>
 *
 *	-		Will read from standard input a one line status
 *				message.
 */

#include "bb.h"		/* THE BIG BROTHER INCLUDE FILE */
#include <ctype.h>
#include <netdb.h>	/* SMM 1.10 FOR DDNS */

char bbprog[] = "bb";

int bbnotify(machine,data)
char *machine;				/* IP ADDRESS */
char *data;				/* DATA TO SEND ACROSS */
{
  char *bbpage = NULL;
  char *bbdisplays = NULL;
  char *bbpagers = NULL;
  char *pagelevels = NULL;
  char v1[16],v2[128],v3[16];
  int  bbsend();
  int rc = 1;
  char *datap;

  bbdisplays = (char *) getenv("BBDISPLAYS");
#if DEBUG
  debug("Sending: ** %s ** to %s - %s\n",data,machine,bbdisplays);
#endif
  rc = bbsend(machine, bbdisplays, data);     /* SEND IT ACROSS */

  /* If BBPAGE is defined then send also a msg if it's a red alert */
  /* What if BBPAGE == BBDISP ? for now send two messages */
  /* keep it simple ... */
  bbpage = (char *) getenv("BBPAGE");
  bbpagers = (char *) getenv("BBPAGERS");
  pagelevels = (char *) getenv("PAGELEVELS");
  if( ! pagelevels || (strlen(pagelevels) == 0) )
	pagelevels = PAGELEVELSDEFAULT;
  if( (bbpage != NULL) && (pagelevels != NULL) ) {
    /* %*s could have been used for v2 but */
    /* Linux thought otherwise i.e. bug or I misunderstood the %*s (skip) */
    sscanf(data,"%15s %127s %15s %*s",v1,v2,v3);
#if DEBUG
    debug("v1:[%s] v2:[%s] v3:[%s]\n",v1,v2,v3);
#endif
    if( !strncmp(v1,"status",6) ) {
      if( strstr(pagelevels,v3) ) {
        memcpy(data,"page  ",6); /* Change msg type */
	/* Get rid of expiry delay, if it's defined */
	datap = data + 6;
	if( *datap == '+' ) {
		while( *datap && !isspace(*datap) ) {
			*datap = ' ';
			datap++;
		}
	}
#if DEBUG
	debug("Sending: ** %s ** to %s - %s\n",data,bbpage,bbpagers);
#endif
	rc = bbsend(bbpage,bbpagers,data);      /* SEND IT ACROSS TO BBPAGER */
      }
    }
  }

  return(rc);
}

int main(argc, argv)
int argc;
char *argv[];
{
char data[1024];
int rc = 1;

	if (argc != 3) {
		fprintf(stderr, "bb: incorrect number of arguments\n");
		fprintf(stderr, "Format: <IP-ADDR> <DATA>\n");
		exit(1);
	}

	if( argv[2][0] == '-' ) {
#if DEBUG
	  debug("bb gets its input from stdin\n");
#endif
	  /* It expects one line messages .... */
	  while (fgets(data,sizeof(data)-1,stdin) != NULL) {
#if DEBUG
	    debug("data came in [%s]\n",data);
#endif
	    rc = bbnotify(argv[1],data);
	  }
#if DEBUG
	  debug("Done\n");
#endif
	}
	else {
	  rc = bbnotify(argv[1],argv[2]);
	}

	exit(rc);
}
