#include <exec/types.h>
#include <exec/exec.h>
#include <stdio.h>
#include <stdlib.h>
#include <functions.h>
#include "work:romconf/doorheader.h"
#define NL NULL
static struct FileLock      *pdir = NL;
static struct FileInfoBlock *dir_info = NL;
void Convert_CTime_To_Date(char *Wstr, char *Wfmtstr, char *DT_temp);
void DoIt();
int EnterDesc(char *FileName,long fsize,int dirnum);
void free_pdir();
void end();
#define gu getuserstring
#define GU gu
#define pm prompt
#define sm sendmessage
#define hk hotkey
char GSTR1[200];
char GSTR3[200];
char GSTR2[200];
long MoveFile(char *Path,char *filename,long filesize,char *Conference_Location);
long FileCopy(char *s,char *d);
long DynAllocate(char **pbuf,long maxbufsize);
long RFreeSpace(char *path);
void MemoryError(void);

main(int argc,char *argv[])
{
  char CMD[200];
  char Access[20];
  char FileName[200];
  
  if(argc!=2)
  {
    printf("SysUp v1.2, written by Joseph Hodge\n");
    printf("This is an AmiExpress v1.1w+ module\n");
    exit(0);
  }
  Register(argv[1][0]-'0');
  gu(CMD,DT_NAME);
  gu(Access,DT_SECSTATUS);

  sm("",1);
  sm("[36mLocal Sysop upload v1.2, [32mwritten by Joseph Hodge[0m",1);

  DoIt();
  Logoff();
}

void DoIt()
{
  char Dir[100];
char Path[200];
  FILE *fi,*fo;
  int ndir;
  int First=1;
  char DirName[200];
  int EnterD=0;
  int MoveFiles=0;
  int GotSome=0;
  char BBSZOOM[200];
  char Conference_Location[200];
  gu(Dir,BB_CONFLOCAL);
  strcpy(Conference_Location,Dir);
  gu(BBSZOOM,BB_LOCAL);
  strcat(BBSZOOM,"Zoom/Sysup.data");
  strcat(Dir,"ndirs");
  fi=fopen(Dir,"r");
  if(fi==NULL)
  {
    sm("[33mFiles are not supported in this conference.",1);
    return;
  }
  fgets(Dir,80,fi); fclose(fi);
  ndir=atoi(Dir);
  sm("",1);
  hk("[36mWould you like to enter file descriptions for the files [[32mY[33m/[37mn[36m] >:[0m",Dir);
  if(Dir[0]=='N' || Dir[0]=='n') sm("[37mNo.[0m",1);
  else { sm("[32mYes.[0m",1); EnterD=1; }
  
  if(EnterD)
  {
    sprintf(Dir,"[36mThere are [31m%d [36mDir listings in this conference.",ndir);
    sm(Dir,1);
    sm("[33mWhich Dir listing would you like to Update [36m>:",0);
    pm("",Dir,3);
    if(atoi(Dir)>ndir || atoi(Dir)<1)
    {
      sm("",1);
      sm("[31mThat Dir listing does not exist![0m",1);
      return;
    }
    ndir=atoi(Dir);
    GU(Dir,BB_CONFLOCAL);
    sprintf(DirName,"%sdir%d",Dir,ndir);
  }
  sm("",1);
  hk("[36mWould you like the files moved to ULpath [[32mY[33m/[37mn[36m] >:[0m",Dir);
  if(Dir[0]=='N' || Dir[0]=='n') sm("[37mNo.[0m",1);
  else { sm("[32mYes.[0m",1); MoveFiles=1; }
  if(!MoveFiles && !EnterD)
  {
    sm("[33mAborting Local Sysop upload no options selected![0m",1);
    Logoff();
  }
 
  sm("[33mPlease specify directory path which contains your local files[0m",1);  
  pm("[33mor [RETURN] to Abort >:[0m",Path,200);
  if(Path[0]=='\0') 
  {
    sm("[37mAborting![0m",1); Logoff();
  }
  if(Path[strlen(Path)-1]=='/') Path[strlen(Path)-1]='\0';
  if(access(Path,00))
  {
    sm("[34mThat path does not exist![0m",1);
    Logoff();
    
  }
  if(MoveFiles)
  {
    hk("[35mARE YOU SURE YOU WISH THE FILES MOVED? [[32mY[33m/[37mn[35m] >:",Dir);
    if(Dir[0]=='N' || Dir[0]=='n') { sm("[37mNo.[0m",1); MoveFiles=0; }
    else sm("[32mYes.[0m",1);
  }
  if(!MoveFiles && !EnterD)
  {
    sm("[33mAborting Local Sysop upload no options selected![0m",1);
    Logoff();
  }

  if ((dir_info =(struct FileInfoBlock *)AllocMem((long)sizeof(struct FileInfoBlock),0L)) == NULL)
   {
     sm("Memory Allocation Error.",1);
     Delay(300L);
     Logoff();
   }
  if (! (pdir=(struct FileLock *)Lock(Path,(ULONG)ACCESS_READ)) )
  {
    free_pdir();
     sm("Error, can't lock directory!",1);
     Logoff();
  }
  if ( ! Examine((BPTR)pdir, dir_info) )
  {
    free_pdir();
    sm("Error, can't examine directory!",1);
    Logoff();
  }
  while(ExNext((BPTR)pdir,dir_info))
  {
    if(dir_info->fib_DirEntryType < 0L )
    {
       GotSome=1;
if(First && EnterD)
      {
        sm("[0m",1);sm("Please enter a description, you have eight lines for your description.",1);
        sm("Press return alone to end.",1);
        First=0;
      }
      if(strlen(dir_info->fib_FileName)>12)
      {
        sm("[32mFile:[36m ",0);
        sm(dir_info->fib_FileName,0);
        sm("[32m is too long. Skipping",1);
      }else
      {
        if(EnterD)EnterDesc(dir_info->fib_FileName,dir_info->fib_Size,ndir);
        if(MoveFiles)MoveFile(Path,dir_info->fib_FileName,dir_info->fib_Size,Conference_Location);

      }
    }
  }
  if(GotSome==0)
  {
     sm("",1);
     sm("[34mNo Files to work.",1);
     sm("",1);
     Logoff();
  }
      
  

}

