/*
**	$RCSfile: ValidateWait.c,v $
**	$Filename: ValidateWait.c $
**	$Revision: 0.1 $
**	$Date: 1995/01/22 17:33:51 $
**
**	Wait for a volume to be validated by the file system (version 0.2)
**	
**	(C) Copyright 1995 by Etienne Vogt
*/

#include <exec/alerts.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/dostags.h>
#include <workbench/startup.h>
#define __USE_SYSBASE
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>

struct ExecBase *SysBase;
struct DosLibrary *DOSBase;
static struct WBStartup *wbmsg;
static struct RDArgs *myrda;

static UBYTE version[] = "$VER: ValidateWait 0.2 (5.8.95)";
static UBYTE template[] = "DRIVE/A,TIMEOUT/K/N";

#define	OPT_DRIVE	0
#define	OPT_TIMEOUT	1
#define OPTMAX		2

ULONG __saveds main(void);
static void cleanexit(ULONG rc);

ULONG __saveds main(void)	/* No startup code */
{
  struct Process *myproc;
  LONG opts[OPTMAX];
  ULONG rc = 0;

  SysBase = *(struct ExecBase **)4;
  DOSBase = NULL;
  wbmsg = NULL;
  myrda = NULL;

  myproc = (struct Process *)FindTask(NULL);
  if ((DOSBase = (struct DosLibrary *)OpenLibrary("dos.library",36)) == NULL)
  { Alert(AT_Recovery|AG_OpenLib|AO_DOSLib);
    return 100;
  }

  if (!(myproc->pr_CLI))		/* If started from WB, exit cleanly */
  { WaitPort(&(myproc->pr_MsgPort));
    wbmsg = (struct WBStartup *)GetMsg(&(myproc->pr_MsgPort));
    cleanexit(20);
  }
  else
  { BPTR lock;
    struct InfoData *info;
    int timeout, count = 0;

    memset((char *)opts, 0, sizeof(opts));
    if ((myrda = ReadArgs(template, opts, NULL)) == NULL)
    { PrintFault(IoErr(),"ValidateWait");
      cleanexit(20);
    }
    if (opts[OPT_TIMEOUT]) timeout = *((LONG *)opts[OPT_TIMEOUT]);
    else timeout = 300;

    if ((lock = Lock((STRPTR)opts[OPT_DRIVE], SHARED_LOCK)) == NULL)
    { PrintFault(IoErr(),"ValidateWait");
      cleanexit(10);
    }
    if ((info = AllocVec(sizeof(struct InfoData), MEMF_PUBLIC)) == NULL)
    { Printf("ValidateWait : No memory for InfoData.\n");
      UnLock(lock);
      cleanexit(20);
    }

    do
    { if (Info(lock, info) == DOSFALSE)
      { PrintFault(IoErr(),"ValidateWait");
	UnLock(lock);
	FreeVec(info);
	cleanexit(10);
      }
      if (info->id_DiskState != ID_VALIDATING) break;
      else Delay(TICKS_PER_SECOND);
      if (CheckSignal(SIGBREAKF_CTRL_C)) count = timeout;
    } while (++count < timeout);

    if (count >= timeout)
    { Printf("ValidateWait : Volume Validation timed out.\n");
      rc = 10;
    }
    UnLock(lock);
    FreeVec(info);
  }
  cleanexit(rc);
}

static void cleanexit(ULONG rc)
{
  if (myrda) FreeArgs(myrda);
  if (DOSBase) CloseLibrary((struct Library *)DOSBase);
  if (wbmsg)
  { Forbid();
    ReplyMsg((struct Message *)wbmsg);
  }
  Exit(rc);
}
