
#include "procstatd.h"
#include <dirent.h>

int sendline(int fd, char *buffer, int length);

#define MAX_BUFFER 4096

static DIR* dp_proc = NULL;

void append_pid( char* buf, char* add ) {
	int i,j;

	i = 0;
	while( i < MAX_BUFFER ) {
		if( buf[i] == 0 ) {
			break;
		}
		i++;
	}

	j = 0;
	while( j < 1024 ) {
		if( add[j] == 0 ) {
			break;
		}

		buf[i] = add[j];
		i++;
		j++;
	}

	buf[i] = '|';
	buf[i+1] = 0;

	return;
}

char* next_pid( char* list ) {
	static char* last = NULL;
	static int   ofs = 0;
	char* cp;
	int   i;

	if( last != list ) {
		last = list;
		ofs = 0;
	}

	cp = list + ofs;

	i = 0;
	while( (cp[i]!='|') && (cp[i]!=0) ) {
		i++;
	}
	cp[i] = 0;

	ofs = ofs + i + 1;

	return( cp );
}

void clean_up( char* data, int len ) {
	int i;

	for(i=0;i<len;i++) {
		if( data[i] == '\n' ) {
			data[i] = '|';
		} else if( data[i] == ':' ) {
			data[i] = ' ';
		}
	}

	return;
}

void clean_up2( char* data, int len ) {
	int i;

	for(i=0;i<(len-1);i++) {
		if( data[i] == 0 ) {
			data[i] = ' ';
		} else if( data[i] == '\n' ) {
			data[i] = ' ';
		}
	}

	return;
}

void init_jobslist() {
	dp_proc = opendir( "/proc" );
	if( dp_proc == NULL ) {
		printf("Error opening /proc\n");
		exit( -1 );
	}

	return;
}

void get_and_send_jobslist() {
	FILE* fp;
	struct dirent* procdir;
	char list[MAX_BUFFER];
	char fname[256];
	char data[1024];
	char* pid;
	int  num_jobs;
	int  c,i,j,f;

	if( dp_proc == NULL ) {
		init_jobslist();
	}

	/* "zero out" the list of pids */
	list[0] = 0;

	/* create a list of jobs */
	rewinddir( dp_proc );
	num_jobs = 0;
	while( 1 ) {
		procdir = readdir( dp_proc );
		if( procdir == NULL ) {
			break;
		}

		if( (procdir->d_name[0]>='0') && (procdir->d_name[0]<='9') ) {
			append_pid( list, procdir->d_name );
			num_jobs++;
		}
	}

	sprintf( outbuf, "num_jobs %d\n", num_jobs );
	buflen = strlen( outbuf );
	sendline( client_fd, outbuf, buflen );

	if(verbose) printf("list = %i items: %s\n",num_jobs,list);

	for(c=0;c<num_jobs;c++) {
		pid = next_pid( list );
		sprintf( fname, "/proc/%s/status", pid );
		fp = fopen( fname, "r" );
		if( fp == NULL ) {
			continue;
		}

		/* read in the data then clean it up */
		i = fread( data, 1, 1024, fp );
		clean_up( data, i );

		strncpy( outbuf, data, i );
		/* strncpy *SHOULD* copy the trailing zero, but it doesn't ! */
		outbuf[i] = 0;
		strncat( outbuf, "cmdline ", 8 );
		fclose( fp );

		sprintf( fname, "/proc/%s/cmdline", pid );
		fp = fopen( fname, "r" );
		if( fp == NULL ) {
			continue;
		}

		/* read in the data then clean it up */
		j = fread( data, 1, 1024, fp );
		if( j != 0 ) {
			clean_up2( data, j );
			strncat( outbuf, data, j );
		}
		strncat( outbuf, "|\n", 2 );
		fclose( fp );

		buflen = strlen(outbuf);
		sendline(client_fd,outbuf,buflen);
	}

} /* End get_and_send_jobslist */

