/* AddDesc for AXsh v1.0 by Guru Gnosis Sahib */

#include <stdio.h>
#include <string.h>
#include <libraries/dos.h>
#include <dos/var.h>
#include <dos/dostags.h>

main(int argc, char *argv[])
{
	FILE *input, *output;
	BPTR lock;
	char ulpath[80], descpath[80], filename[80], fullfile[80],
		temp[80], temp2[80];
	int success, nofile, superuser = FALSE;

	success = GetVar("accesslevel", temp, 80, GVF_LOCAL_ONLY);
	if(!stricmp(temp, "superuser") || !stricmp(temp, "wizard") ||
	    !stricmp(temp, "assistant") || !stricmp(temp, "system"))
		superuser = TRUE;

/* Open up config files and set things up */

	puts("AddDesc for AXsh v1.0 by Guru Gnosis Sahib");
	if(argc != 2 && superuser == FALSE)
	{
		puts("Usage: AddDesc <filename>\n");
		exit(0);
	}
	strcpy(filename, argv[1]);
	strcpy(ulpath, "Storage:Temp/");

	if(!(input = fopen("AXsh:etc/rc.ffe", "r")))
	{
		puts("AddDesc: AXsh:etc/rc.ffe not found");
		exit(0);
	}
	while(!feof(input))
	{
		fgets(temp, 80, input);
		if(temp[0] == '%')
		{
			if(!(strnicmp(temp, "%descpath:", 9)))
			{
				fscanf(input, "%s", descpath);
				break;
			}
		}
	}
	fclose(input);

/* The main loop */

	if(argc != 2)
	{
		puts("\nEnter name of uploaded file: (ENTER to finish)");
		gets(filename);
		if(!strcmp(filename, ""))
		{
			puts("Aborted.");
			exit(0);
		}
	}
	strcpy(fullfile, ulpath);
	strcat(fullfile, filename);
	lock = Lock(fullfile, ACCESS_READ);
	nofile = FALSE;
	if(lock == 0)
	{
		strcpy(fullfile, filename);
		lock = Lock(fullfile, ACCESS_READ);
		if(lock == 0)
		{
			puts("File not found!");
			nofile = TRUE;
		}
	}
	if(lock != 0 || superuser == TRUE)
	{
		UnLock(lock);
		sprintf(temp, "%s%s.dsc", descpath, filename);
		lock = Lock(temp, ACCESS_READ);
		UnLock(lock);
		if(lock != 0)
		{
			puts("Description written already!");
			if(superuser == TRUE)
			{
				puts("Overwrite description? (y/N)");
				fgets(temp2, 80, stdin);
				if(!strnicmp(temp2, "y", 1)) lock = 0;
			}
		}
		if(lock == 0)
		{				
			if(!(output = fopen(temp, "w")))
			{
				puts("AddDesc: Could not open description file");
				exit(0);
			}
			puts("Enter a description for the file: (ENTER alone to finish)");
			while(strcmp(temp, ""))
			{
				gets(temp);
				fprintf(output, "%s\n", temp);
			}
			fclose(output);
			if(nofile == FALSE)
			{
				sprintf(temp, "touch >NIL: \"%s\"", fullfile);
				success = System(temp, TAG_END);
				sprintf(temp, "protect >NIL: \"%s\" +rwed", fullfile);
				success = System(temp, TAG_END);
			}
		}
	}
	exit(0);
}
