wsh/
wsh/binsrc/
wsh/docs/help/
wsh/docs/old/
wsh/etc/
wsh/src/util/
/*  This program connects to a disconnected bgtcli session. 
		-Sam Lantinga	1/20/93
*/

#include <stdio.h>
#include <signal.h>

extern char *getenv();

int  israw=0;
char sigfile[18], holdfile[18];

void cleanup()
{
	unlink(sigfile);

	if ( israw )
		tty_reset(0);
	exit(1);
}


main(argc, argv)
int argc;
char *argv[];
{
	int pid;
	char *user;
	FILE *info;

	if ( ! isatty(1) )
	{
		fprintf(stderr, "Standard input must be a tty.\n");
		exit(1);
	}
	else
	{
		if ( (user=getenv("LOGNAME")) == NULL )
		{
			fprintf(stderr, 
		"The 'LOGNAME' environment variable is not set.\n");
			exit(1);
		}
		sprintf(holdfile, "/tmp/%s.fg", user);
		if ( (info=fopen(holdfile, "r")) == NULL )
		{
			fprintf(stderr, "Can't find an active process.\n");
			exit(3);
		}
		else
		{
			fscanf(info, "%d", &pid);
			fscanf(info, "%d", &israw);
			fclose(info);
		}
	}

	sprintf(sigfile, "/tmp/%s.sig", user);
	if ( (info=fopen(sigfile, "w")) == NULL )
	{
		perror(sigfile);
		exit(2);
	}
	else
	{
		fprintf(info, "%s\n%d\n", ttyname(1), getpid());
		fclose(info);
#ifdef OLDDEBUG
		sleep(60);
#endif
	}

	signal(SIGINT, cleanup);
	signal(SIGQUIT, cleanup);
	signal(SIGTERM, cleanup);
	signal(SIGHUP, cleanup);

	if ( israw )
	{
		tty_getmode(0);
		tty_raw(0);
	}

	if ( kill(pid, SIGUSR2) < 0 )
	{
		perror("Can't connect to process");
		fprintf(stderr, "\r");

		unlink(holdfile);
		cleanup();
	}

	pause();
	cleanup();
}