int EnterDesc(char *FileName,long fsize,int dirnum)
{
   FILE *fi;
   char str[200];
   char Istr[200];
   char fmtstr[200];
   char temp[80],str2[255];
   char odate[20],fcomment[70],scomment[9][50];
   long Time_system;
   int status;
   int x2;
   Time_system=time(NULL);
   sprintf(fmtstr,"%s",ctime(&Time_system));
   Convert_CTime_To_Date(fmtstr,odate,temp);
   sm("[0m",0);
   while(1)
   {			
				sm("[36m                                [--------------------------------------------]",1);
				sprintf(fmtstr,"[33m%-13s [35m%7ld  [32m%s :[0m",FileName,fsize,odate);
				sm(fmtstr,0);
                    sprintf(fmtstr,"%-13sP%7ld  %s  ",FileName,fsize,odate);
				pm("",fcomment,44);
				if(strlen(fcomment)==0) { continue; }
                    strcat(fmtstr,fcomment); strcpy(fcomment,fmtstr);
				x2=0;
                        do
					{
					sm("                               [32m :[0m",0);
					pm("",scomment[x2],44);
					x2+=1;
					} while(strlen(scomment[x2-1])!=0&&x2<7);
                    gu(Istr,BB_CONFLOCAL);
                    sprintf(fmtstr,"%sdir%d",Istr,dirnum);
                    strcat(Istr,"Upload/");
                    strcat(Istr,FileName);
     
      break;
   }
   sm("",1);
   fi=fopen(fmtstr,"a");
   if(fi==NULL) return(1);
   dirnum=0;
   fprintf(fi,"%s\n",fcomment);
   while(dirnum<x2-1)
   {
     fprintf(fi,"                                 %s\n",scomment[dirnum]);
     dirnum++;
   }
   fclose(fi);
}

void free_pdir()
{
   if ( pdir )
      {
      UnLock((BPTR)pdir);
      pdir=NL;
       }
   return;   
}

Logoff()
{
  sm("",1);
  ShutDown();
  end();
}
void end()
{
  free_pdir();
 if(dir_info!=NL)
  {
   free_pdir();
   FreeMem(dir_info,(long)sizeof(struct FileInfoBlock));
  }
 exit(0);
}

void Convert_CTime_To_Date(char *Wstr, char *Wfmtstr, char *DT_temp)
{
int month,day,year;
char s1[10],s2[10],tempdt[30];

sscanf(Wstr,"%s %s %d %s %d",&s2,&s1,&day,&tempdt,&year);
strcpy(DT_temp,tempdt);

month=0;
if(s1[0]=='D')
	{
	month=12;
	goto NextP;
	}
if(s1[0]=='N')
	{
	month=11;
	goto NextP;
	}
if(s1[0]=='O')
	{
	month=10;
	goto NextP;
	}
if(s1[0]=='S')
	{	
	month=9;
	goto NextP;
	}
if(s1[0]=='A')
	{
	if(s1[1]=='u')
		{
		month=8;
		goto NextP;
		}
	else
		{
		month=4;
		goto NextP;
		}
	}
if(s1[0]=='J')
	{
	if(s1[1]=='a')
		{
		month=1;
		goto NextP;
		}
	else if(s1[2]=='n')
		{
		month=6;
		goto NextP;
		}
	else if(s1[2]=='l')
		{
		month=7;
		goto NextP;
		}
	}
if(s1[0]=='M')
	{
	if(s1[2]=='y')
		{
		month=5;
		goto NextP;
		}
	if(s1[2]=='r')
		{
		month=3;
		goto NextP;
		}
	}
if(s1[0]=='F')
	{
	month=2;
	}

NextP:

year-=1900;
sprintf(Wfmtstr,"%2d-%2d-%2d",month,day,year);
if(Wfmtstr[0]==' ') { Wfmtstr[0]='0'; }
if(Wfmtstr[3]==' ') { Wfmtstr[3]='0'; }
if(Wfmtstr[6]==' ') { Wfmtstr[6]='0'; }
}
long DynAllocate(char **pbuf,long maxbufsize)
{
do
	{
	*pbuf=(char *)AllocMem(maxbufsize,MEMF_FAST|MEMF_CLEAR);
	maxbufsize=maxbufsize>>1;
	} while(*pbuf==NULL&&maxbufsize>8192);
maxbufsize=maxbufsize<<1;
if(*pbuf!=NULL)
	{
	return(maxbufsize);
	}
*pbuf=(char *)AllocMem(maxbufsize,MEMF_CHIP|MEMF_CLEAR);
if(*pbuf!=NULL)
	{
	return(maxbufsize);
	}
return(0L);
}

