/* execdacp.c - DACP to NewCLI */

/* Date Written: 01/28/87
** Author: Tim Holloway
**
** Description: spawns a New CLI upon reciept of a signal from system
** accessory control.
**
** Quirks:
**
** This program cannot be shut down - you must reboot to do so.
** While this is generally a tacky practice, this accessory is likely to
** be used so frequently that you would probably not want to do so unless
** system resources (primarily memory) were so tight that a reboot to
** clear the decks would be desirable anyway.
*/

#include <exec/types.h>
#include <exec/exec.h>
#include <exec/alerts.h>
#include <exec/libraries.h>
#include <intuition/intuition.h>
#include "dacp.h"

#define PGMID "Pop-up NewCLI:"		/* ID for Gripes */
#define ACCESSORY_ID "NewCLI"

/* struct Library* IntuitionBase; */
/* extern struct Library* OpenLibrary(TEXT *, int); */

DACPmsg log_dacp =
{
   {
      {NULL, NULL, NT_MESSAGE, 0, ACCESSORY_ID },	/* Node */
      NULL, sizeof(DACPmsg)				/* Message */
   },
   0L, LOGIN_DACP				/* user stuff */
};

#define IREV 0		/* any old Intuition should do */

extern struct MsgPort *CreatePort(char *, int), *FindPort(char *);
struct MsgPort *mp, *mp1;
LONGBITS DACPsignal = 0;
int DACPSigNum;

static void
go_away(error_severity)
int error_severity;
{
	if (mp1 != NULL) DeletePort(mp1);
	if (IntuitionBase != NULL) CloseLibrary(IntuitionBase);
	Exit(error_severity);
}

main()
{

/*
** NOTE: the the second parameter of the Alert() function is (apparently)
** undefined.  If if was up to me, it would be a string to be displayed,
** saying: "Pop-up NewCLI couldn't open the Intuition Library".
*/

	if ( (IntuitionBase =
		 OpenLibrary("intuition.library", IREV)) == NULL
	   )
	{
		Alert (AT_Recovery + AG_OpenLib + AO_Intuition, NULL);
		Exit(20); /* nothing was opened yet */
	}

	if ( (mp1 = CreatePort(NULL, 0)) == NULL)
	{
		Gripe (PGMID, "Couldn't create reply port.", "");
		go_away(20);
	}

	log_dacp.msg.mn_ReplyPort = mp1;

	DACPSigNum = AllocSignal(-1);
	log_dacp.sigbits =
		DACPsignal =  1L << DACPSigNum;
	if (DACPsignal == -1)
	{
		Gripe (PGMID, "Could not get a Signal.",
			 "(is AmigaDOS OK?)");
		go_away(20);
	}
/* SHOULD TEST TO SEE IF WE GOT SIGNAL HERE... */
	log_dacp.log_status = LOGIN_DACP;


    /******* CAUTION - turning multitasking OFF *****************/
	Forbid();		
	mp = FindPort(LOGPORTNAME);

	if (mp == NULL)
	{
		Permit();
		Gripe ( PGMID, 
			"DACP must be inactive,",
			"(Couldn't find message port).");
		go_away(20);
	}
	else
	{
		PutMsg(mp, &log_dacp);
		Permit();		/* Restore multitasking */
		WaitPort(mp1);
	}

	/* The only message that should EVER show on mp1 should be
	   the returning log message!
	 */
	(void) GetMsg(mp1);
	if (log_dacp.log_status != LOGIN_DACP)	/* Login failed */
	{
		Gripe(PGMID, "couldn't connect to", "accessory control.");
		go_away(1);
	}

	FOREVER
	{
		register int i;

		i = Wait(DACPsignal);
		Execute ("NewCLI", NULL, NULL);
	}
}
