/*
 *========================================================================
 * $Id: get_proc_uptime.c 163 2005-09-14 22:54:20Z rgb $
 *
 * See copyright in copyright.h and the accompanying file COPYING
 *========================================================================
 */

#include "xmlsysd.h"

/*
 * This routine parses /proc/stat and packs its values into doc.
 */

void get_proc_uptime(xmlNodePtr proc)
{

 int i,numfields, cpuid;
 struct timeval tv;
 xmlNodePtr uptime,statname,statvalue;

 if(verbose==102){
   fprintf(stderr,"Starting get_proc_stat().\n");
 }

 /* 
  * Create a timestamped child of document root.  Everything below
  * will belong to this
  */
 uptime = xmlNewChild(proc,NULL,(xmlChar*) "uptime",NULL);
 gettimeofday(&tv,0);
 sprintf(outbuf,"%d",tv.tv_sec);
 xmlSetProp(uptime,(xmlChar*) "tv_sec",(xmlChar*) outbuf);
 sprintf(outbuf,"%d",tv.tv_usec);
 xmlSetProp(uptime,(xmlChar*) "tv_usec",(xmlChar*) outbuf);

 /* 
  * Now, for a clever trick.  We RESET the files without actually
  * closing or reopening them.  This should save the overhead of
  * an open/close (presumed relatively large, as one has to 
  * allocate/free certain kernel structures and stat the file in question 
  * on EACH open/close).
  */

 /* PROC_UPTIME */
 errno = 2;
 if(stat_fd[PROC_UPTIME]){
   rewind(stat_fd[PROC_UPTIME]);	/* void, so tough to check errors */
 } else {
   xmlSetProp(uptime,(xmlChar*) "available",(xmlChar*) "no");
   return;
 }
 if(errno == EBADF){
   fprintf(stderr,"Error: The %s file descriptor/stream is not seekable.\n",procpaths[PROC_UPTIME]);
   fclose(stat_fd[PROC_UPTIME]); 
   fprintf(stderr,"Closing and reopening %s.\n",procpaths[PROC_UPTIME]);
   stat_fd[PROC_UPTIME] = fopen(procpaths[PROC_UPTIME],"r");
 }

 if(verbose == 102){
   fprintf(stderr,"Rewound %s.\n",procpaths[PROC_UPTIME]);
 }

 /* Should be just one line, two fields.  An easy one */
 while(TRUE){

   /* Normal EOF causes break from while loop */
   if((fgets(statbuf,K,stat_fd[PROC_UPTIME]) == NULL)) break;

   if(verbose == 102){
     fprintf(stderr,"Parsing %s\n",statbuf);
   }

   /* parse the line into fields */
   numfields = parse(statbuf,fields,MAXFIELDNUMBER,K);

   statname = xmlNewChild(uptime,NULL,(xmlChar*) "up",(xmlChar*) fields[0]);
   statname = xmlNewChild(uptime,NULL,(xmlChar*) "idle",(xmlChar*) fields[1]);

 }

}