long FileCopy(char *s,char *d)
{
UBYTE *buf;
long bufsize,stat1,stat2;
BPTR fhs,fhd;

if(bufsize=DynAllocate(&buf,1048576))
	{
	if(fhs=Open(d,MODE_OLDFILE))
		{
		Close(fhs);
		FreeMem(buf,bufsize);return(0);
		}
	if(fhs=Open(s,MODE_OLDFILE))
		{
		if(fhd=Open(d,MODE_NEWFILE))
			{
			do
				{
				stat1=Read(fhs,buf,bufsize);
				if(stat1>0)
					{
					stat2=Write(fhd,buf,stat1);
					}
				} while(stat1>0&&stat2>0);
			if(stat1<0)
				{
                    sm("",1);
				sprintf(GSTR3,"[37mERROR while reading from %s![0m",s);
                    sm(GSTR3,1);sm("",1);
				}
			if(stat2<0)
				{
                    sm("",1);
				sprintf(GSTR3,"[37mERROR while writing to %s![0m",s);
				sm(GSTR3,1);sm("",1);
				}
			Close(fhd);
			}
		Close(fhs);
		}
	FreeMem(buf,bufsize);
	}
if(stat1>=0&&stat2>=0)
	{
	return(1);
	}
return(0);
}

long MoveFile(char *Path,char *filename,long filesize,char *Conference_Location)
{
long stat,err;
FILE *f;
char *p;
char FN[200];
filesize=filesize+16384;
strcpy(FN,filename);
sprintf(GSTR3,"%sulpaths",Conference_Location);
if(f=fopen(GSTR3,"r"))
	{
	while(p=fgets(GSTR3,80,f))
		{
		GSTR3[81]='\0';
		GSTR3[strlen(GSTR3)-1]='\0'; // removes the \n at end of line
		stat=RFreeSpace(GSTR3);
		if(stat>filesize)
			{
               if(*(Path+(strlen(Path)-1))!=':')
			sprintf(GSTR1,"%s/%s",Path,filename);
               else
               sprintf(GSTR1,"%s%s",Path,filename);
			sprintf(GSTR2,"%s%s",GSTR3,filename);
			if(stat=FileCopy(GSTR1,GSTR2))
				{
				fclose(f);
				DeleteFile(GSTR1);
				sm("[36m",0);sm(filename,0); sm("[34m Posted in Directory[0m",1);
                    sm("",1);
				return(1);
				}
			}
		} while(p!=NULL);
	fclose(f);
	sm("[37mWARNING!",1);sm("No free space on any path!  Moving to upload dir...[0m",1);
	}
if(*(Path+(strlen(Path)-1))!=':')
sprintf(GSTR1,"%s/%s",Path,filename);
else
sprintf(GSTR1,"%s%s",Path,filename);
sprintf(GSTR2,"%sUPLOAD/%s",Conference_Location,filename);
		if((stat=FileCopy(GSTR1,GSTR2))) DeleteFile(GSTR1);
if(stat==NULL)
	{
	sm("[37mFAILURE!!!  unable to move file [[33m",0);
     sm(filename,0); sm("![0m",1);
     sm("",1);
	}
if(stat!=NULL)
	{
	sm("[32m",0); sm(filename,0);sm("[36m Posted in Directory[0m",1);
     sm("",1);
	return(1);
	}
return(0);
}
long RFreeSpace(char *path)
{
BPTR FLock;
struct InfoData *i_data;

long stat=0;

if(i_data=(struct InfoData *)AllocMem((long)sizeof(struct InfoData),MEMF_CHIP))
	{
	if(FLock = Lock(path,ACCESS_READ))
		{
		if(stat=Info(FLock,i_data))
			{
			stat=(i_data->id_NumBlocks*i_data->id_BytesPerBlock)-(i_data->id_NumBlocksUsed*i_data->id_BytesPerBlock);
			}
		else
			{
               sm("",1);
			sprintf(GSTR3,"[33mCan not get info from %s for free space[0m",path);
			sm(GSTR3,1);
			}
		UnLock(FLock);
		}
	else
		{
          sm("",1);
		sprintf(GSTR3,"[33mCan not find free space for %s[0m",path);
		sm(GSTR3,1);
		}
	FreeMem(i_data,sizeof(struct InfoData));
	}
else
	{
	(void)MemoryError();
	}
return(stat);
}

void MemoryError(void)
{
sm("",1);
sm("[33mCould not allocate enough memory for workspace!!![0m",1);
sm("",1);
}
