#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#define MAX_FILES 50
#define FNAME_LENGTH 255

int listdir (char *dname, char (*dest)[FNAME_LENGTH]);
int getfsize(char *dir, char* fname);

int main(int argc, char** argv)
{
	if (argc < 4)
	{
		printf("Usage: %s <interval> <btd> <queue>\n", argv[0]);
		return -1;
	}
	int interval = atoi(argv[1]);
	char *btd_path = argv[2];
	char *queue_path = argv[3];
	char btd_fnames[MAX_FILES][FNAME_LENGTH];
	char queue_fnames[MAX_FILES][FNAME_LENGTH];
	int btd_num, queue_num, i, j, fsize1, fsize2, f;
	
	char rfile[255];
	

	while (1)
	{
		btd_num = listdir(btd_path, btd_fnames);
		queue_num = listdir(queue_path, queue_fnames);
		// add to queue
		for (i = 0; i < queue_num; i++)
		{
			strcpy(rfile, "/mnt/mips/bt -a ");
			strcat(rfile, queue_path);
			strcat(rfile, queue_fnames[i]);
			printf("Adding %s\n", rfile);
			system(rfile);
		}
		// clean up
		for (i = 0; i < btd_num; i++)
		{
			fsize1 = getfsize(btd_path, btd_fnames[i]);
			f = -1;
			for (j = 0; j < queue_num; j++)
			{
				fsize2 = getfsize(queue_path, queue_fnames[j]);
				if (fsize1 == fsize2) f = j;
			}
			if (f == -1)
			{
				// remove torrent
				strcpy(rfile, btd_path);
				strcat(rfile, btd_fnames[i]);
				unlink(rfile);
				btd_fnames[i][40] = '\0';
				printf("Removing %s\n", btd_fnames[i]);
				strcpy(rfile, "/mnt/mips/bt -r ");
				strcat(rfile, btd_fnames[i]);
				system(rfile);
			}
		}
		sleep(interval);
	}
	return 0;
}

int listdir (char *dname, char (*dest)[FNAME_LENGTH])
{
	DIR *dirp;
	struct dirent *dp;
	int c = 0;

	dirp = opendir(dname);
	if (dirp == NULL) return -1;
	
	while((dp = readdir(dirp)) != NULL && c < MAX_FILES)
	{
		strcpy(dest[c], dp->d_name);
		//printf("%s\n", dest[c]);
		if (strcmp("..", dest[c]) != 0 && strcmp(".", dest[c]) != 0)
			c++;
	}
	closedir(dirp);
	return c;
}

int getfsize(char *dir, char* fname)
{
	char tmpf[FNAME_LENGTH];
	struct stat fstat;

	strcpy(tmpf, dir);
	strcat(tmpf, "/");
	strcat(tmpf, fname);
	stat(tmpf, &fstat);
	return fstat.st_size;
}

