/*
   testclient.c --- example shutdown client.

   (c) Copyright 1995 SHW Wabnitz
   Written by Bernhard Fastenrath (fasten@shw.com)

   This file may be distributed under the terms
   of the GNU General Public License.
*/

#include <dos.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <exec/types.h>
#include <proto/exec.h>

#if defined (__GNUC__)
#include "shutdown_inline.h"
#else
#include "shutdown_pragmas.h"
#endif
#include "shutdown.h"
#include "ups.h"

struct Library *ShutdownBase = NULL;
struct MsgPort *prt = NULL;

int
SigBreakHandler (void)
{
  struct Message *msg;

  if (ShutdownBase)
  {
    if (prt)
    {
      Forbid ();
      while (msg = GetMsg (prt))
        ReplyMsg (msg);
      RemShutdownPort (prt);
      DeleteMsgPort (prt);
      Permit ();
    }
    CloseLibrary (ShutdownBase);
  }
  exit (EXIT_SUCCESS);
  return 0;
}

int
main (int argc, char *argv[])
{
  ShutdownMessage *sm;
  UpsInfo *ups;
  char *UpsEvents[] = UPS_EV_NAMES;

#if !defined (__GNUC__)
  onbreak (SigBreakHandler);
#endif
  if (!(ShutdownBase = OpenLibrary ("shutdown.library", 0)))
  {
    printf ("Failed to open shutdown.library.\n");
    return EXIT_FAILURE;
  }
  if (prt = CreateMsgPort ())
  {
    if (AddShutdownPort (prt))
    {
      while (1)
      {
	printf ("... waiting\n");
	WaitPort (prt);
#if !defined (__GNUC__)
	chkabort ();
#endif
	if (sm = (ShutdownMessage *) GetMsg (prt))
	{
	  switch (sm -> sm_Status)
	  {
	    case SHUTDOWN_WARN:
	      printf ("Shutdown announced.\n");
	      break;
	    case SHUTDOWN_INFO:
	      if (sm -> sm_Info == SDM_UPS_MONITOR)
              {
	        printf ("Shutdown info received:\n");
                ups = sm -> sm_Extra;
                if (ups -> ui_Event > UPS_EV_MAX)
                  printf ("Event = %d (unknown)\n", ups -> ui_Event);
                else
                  printf ("Event = %s.\n", UpsEvents[ups -> ui_Event]);
	        printf ("Charge = %d.\n", ups -> ui_Charge);
	        printf ("Remaining time = %d.\n", ups -> ui_Time);	        
              }
	      else
	        printf ("Shutdown info received.\n");
	      break;
	    case SHUTDOWN_ABORT:
	      printf ("Shutdown has been aborted.\n");
	      RemShutdownPort (prt);   /* prevent new messages */
	      ReplyMsg ((struct Message *) sm);
	      DeleteMsgPort (prt);
	      CloseLibrary (ShutdownBase);
	      exit (EXIT_SUCCESS);
	    case SHUTDOWN_UMOUNT:
	      printf ("Unmounting filesystems.\n");
	      break;
	    case SHUTDOWN_NOW:
	      printf ("Shutdown now!\n");
	      break;
	    case SHUTDOWN_HALT:
	      printf ("Shutdown done, system halted.\n");
	      break;
	    default:
	      printf ("Unknown message.\n");
	      break;
	  }
	}
	ReplyMsg ((struct Message *) sm);
      }
    }
    DeleteMsgPort (prt);
  }
  CloseLibrary (ShutdownBase);
  exit (EXIT_FAILURE);
}
