#include "xattr.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/ext2_fs.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <syslog.h>
#include <errno.h>
#include "auth.h"

char argbuf[1024];

/* Null function... */
void *xattrproc_null_1_svc(void *argp, struct svc_req *dummy)
{
  return (void *)1;
}

/* Geteattr : gets the extended attributes */
res *xattrproc_geteattr_1_svc(geteattrargs *argp, struct svc_req *dummy)
{
  static int fd, ret;
  static res res;
  unsigned long flags;
  nfs_client *cp;
  nfs_mount  *mp;
  char tmp[1024];
  strcpy(argbuf,argp->filename);
  if (((cp = auth_clnt(dummy)) == NULL) 
          || (mp = auth_path(cp, dummy, argbuf)) == NULL
          /*|| mp->o.noaccess*/) {
                res.mode = -13; /* NFSERR_ACCESS */
                sprintf(tmp,"access denied %s\n",argbuf);
                syslog(LOG_DAEMON,tmp);
                return &res;
  }
  res.mode=-1;
  fd=open(argp->filename, O_RDONLY);
  
  if (fd<0)                                 /* Something goes wrong */
    return &res;
  
  ret=ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
  
  close(fd);
  
  if (ret<0) {                               /* Ioctl error */
    res.mode=ret;
    return &res;
  }
  res.mode=flags;                           /* Ioctl ok */
  return &res;
}

res *xattrproc_seteattr_1_svc(seteattrargs *argp, struct svc_req *dummy)
{
  int fd,ret;
  static res res;
  unsigned long flags;
  nfs_client *cp;
  nfs_mount  *mp;
  char tmp[1024];
  strcpy(argbuf,argp->filename);
  if (((cp = auth_clnt(dummy)) == NULL) 
          || (mp = auth_path(cp, dummy, argbuf)) == NULL
          /*|| mp->o.noaccess*/) {
                res.mode = -13; /* NFSERR_ACCESS */
                sprintf(tmp,"access denied %s\n",argbuf);
                syslog(LOG_DAEMON,tmp);
                return &res;
  }
  res.mode=-1; 
  flags=argp->mode;
  fd=open(argp->filename,O_RDONLY);

  if (fd<0)                                /* Something goes wrong */
    return &res;

  ret=ioctl (fd, EXT2_IOC_SETFLAGS, &flags);
  close(fd);

  if (ret<0)                               /* Ioctl error */
    return &res;
  
  res.mode=0;
                              /* Ioctl ok */
  return &res;
}


res *xattrproc_truncate_1_svc(truncateargs *argp, struct svc_req *dummy)
{
	static res res;
	nfs_client *cp;
	nfs_mount  *mp;
	strcpy(argbuf,argp->filename);
	if (((cp = auth_clnt(dummy)) == NULL) 
		|| (mp = auth_path(cp, dummy, argbuf)) == NULL
		/*|| mp->o.noaccess*/) {
		res.mode = -13; /* NFSERR_ACCESS */
		return &res;
	}	
	res.mode=truncate(argp->filename,argp->lenght);
	if (res.mode<0)
		res.mode=-errno;
	return &res;
}