/* MOUNTED -- is a disk mounted?
 *
 * Copyright 1987 by Peter da Silva.
 *
 * This code may be freely distributed provided this notice is
 * retained. It may be hacked, munged, and incorporated in commercial
 * software if you want, so long as you credit me for it.
 */
#include <stdio.h>
#include <ctype.h>
#include <libraries/dosextens.h>

struct DosLibrary *DosLibrary;

/* hack BPTRS */

#define toAPTR(b) ((b)<<2)
#define toBPTR(a) ((a)>>2)

#define VOLUMES 16 /* If you have more than 16 drives, tough luck :-> */
char volumes[VOLUMES][33];
int nvols;

main(ac, av)
int ac;
char **av;
{
	GetVolumes();
	if(ac==0) wbmain(); /* I think this should work with Lattice */
	else if(ac==1) dumpvols();
	else if(ac==2 && av[1][0] != '?')
		exit(mounted(av[1])?0:5); /* Code 5 is warn */
	else {
		/* should loop & return success only if all work. */
		printf("MOUNTED Copyright (c) 1987 by Peter da Silva.\n");
		printf("Usage: mounted [volumename]\n");
		printf("Returns error code 5 is volume is not mounted.\n");
		exit(10); /* code 10 is error. maybe Should be 20 (fatal). */
	}
	exit(0);
}

GetVolumes() /* who'se out there */
{
	struct RootNode *root;
	struct DosInfo *info;
	struct DeviceList *list;

	DosLibrary = OpenLibrary("dos.library", 0);
	if(!DosLibrary) {
		printf("Can't open dos.library\n");
		exit(2);
	}
	nvols = 0;

	/* The following 3 lines caused me some worry, but they worked
	   first time. Thank you C=Amiga. */
	root = DosLibrary -> dl_Root;
	info = toAPTR(root->rn_Info);
	list = toAPTR(info->di_DevInfo);
	while(list) {
		if(list->dl_Type == DLT_VOLUME && /* is it a device? */
		   list->dl_Task != 0) { /* Ignore unmounted devices */
			char *ptr;
			int count;
			ptr = toAPTR((BPTR)list->dl_Name);
			count = *ptr++;
			if(count > 16) /* Should be a CONSTANT */
				count = 16;
			strncpy(volumes[nvols], ptr, count);
			volumes[nvols][count] = 0;
			nvols++;
		}
		list = toAPTR(list->dl_Next);
	}
	CloseLibrary(DosLibrary);
}

wbmain(dummy) /* if run from workbench, just list mounted volumes */
{
	FILE *fp;
	if(!(fp = fopen("CON:160/50/320/100/Mounted volumes.")))
		return;
	fdumpvols(fp);
	sleep(10);
	fclose(fp);
}

sleep(n) /* This should have been provided by Aztec, for god's sake. */
{
	Delay(50*n);
}

dumpvols()
{
	fdumpvols(stdout);
}

fdumpvols(fp)
FILE *fp;
{
	int i;
	for(i = 0; i < nvols; i++)
		printf("%s\n", volumes[i]);
}

mounted(name) /* The biggee */
char *name;
{
	int i;
	for(i = 0; i < nvols; i++)
		if(streq(volumes[i], name))
			return 1;
	return 0;
}

streq(s1, s2)
char *s1, *s2;
{
	normalise(s1);
	normalise(s2);
	return strcmp(s1, s2)==0;
}

normalise(s)
char *s;
{
	int i;
	for(i = 0; s[i]; i++)
		if(isupper(s[i]))
			s[i] = tolower(s[i]);
		else if(s[i]==':') {
			s[i] = 0;
			break;
		}
}
