/*  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/>.
*/
#define _GNU_SOURCE
#include <gd.h>
#include "gdfontl.h"
#include "gdfontmb.h"
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include "dates.h"
//#include "cores.h"
//#include "doubletoint.h"
#include "gdfonts.h"
#include "gdfontt.h"
#include "gdfontl.h"
//gdfontt.h", "gdfonts.h", "gdfontmb.h", "gdfontl.h" and "gdfontg.h"


//int error()
//{
//	printf("Error, out of bounds exception!");
//}


//int memarray1[9];

int main() {
	gdImagePtr im; 
	FILE *out; 
	int black,white,red,blue,green,yellow,orange,purple,brown,grey;
	FILE* lsnetlog;  

	im = gdImageCreate(1620,255); 

	white = gdImageColorAllocate(im, 255, 255, 255);
	black = gdImageColorAllocate(im, 0, 0, 0); 
	//white = gdImageColorAllocate(im, 255, 255, 255);	
	red = gdImageColorAllocate(im, 255, 0, 0);
	blue = gdImageColorAllocate(im, 0, 0, 255);
	green = gdImageColorAllocate(im, 0, 255, 0);
	yellow = gdImageColorAllocate(im, 255, 255, 0);
	orange = gdImageColorAllocate(im, 255, 128, 0);
	purple = gdImageColorAllocate(im, 255, 0, 255);
	brown = gdImageColorAllocate(im, 128, 64, 0);
	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 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];	

	int i;
	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
	int num6 = 0;
	int num7 = 210;
	//int coresfound = coresdetected();
	//meminfo(1,memarray1);
	
	
        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    , "KB/s" , black);
	gdImageString(im, gdFontMediumBold,   50   ,   240    , "Hours" , 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;
	

///// search the last 1440 entries and find the highest occurance
	i = 1441;

        t = time(NULL);  
        local = localtime(&t);
        strcat(datestrcurrent, asctime(local));
        datestrcurrent[strlen(datestrcurrent)-1]='\0';   
        minsince2 = dates(datestrcurrent);      

        if( ( lsnetlog = fopen( "/var/lib/lsnet/lsnet.log", "r" ) ) == NULL ) {
                fprintf( stderr, "Error opening /var/lib/lsnet/lsnet.log\n" );
                exit( 1 );
        }
        while( fgets(linestring, sizeof(linestring), lsnetlog) != NULL)
        {
                        strcpy(copystr, linestring);
                        minsince = dates(copystr);
                        if (i == 1440)
                        {
                                lastminsince = minsince;
                        }
			if (minsince >= (minsince2 - 1439))
                        //if (minsince <= minsince2 - 1440 && coordinate <= 1500)
                        { 
				//printf("entry not older than 1 day\n");
                                if (i >= 0)
                                {
					//Thu Feb 26 06:46:45 2009 0.955699 18.408590 0.106445 0.514237
					//printf("linestring: %s\n", linestring);
                                        //strcpy(copystr, linestring);
                                        token = strtok(linestring, 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);
					max = netin + netout;
					//printf("max: %lf\n", max);
					if (max > oldmax)
					{
						oldmax = max;
					}

					i--;

				}
			//lastminsince = minsince;
			//i--;
			}
	}

	fclose(lsnetlog);
//printf("closed file\n");

	//oldmax = oldmax / 60;
	//oldmax = oldmax * 1024;
	tenth = oldmax / 10;
	tenth = ceil(tenth);
//printf("oldmax: %lf\n", oldmax);

	counter4 = 110;
	counter5 = tenth;
	//num6 = 0;
	//gdImageDashedLine(im, 0, 0, 99, 99, red);
	//dImageSetStyle(gdImagePtr im, int *style, int styleLength)
	
	//gdImageSetStyle(im, styleDashed, 6);
	//gdImageLine(im, 0, 99, 0, 99, gdStyled);
	//num3 = 210;
	emptyvarstr = sprintf( labelstring, "%d", 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, "%d", num6);
	}





       	if( ( lsnetlog = fopen( "/var/lib/lsnet/lsnet.log", "r" ) ) == NULL ) {
               	fprintf( stderr, "Error opening /var/lib/lsnet/lsnet.log\n" );
               	exit( 1 );
       	}
       	t = time(NULL);
       	local = localtime(&t);
       	strcat(datestrcurrent, asctime(local));
       	datestrcurrent[strlen(datestrcurrent)-1]='\0';
	minsince2 = dates(datestrcurrent);
	//lastminsince = minsince;
	i = 1440;
	coordinate = 60;
	//printf("minsince2: %d\n", minsince2);
       	while( fgets(linestring, sizeof(linestring), lsnetlog) != NULL)
       	{
			//printf("opened file, linestring: %s\n", linestring);
			strcpy(copystr, linestring);
			//printf("copied string\n");		
			minsince = dates(copystr);
			//printf("back from dates\n");
			if (i == 1440)
			{
				lastminsince = minsince;
			}
			if (minsince >= (minsince2 - 1439) && coordinate <= 1500)
			//if (minsince >= minsince2 - 1439 && coordinate <= 1500)
			{ 
				if (i >= 0)
				{
					//printf("linestring: %s\n", linestring);
					//printf("started loops\n");
					//user, nice, system, idle, iowait, irq, softirq
					//strcpy(copystr, linestring);
					token = strtok(linestring, search);
					token = strtok(NULL, search);
					token = strtok(NULL, search);
					token = strtok(NULL, search);
			
					temp[0]=token[0];
					temp[1]=token[1];
					temp[2]=0;
					hour = atoi(temp);

					temp[0]=token[3];
					temp[1]=token[4];
					temp[2]=0;
       					min = atoi(temp);
					temp[0]=token[6];
					temp[1]=token[7];
					temp[2]=0;
       					sec = atoi(temp);

					token = strtok(NULL, search);

                                        token = strtok(NULL, search);
                                        netin = atof(token);
                                        token = strtok(NULL, search);
                                        token = strtok(NULL, search);
                                        netout = atof(token);
                                        max = netin + netout;
					//max = max / 60;
					//max = max / 1024



                                        
                                        //#top of netin
                                        num3 = netin / oldmax;
                                        num3 = num3 * 200;
                                        num3 = 200 - num3;
                                        num3 = num3 + 10;



		                        //#top of netout
	        	                num4 = (netout + netin) / oldmax;
	                        	num4 = num4 * 200;
                        		num4 = 200 - num4;
                        		num4 = num4 + 10;

					difference = minsince - lastminsince;
					difference = ceil(difference);
                                        if (difference >= 2)
                                        {
                                                //#leave a blank line for each 1min lost
                                                for (counter3 = 1; counter3 < difference; counter3++)
                                                {
                                                   	coordinate++;
                                                }
                                        }

                                        //if multiple of 60 drawl date labels
                                        modulo4 = coordinate % 60;
                                        if (modulo4 == 0)
                                        {
                                        	labeldate1 = hourhash(hour);
                                                isam = ampm(hour);
						if (labeldate1 < 10)
						{
							emptyvarstr = sprintf( hourstr, "0%d", labeldate1);
							//hourstr[strlen(hourstr)-1]='\0';
						}else{
							emptyvarstr = sprintf( hourstr, "%d", labeldate1);
						}
                                                if (min < 10)
                                                {
                                                        emptyvarstr = sprintf( minstr, "0%d", min);
							//minstr[strlen(minstr)-1]='\0';          
                                                }else{
							emptyvarstr = sprintf( minstr, "%d", min);
						}
                                                if (sec < 10)
                                                {
                                                        emptyvarstr = sprintf( secstr, "0%d", sec);          
							//secstr[strlen(secstr)-1]='\0';
                                                }else{
							emptyvarstr = sprintf( secstr, "%d", sec);
						}
                                                if (isam == 1)
                                                {
                                                	emptyvarstr = sprintf( labeldate2, "%s:%s:%s AM", hourstr, minstr, secstr);
                                                }else{
                                                        emptyvarstr = sprintf( labeldate2, "%s:%s:%s PM", hourstr, minstr, secstr);
                                                }
                                                if (stagger == 230)
                                                {
                                                	stagger = 220;
                                                }else{
                                                        stagger = 230;
                                                }
                                                gdImageString(im, gdFontSmall,   coordinate - 30   ,  stagger  , labeldate2 , black);
                                                gdImageLine(im, coordinate, 210, coordinate , stagger, black);
                                         }

					if (netin > 0 && netout > 0)
					{
							//#netout line
						gdImageLine(im, coordinate, num4, coordinate , 210 , red);
                                        		//#netin line
                                        	gdImageLine(im, coordinate, num3, coordinate , 210, green);
					}



						//coordinate++;
						//lastminsince = minsince;
						i--;
					}	
				//i--;
				lastminsince = minsince;
				coordinate++;
			}
	}

