/*  This file is part of lsnet. 

    Lsnet is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Lsnet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with lsnet.  If not, see <http://www.gnu.org/licenses/>.
*/

int netmonth() {
	gdImagePtr im; 
	FILE *out; 
	FILE* lsnetlog;  
	im = gdImageCreate(1620,255); 
        //allocate colors
        int white = gdImageColorAllocate(im, 255, 255, 255);
        int black = gdImageColorAllocate(im, 0, 0, 0);
        int red = gdImageColorAllocate(im, 255, 0, 0);
        int blue = gdImageColorAllocate(im, 0, 0, 255);
        int green = gdImageColorAllocate(im, 0, 255, 0);
        int yellow = gdImageColorAllocate(im, 255, 255, 0);
        int orange = gdImageColorAllocate(im, 255, 128, 0);
        int purple = gdImageColorAllocate(im, 255, 0, 255);
        int brown = gdImageColorAllocate(im, 128, 64, 0);
        int grey = gdImageColorAllocate(im, 128, 128, 128);


/*	int styleDashed[6];
	styleDashed[0] = blue;
	styleDashed[1] = yellow;
	styleDashed[2] = orange;
	styleDashed[3] = gdTransparent;
	styleDashed[4] = gdTransparent;
	styleDashed[5] = gdTransparent;
*/
        int styleDashed[8];
        styleDashed[0] = blue;
        styleDashed[1] = blue;
        styleDashed[2] = orange;
        styleDashed[3] = orange;
        styleDashed[4] = gdTransparent;
        styleDashed[5] = yellow;
        styleDashed[6] = gdTransparent;
        styleDashed[7] = yellow;

        gdImageSetStyle(im, styleDashed, 8);




	////declare variables

        char *token;
        char *line;
        char *search = " ";

	char temp[10];
	double days[33][2];	
	//zero initialize
	//memset ((void*) days, '0', sizeof (double) * 33 * 2);
	double infloat, outfloat;

	char linestring[1000];
	char copystr[1000];

	//char temp[30];
        char hourstr[3];
        char minstr[3];
        char secstr[3];
	char labeldate2[12];
	char labelstring[30];
	//char labelstring2[(sizeof(int) * 7) + (sizeof(char) * 7))];
	char datestrcurrent[30];	
	char monthstr[4];

	int day, month, year, numdays, lines1, lines2, lastday;
	int i;
	double width, height, height2, total1, total2;
	int lastline;
	int isam;
	int minsince;
	int minsince2;
	int lastminsince;
	
	int hour, min, sec;
	int labeldate1;
	int counter, counter2, counter3, counter4, counter5, count4;
	int modulo4;
	int coordinate = 60;
	int emptyvarstr;
        double difference = 0;
        int lastdate = 0;  
        int stagger = 230; 

	double tenth;
	double max, oldmax, netin, netout;
	double num3; 
	double num4, num5;

	//coordinate
	double downnum = 210;
	//points
	double num6 = 0;
	double num7 = 210;
	//int coresfound = coresdetected();
	//meminfo(1,memarray1);
	
	char weblocation[60];	

        struct tm *local;
        time_t t;


	//////////////




	gdImageLine(im, 50, 10, 50, 210, black);
	gdImageLine(im, 10, 210, 1500, 210, black);
	gdImageString(im, gdFontMediumBold,   1   ,   1    , "MB" , black);
	//gdImageString(im, gdFontMediumBold,   50   ,   240    , "Day" , black);
	gdImageFilledRectangle(im, 1520, 65, 1540, 85, red);
	gdImageString(im, gdFontLarge,   1545   ,   85    , "Upload" , red);
	gdImageFilledRectangle(im, 1520, 105, 1540, 125, green);
	gdImageString(im, gdFontLarge,   1545   ,   125    , "Download" , green);
	gdImageString(im, gdFontMediumBold,   1520   ,  200        , "Net Usage eth0" , black);

	//num3 = 210;
	//num4 = 0;

	max = 0;
	oldmax = 10;
	



	//get current month

	t = time(NULL);
	local = localtime(&t);
	memset ((void*) datestrcurrent, '\0', sizeof (datestrcurrent));
	strcpy(datestrcurrent, asctime(local));
	//datestrcurrent[3]='\0';

	//printf("%s\n", datestrcurrent);
	//get day number
	day = dates(datestrcurrent, 2);
	//printf("day %d\n", day);

	strcpy(datestrcurrent, asctime(local));
	//get month number
	month = dates(datestrcurrent, 1);
	//printf("month %d\n", month);
	
	//memset ((void*) labelstring, '0', sizeof (labelstring));
	//strcpy(labelstring,datestrcurrent[4]);
	//strcat(labelstring,datestrcurrent[5]);
	//strcat(labelstring,datestrcurrent[6]);
	
	temp[0]=datestrcurrent[4];
	temp[1]=0;
	strcpy(labelstring,temp);
        temp[0]=datestrcurrent[5];
	temp[1]=0;
	strcat(labelstring,temp);
        temp[0]=datestrcurrent[6];
        temp[1]=0;
	strcat(labelstring,temp);

	//printf("labelstring %s\n", labelstring);
	//emptyvarstr = sprintf( labelstring, "%d", month);
	//gdImageString(im, gdFontLarge,   1500   ,   230    , "DAYS" , black);
	//gdImageString(im, gdFontLarge,   1550   ,   230    , labelstring , black);

	strcpy(datestrcurrent, asctime(local));
	//get year
	year = dates(datestrcurrent, 6);
	//printf("year %d\n", year);

	emptyvarstr = sprintf( temp, " %d", year);
	strcat(labelstring,temp);
        gdImageString(im, gdFontLarge,   1500   ,   230    , "DAYS" , black);
        gdImageString(im, gdFontLarge,   1540   ,   230    , labelstring , black);
		

	strcpy(datestrcurrent, asctime(local));
	//get number of days in month
	numdays = dates(datestrcurrent, 7); 

        //printf("stop 3\n");

	//open logfile
        if( ( lsnetlog = fopen( "/var/lib/lsnet/lsnet.log", "r" ) ) == NULL ) {
                fprintf( stderr, "Error opening /var/lib/lsnet/lsnet.log\n" );
                exit( 1 );
        }



	//count total number of lines in logfile
	lines1=0;
        while( fgets(linestring, sizeof(linestring), lsnetlog) != NULL)
        {
		lines1++;	
	}

	//printf("lines counted %d\n", lines1);
	fclose(lsnetlog);


        if( ( lsnetlog = fopen( "/var/lib/lsnet/lsnet.log", "r" ) ) == NULL ) {
                fprintf( stderr, "Error opening /var/lib/lsnet/lsnet.log\n" );
                exit( 1 );
        }

	

	//take sum of all bandwidth usage entries for each day (up and down)
	//put them into an array

	//look at only the last 47520 lines (33 days max, 1min per line)
	lines1=lines1-47520;
	lines2=0;
	lastday=1;
        while( fgets(linestring, sizeof(linestring), lsnetlog) != NULL)
        {
		lines2++;
		if(lines2>lines1)
		{
                        strcpy(copystr, linestring);
				//verify that it is in the same month
			if(month == dates(copystr, 1))
			{

					//if in the same day, add to totals in the 2nd and 3rd elements of array
				//if( dates(copystr, 2)
				strcpy(copystr, linestring);
				token = strtok(copystr, search);
                                token = strtok(NULL, search);
                                token = strtok(NULL, search);  
                                token = strtok(NULL, search);
                                token = strtok(NULL, search);
                                token = strtok(NULL, search);
                                netin = atof(token);
                                token = strtok(NULL, search);
                                token = strtok(NULL, search);
                                netout = atof(token);
				
				//memset ((void*) copystr, '\0', sizeof (copystr));
				strcpy(copystr, linestring);
				if(lastday == dates(copystr, 2) )
				{

				
				//printf("netin: %.0lf netout: %lf\n", netin, netout);
				//printf("%d\n", dates(copystr, 2));
					days[lastday][0]+=(netin*60);
					days[lastday][1]+=(netout*60);
				} else {
					//memset ((void*) copystr, '\0', sizeof (copystr));
					strcpy(copystr, linestring);
					lastday = dates(copystr, 2);

					//emptyvarstr = sprintf( labelstring, "%d", lastday);
					//gdImageString(im, gdFontMediumBold,   50   ,   240    , labelstring , black);


					days[lastday][0]=(netin*60);
					days[lastday][1]=(netout*60);
				}
			}
		}
	}

	fclose(lsnetlog);


	for(i=1; i<=day; i++)
	{
		days[i][0]=days[i][0]/1024;
		days[i][1]=days[i][1]/1024;
		//printf("day %d: %lf\n", i, infloat);
		//printf("day %d: %lf\n", i, outfloat);
	}

	//find highest sum of up/down

	max = 0;
	total1 = 0;
	total2 = 0;
        for(i=1; i<=day; i++)           
        {
		total1 += days[i][0];
		total2 += days[i][1];  
		if((days[i][0]+days[i][1])>max)
		{
			max = days[i][0]+days[i][1];	
		}
	}


	//print totals

	gdImageString(im, gdFontMediumBold,   1530   ,   150    , "Totals:" , black);
	emptyvarstr = sprintf( labelstring, "up   %.0lf MB", total2);
	gdImageString(im, gdFontSmall,   1505   ,   165    , labelstring , black);
	emptyvarstr = sprintf( labelstring, "down %.0lf MB", total1);
	gdImageString(im, gdFontSmall,   1505   ,   175    , labelstring , black);
	

	//plot left side labels

	tenth = max/10;
	//tenth = ceil(max);
	num7 = 210;
	num6 = 0;
	emptyvarstr = sprintf( labelstring, "%.0lf", num6); 
        for (i = 0; i < 11; ++i)
        {                               
                gdImageString(im, gdFontSmall,   25   ,   num7    , labelstring , black);
                gdImageLine(im, 35, num7, 1500, num7, gdStyled);
                num6 = num6 + tenth;
                num6 = ceil(num6);
                num7 = num7 - 20; 
                emptyvarstr = sprintf( labelstring, "%.0lf", num6);
        }

	




	//plot array of entries onto chart, starting with current day


	width=1440/day;

	//If less than 5 days to be plotted, don't make rectangles so large (don't look good)
	if(day < 5)
	{
		width = 120;
		
	}
	
	for(i=day; i>0; i--)
	{
		//printf("day: %d\n", i);
		//plot download rectangle
		height = (days[i][0] / max) * 200;
		height = 210 - height;
		num3 = 60 + (width*(i-1));
		num4 = num3+width-5;
		gdImageFilledRectangle(im, num3, height, num4, 210, green);

		if(i==1)
		{
			emptyvarstr = sprintf( labelstring, "%dst", i);
		}else if(i==2){
			emptyvarstr = sprintf( labelstring, "%dnd", i);
		}else if(i==3){
			emptyvarstr = sprintf( labelstring, "%drd", i);
		}else{
			emptyvarstr = sprintf( labelstring, "%dth", i);
		}

		gdImageString(im, gdFontMediumBold,   ((num3+num4)/2)   ,   240    , labelstring , black);
		gdImageLine(im, ((num3+num4)/2), 210, ((num3+num4)/2), 240, black);

		//printf("num3: %d height: %d num4: %d\n", num3, height, num4);		

		//plot upload rectangle
		height2 = (days[i][1] / max) * 200;
		height2 = height - height2;
		gdImageFilledRectangle(im, num3, height2, num4, height, red);
		//printf("day: %d ", i);
		//printf("num3: %d height2: %d num4: %d height: %d\n", num3, height2, num4, height);
	}









        strcpy(weblocation, webpath);
        strcat(weblocation, "/net2.png");
        //printf("weblocation netday: %s\n", weblocation);
        out = fopen(weblocation, "w");


	//out = fopen("/var/www/htdocs/lsnet/net.png", "w"); 
	gdImageInterlace(im, 1);
	//gdImageJpeg(im, out, -1); //write the image to thefile using the default quality setting
	gdImagePng(im, out);
	//fclose(lsnetlog);
	fclose(out); 
	gdImageDestroy(im);
	return (0);
}

