/*
 * Copyright (c) 2022, Trond Myklebust <trond.myklebust@hammerspace.com>
 *
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
 * version 2.1 as published by the Free Software Foundation.
 *
 * This code 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 LESSER GENERAL PUBLIC LICENSE for more details.
 */

#include <sys/types.h>
#include <config.h>
#ifdef HAVE_ATTR_XATTR_H
# include <attr/xattr.h>
#else
# ifdef HAVE_SYS_XATTR_H
#  include <sys/xattr.h>
# endif
#endif
#include "libacl_nfs4.h"

static int nfs4_setacl_byname(const char *path, const char *xattr_name,
			      struct nfs4_acl *acl, enum acl_type type)
{
	char *xdrbuf = NULL;
	int ret;

	ret = acl_nfs41_xattr_pack(acl, &xdrbuf, type);
	if (ret != -1)
		ret = setxattr(path, xattr_name, xdrbuf, ret, XATTR_REPLACE);
	free(xdrbuf);
	return ret;
}

int nfs4_setacl(const char *path, struct nfs4_acl *acl)
{
	return nfs4_setacl_byname(path, ACL_NFS4_XATTR, acl, ACL_TYPE_ACL);
}
int nfs4_setdacl(const char *path, struct nfs4_acl *acl)
{
	return nfs4_setacl_byname(path, DACL_NFS4_XATTR, acl, ACL_TYPE_DACL);
}
int nfs4_setsacl(const char *path, struct nfs4_acl *acl)
{
	return nfs4_setacl_byname(path, SACL_NFS4_XATTR, acl, ACL_TYPE_SACL);
}
