/*
**	$RCSfile: Halt.c,v $
**	$Filename: Halt.c $
**	$Revision: 0.1 $
**	$Date: 1995/04/15 17:33:51 $
**
**	sysmon.library support command Halt (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 "sysmon.h"
#include "sysmon_protos.h"
#include "sysmon_pragmas.h"
#include <string.h>

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

static UBYTE version[] = "$VER: Halt 0.3 (5.8.95)";
static UBYTE template[] = "REBOOT/S,REKICK/S";

#define	OPT_REBOOT	0
#define	OPT_REKICK	1
#define OPTMAX		2

ULONG __saveds main(void);
static void cleanexit(ULONG rc);
static void KPrintf(STRPTR fmt, ...);

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

  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
  { if ((SysmonBase = OpenLibrary("sysmon.library",0)) == NULL)
    { Printf("Halt failed : Couldn't open sysmon.library\n");
      cleanexit(20);
    }
    memset((char *)opts, 0, sizeof(opts));
    if ((myrda = ReadArgs(template, opts, NULL)) == NULL)
    { PrintFault(IoErr(),"Halt failed");
      cleanexit(20);
    }
    if (opts[OPT_REBOOT]) flags |= HALTF_REBOOT;
    if (opts[OPT_REKICK]) flags |= HALTF_REKICK;
    KPrintf("\a\a\aSystem going down...");
    smHalt(flags);			/* Never returns...	*/
  }

  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 void KPrintf(STRPTR fmt, ...)
{ smVKPrintf(fmt, &fmt + 1);
}
