/*
Topal: GPG/GnuPG and Alpine/Pine integration
Copyright (C) 2001--2008  Phillip J. Brooke

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <fcntl.h>
#include <glob.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
/* Debian: include errno to stop ld.so whinging. */
#include <errno.h>

int errno_wrapper () {
  return errno;
}

int waitpid_wrapper (pid_t pid) {
  int status;
  int rv;
  int exitstatus;
  rv = waitpid(pid, &status, 0);
  if (rv > 0)
    {
      exitstatus = WEXITSTATUS(status);
      return exitstatus;
    }
  else
    return rv;
}

int open_append_wrapper (const char *pathname) {
  return open (pathname, O_CREAT|O_APPEND|O_WRONLY, S_IRUSR|S_IWUSR);
}

int open_out_wrapper (const char *pathname) {
  return open (pathname, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
}

int open_in_wrapper (const char *pathname) {
  return open (pathname, O_RDONLY);
}

/* Given a pattern string, glob.  
   This is done as an iterator: it is not thread/task safe! */

glob_t globbuf;

int glob_actual (const char *pattern) {
  glob(pattern, 0, NULL, &globbuf);
  return globbuf.gl_pathc;
}

char *glob_text (int index) {
  if (index >= globbuf.gl_pathc)
    return NULL;
  else
    return globbuf.gl_pathv[index];
}

void glob_free () {
  globfree(&globbuf);
}
