// Copyright, 2001-2003, Astra Network Inc.  All Rights Reserved

// This source code has been published by Astra Network Inc. However, any
// use, reproduction, modification, distribution or transfer of this
// software, or any software which includes or is based upon any of this
// code, is only permitted if expressly authorized by a written license
// agreement from Astra. Contact your Astra representative directly for
// more information.

#include <olmod.h>
#include <stdlib.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <procfs.h>
#include <sys/time.h>

typedef struct cpu_data_s
{
  pid_t process;
}
cpu_data_t;

olmod_blackbox_t *
cpu_module_inst (pid_t process, olmod_arglist_t * static_args)
{
  cpu_data_t *blackbox;

  if (!(blackbox = (cpu_data_t *) malloc (sizeof (blackbox))))
    {
      printf ("mod_cpu: malloc failed\n");
      return NULL;
    }

  blackbox->process = process;

  return blackbox;
}

int64_t
cpu_module_get (olmod_blackbox_t * data, olmod_arglist_t * dynamic_args)
{
  cpu_data_t *blackbox = (cpu_data_t *) data;
  char fname[PATH_MAX];
  int fd;
  psinfo_t psinfo;

  snprintf (fname, PATH_MAX, "/proc/%d/psinfo", blackbox->process);

  if ((fd = open (fname, O_RDONLY)) == -1)
    {
      fprintf (stderr, "mod_cpu: open of %s failed\n", fname);
      return 0;
    }
  if (sizeof (psinfo_t) != read (fd, &psinfo, sizeof (psinfo_t)))
    {
      fprintf (stderr, "mod_cpu: read of %s failed\n", fname);
      return 0;
    }
  close (fd);

  return ((long) psinfo.pr_pctcpu) * 10000 / 32767;
}
