// 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 <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <procfs.h>
#include <libgen.h>

int64_t
getpidbyname_module_get (olmod_blackbox_t * data,
			 olmod_arglist_t * dynamic_args)
{
  char *name = (char *) dynamic_args[0];
  char fname[PATH_MAX];
  DIR *dir;
  struct dirent *dp;
  int fd;
  psinfo_t psinfo;
  pid_t process = 0;

  dir = opendir ("/proc");
  if (dir != NULL)
    {
      for (;;)
	{
	  dp = readdir (dir);
	  if (dp == NULL)
	    break;

	  snprintf (fname, PATH_MAX, "/proc/%s/psinfo", dp->d_name);
	  if ((fd = open (fname, O_RDONLY)) == -1)
	    {
	      continue;		// in the case of . and ..
	    }
	  if (sizeof (psinfo_t) != read (fd, &psinfo, sizeof (psinfo_t)))
	    {
	      close (fd);
	      continue;
	    }
	  if (strcmp (name, basename (psinfo.pr_fname)) == 0)
	    {
	      process = atol (dp->d_name);
	      close (fd);
	      break;
	    }
	  close (fd);
	}
      closedir (dir);
    }
  return process;
}