//plot date/time for last entry
        if (modulo4 != 0)
        {
                labeldate1 = hourhash(hour);
                isam = ampm(hour);
                if (labeldate1 < 10)
                {
                        emptyvarstr = sprintf( hourstr, "0%d", labeldate1);
                }else{
                        emptyvarstr = sprintf( hourstr, "%d", labeldate1);
                }
                if (min < 10)
                {
                        emptyvarstr = sprintf( minstr, "0%d", min);
                }else{
                        emptyvarstr = sprintf( minstr, "%d", min);
                }
                if (sec < 10)
                {
                        emptyvarstr = sprintf( secstr, "0%d", sec);
                }else{
                        emptyvarstr = sprintf( secstr, "%d", sec);
                }  
 
                if (isam == 1)
                {       
                        emptyvarstr = sprintf( labeldate2, "%s:%s:%s AM", hourstr, minstr, secstr);
                }else{  
                        emptyvarstr = sprintf( labeldate2, "%s:%s:%s PM", hourstr, minstr, secstr);
                }
                if (stagger == 230)
                {       
                        stagger = 220;
                }else{  
                        stagger = 230;
                }
                gdImageString(im, gdFontSmall,   1470   ,  stagger  , labeldate2 , black);
                gdImageLine(im, coordinate, 210, 1500 , stagger, black);
        }
//

	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);
}

