#include "wand_head.h"
#include <sys/types.h>
#include <sys/stat.h>

#define PASS "cleverlights"

long dictsize = 0L;
FILE *dictfp;

void scrn_passwd(num, passwd)	/* reads password num into passwd */
int num;
char *passwd;
{
    long position;

    position = PASSWD;
    while (position >= dictsize)
	position -= dictsize;
    fseek(dictfp,position,SEEK_SET);
    while (fgetc(dictfp) != '\n' && !feof(dictfp));
    /* read a word into passwd */
    if (fscanf(dictfp,"%s\n",passwd) == EOF) {
	rewind(dictfp);
	fscanf(dictfp,"%s\n",passwd);
    }
}

main(argc, argv)
int argc;
char *argv[];
{
    int scr, position, mpw = 0;
    char pass[20];
    char pw[100];
    struct stat *statbuf;

    if(argc < 2) {
	printf("Usage: %s screen1 screen2 ...\n",argv[0]);
	exit(-1);
    }

/* bjr@watserv1.waterloo.edu, added the following to fix password searching.
   To properly search the 'words' dictionary, the size of the file
   is needed.  As a result, there are now five conditions (there were
   originally two,) under which passwords will be disabled.
	1. The program was run with flag -e (screen editor)
	2. The file no_pws is present in the screens directory
	3. A stat() call on the dictionary file fails
	4. The dictionary file cannot be opened using fopen()
	5. The dictionary is empty (0 bytes)
   The variable no_passwords has been replaced by dictsize.  If
   dictsize = 0, passwords are disabled. */

    if (!stat(DICTIONARY, statbuf))	/* if we can stat dictionary */
	if ((dictfp = fopen(DICTIONARY, "r")) != NULL)	/* and open */
	    dictsize = statbuf->st_size;	/* save size */
    if (!dictsize) {
	printf("%s: Cannot access %s.\n",argv[0],DICTIONARY);
	fclose(dictfp);
	exit(-1);
    }

    position = 0;
    while (++position < argc) {
	if (atoi(argv[position])<1) {
	    printf("Option not known: %s.\n",argv[position]);
	    continue;
	}
	scr = atoi(argv[position]);
	if ((scr < 100) && (mpw == 0)) {
	    printf("You need clearance to see passwords below 100.\n");
	    printf("Enter master password:");
	    scanf("%s",pw);
	    if (strncmp(pw,PASS,strlen(PASS))) {
		printf("Foo, charlatan!\n");
		exit(-1);
	    }
	    mpw = 1;
	}
        scrn_passwd((scr-1),pass);
	printf("Screen %d password is '%s'.\n",scr,pass);
    }
#ifdef TOS
    if (!strcmp(argv[0], "")) {	/* probably run from the desktop */
	char c;
	printf("Press any key to end...");
	fflush(stdout);
	c = console_read_byte(stdin);
    }
#endif	/* TOS */
}
