/* WaitDCF77ifCrash                                                 ***RGR***

   Author:   Ralf Gruner, An der Sense 5a, D-02779 Großschönau, Germany.
*/

#include <exec/types.h>
#include <exec/semaphores.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <stdio.h>

BPTR	DateFile =NULL;
char *filename1	="ENVARC:LastBootDate";
BPTR	CONWin =NULL;
char *filename2	="CON:20/20/280/80/WaitDCF77ifCrash/AUTO";

char *version="$VER: WaitDCF77ifCrash 1.03 (4.1.96)";

struct StatusList
{
	struct SignalSemaphore sl_Semaphore;
	STRPTR version;
	BOOL Received;
};

struct StatusList *DCF77PublicStatus=NULL;

UBYTE	* DCF77SemaphoreName = "DCF77 State";
BOOL	DCF77received=FALSE;

main(int argc, char *argv[])
{
	struct DateStamp DS, DSfromFile;
	long bytes;
	char *msg1="";
	char *msg2=	" © 1994-1996 Ralf Gruner, Großschönau, Germany.\n\n"
					" WaitDCF77ifCrash waits for received time from DCF77\n if the date of your hardware clock has been corrupted.\n"
					" Usage: Place it in a script above your date sensitive application.\n\n";

	if(argc != 1)
	{
		puts(msg1);
		puts(version+5);
		puts(msg2);
	}
	else
	{
		DateStamp((struct DateStamp *)&DS);	// Systemzeit in Struktur eintragen
		
		if (NULL!=(DateFile = Open(filename1,MODE_OLDFILE)))
		{
			bytes = Read(DateFile,&DSfromFile,(LONG)sizeof(struct DateStamp));
			Close(DateFile);
	
			if (bytes != (LONG)sizeof(struct DateStamp))
			{
				DSfromFile.ds_Days=0;
			}
	
		}
		else
			DSfromFile.ds_Days=0;

		if(DSfromFile.ds_Days > DS.ds_Days || DSfromFile.ds_Days < DS.ds_Days-182)
		{
			Delay(500L);	// ggf. auf Workbench-Window warten
			if (NULL!=(CONWin = Open(filename2,MODE_NEWFILE)))
				FPrintf(CONWin,"\n\n Waiting for DCF77...\n\n");

			while(!DCF77received)
			{
				Forbid();
				if(DCF77PublicStatus=(struct StatusList *) FindSemaphore(DCF77SemaphoreName))
				{
					ObtainSemaphoreShared((struct SignalSemaphore *) DCF77PublicStatus);
					DCF77received=DCF77PublicStatus->Received;
					ReleaseSemaphore((struct SignalSemaphore *) DCF77PublicStatus);
				}
				else
					DCF77received=FALSE;	// DCF77 läuft nicht
				Permit();
	
				if(!DCF77received)
					Delay(100L);	// zwei Sekunden warten und dann erneut testen
			}

			DateStamp((struct DateStamp *)&DS);	// neue Systemzeit in Struktur eintragen

			if(CONWin)
			{
				FPrintf(CONWin," O.K.\n");
				Delay(150L);
				Close(CONWin);
			}
		}

		if(DSfromFile.ds_Days != DS.ds_Days)
		{
			// nur speichern, wenn Tag geändert
			if (NULL!=(DateFile = Open(filename1,MODE_NEWFILE)))
			{
				bytes = Write(DateFile,&DS,(LONG)sizeof(struct DateStamp));
				if (bytes != (LONG)sizeof(struct DateStamp))
				{
					puts("Error while writing");
				}
				Close(DateFile);
			}
		}
	}
}

