
#include <mysql/mysql.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

my_bool loadavg_init(UDF_INIT *initid, UDF_ARGS *args, char *message);

void loadavg_deinit(UDF_INIT *initid);

char *loadavg(UDF_INIT *initid, UDF_ARGS *args, char *result,
	      unsigned long *length, char *is_null, char *error);

my_bool loadavg_init(UDF_INIT *initid __attribute((unused)),
		     UDF_ARGS *args, char *message)
{
  if ( args->arg_count != 0 )
    {
      strcpy( message, "no arguments accepted." );
      return 1;
    }

  return 0;
}

void loadavg_deinit(UDF_INIT *initid  __attribute((unused)))
{
}

char *loadavg(UDF_INIT *initid  __attribute((unused)),
	      UDF_ARGS *args  __attribute((unused)), 
	      char *result,
	      unsigned long *length,
	      char *is_null  __attribute((unused)), 
	      char *error  __attribute((unused)))
{
  double loadavg[ 3 ] = { -1.0, -1.0, -1.0 }; 

  getloadavg( loadavg, 3 );

  int s = snprintf( result, *length, "%2.2f, %2.2f, %2.2f",
		    loadavg[ 0 ], loadavg[ 1 ], loadavg[ 2 ] );

  if ( s < 0 ) {
    *length = 0;
  } else  if ( (unsigned long) s < *length ) {
    *length = s;
  } else {
    (void) *length--;
  }

  return result;
}
