/*
**	$RCSfile: SysLog.c,v $
**	$Filename: SysLog.c $
**	$Revision: 0.1 $
**	$Date: 1995/02/18 17:33:51 $
**
**	sysmon.library support command SysLog (version 0.3) 
**	
**	(C) Copyright 1995 by Etienne Vogt
*/

#include <exec/alerts.h>
#include <dos/dos.h>
#include <workbench/startup.h>
#define __USE_SYSBASE
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>
#include <stdlib.h>
#include "sysmon.h"
#include "sysmon_protos.h"
#include "sysmon_pragmas.h"

struct ExecBase *SysBase;
struct DosLibrary *DOSBase;
struct Library *SysmonBase;
static struct WBStartup *wbmsg;
static struct RDArgs *myrda;

ULONG __saveds main(void);
static void cleanexit(ULONG rc);
static BOOL SysLog(ULONG priority, APTR format, ...);

static UBYTE version[] = "$VER: SysLog 0.3 (8.10.95)";
static UBYTE template[] = "MESSAGE/A,LEVEL/K/N,NOHEAD/S,NOWIN/S,NOFILE/S";

#define OPT_MESSAGE	0
#define	OPT_LEVEL	1
#define OPT_NOHEAD	2
#define	OPT_NOWIN	3
#define	OPT_NOFILE	4
#define OPTMAX		5

ULONG __saveds main(void)	/* No startup code */
{
  struct Process *myproc;
  LONG opts[OPTMAX];
  ULONG level;

  SysBase = *(struct ExecBase **)4;
  DOSBase = NULL;
  SysmonBase = NULL;
  wbmsg = NULL;
  myrda = NULL;

  myproc = (struct Process *)FindTask(NULL);
  if ((DOSBase = (struct DosLibrary *)OpenLibrary("dos.library",36)) == NULL)
  { Alert(AT_Recovery|AG_OpenLib|AO_DOSLib);
    return 100;
  }

  if (!(myproc->pr_CLI))		/* If started from WB, exit cleanly */
  { WaitPort(&(myproc->pr_MsgPort));
    wbmsg = (struct WBStartup *)GetMsg(&(myproc->pr_MsgPort));
    cleanexit(20);
  }
  else
  { memset((char *)opts, 0, sizeof(opts));
    if ((SysmonBase = OpenLibrary("sysmon.library",0)) == NULL)
    { Printf("SysLog : Couldn't open sysmon.library\n");
      cleanexit(20);
    }
    if ((myrda = ReadArgs(template, opts, NULL)) == NULL)
    { PrintFault(IoErr(),NULL);
      cleanexit(20);
    }
    if (opts[OPT_LEVEL]) level = *((ULONG *)opts[OPT_LEVEL]);
    else level = LOG_DEBUG;

    if (opts[OPT_NOHEAD]) level |= LOG_NOHEAD;
    if (opts[OPT_NOFILE]) level |= LOG_NOFILE;
    if (opts[OPT_NOWIN]) level |= LOG_NOWIN;

    if (!SysLog(level, "%s\n", (APTR)opts[OPT_MESSAGE]))
    { Printf("SysLog : Error sending message\n>%s\n",(STRPTR)opts[OPT_MESSAGE]);
      cleanexit(10);
    }
  }
  cleanexit(0);
}

static void cleanexit(ULONG rc)
{
  if (myrda) FreeArgs(myrda);
  if (DOSBase) CloseLibrary((struct Library *)DOSBase);
  if (SysmonBase) CloseLibrary(SysmonBase);
  if (wbmsg)
  { Forbid();
    ReplyMsg((struct Message *)wbmsg);
  }
  Exit(rc);
}

static BOOL SysLog(ULONG priority, APTR format, ...)
{ return smVSysLog(priority, format, &format + 1);
}
