/*
   shutdown delay example
*/

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

char *ShutdownPortname = "Shutdown";

ULONG
PutAndGet (struct Message *msg, char *portname)
{
  struct MsgPort *prt, *reply_port;

  if (!(reply_port = CreateMsgPort ()))
    return 1;
  msg -> mn_ReplyPort = reply_port;

  Forbid ();
  if (prt = FindPort (portname))
  {
    PutMsg (prt, msg);
    Permit ();
    do
      WaitPort (reply_port);
    while (!GetMsg (reply_port));
  }
  else
    Permit ();

  DeleteMsgPort (reply_port);
  return (ULONG) (prt ? 0 : 2);
}

void
DelayShutdown (BYTE delay)
{
  struct Message *msg;

  if (!(msg = AllocMem (sizeof (struct Message), MEMF_PUBLIC | MEMF_CLEAR)))
  {
    printf ("Out Of Memory.\n");
    exit (0);
  }
  msg -> mn_Node.ln_Pri = delay;

  switch (PutAndGet (msg, ShutdownPortname))
  {
    case 0:
      if (msg -> mn_Node.ln_Name == (APTR) -1)
        printf ("Delay refused.\n");
      else if (msg -> mn_Node.ln_Pri < delay)
        printf ("Delay successful (but only %d seconds).\n", msg -> mn_Node.ln_Pri);
      else
        printf ("Delay successful (%d seconds).\n", msg -> mn_Node.ln_Pri);
      break;
    case 1:
      printf ("Can't allocate port.\n");
      break;
    case 2:
      printf ("Shutdown is not running.\n");
      break;
  }
  FreeMem (msg, sizeof (struct Message));
}

int
main (int argc, char *argv[])
{
  int delay;

  if (argc != 2)
  {
    printf ("Usage: %s <seconds>.\n", argv[0]);
    exit (20);
  }
  delay = atoi (argv[1]);
  if (delay < 1 || delay > 127)
  {
    printf ("The argument must be in the range 1..127.\n");
    exit (20);
  }
  DelayShutdown ((BYTE) delay);
  exit (0);
}
