/*
 * QUOTA    An implementation of the diskquota system for the LINUX
 *          operating system. QUOTA is implemented using the BSD systemcall
 *          interface as the means of communication with the user level.
 *          Should work for all filesystems because of integration into the
 *          VFS layer of the operating system.
 *          This is based on the Melbourne quota system wich uses both user and
 *          group quota files.
 *
 *          Determines if a filesystem has quota enabled and how the quotafile
 *          is named.
 *
 * Version: $Id: hasquota.c,v 2.9 2000/09/05 18:47:15 mvw Exp mvw $
 *
 * Author:  Marco van Wieringen <mvw@planets.elm.net>
 *
 *          This program is free software; you can redistribute it and/or
 *          modify it under the terms of the GNU General Public License
 *          as published by the Free Software Foundation; either version
 *          2 of the License, or (at your option) any later version.
 */
#include <sys/types.h>
#include <limits.h>
#include <sys/quota.h>
#include <string.h>
#include <mntent.h>

#define min(x,y) ((x) < (y)) ? (x) : (y)

#define CORRECT_FSTYPE(type) (\
(!strcmp(type, MNTTYPE_EXT2)) || \
(!strcmp(type, MNTTYPE_EXT3)) || \
(!strcmp(type, MNTTYPE_MINIX)) || \
(!strcmp(type, MNTTYPE_UFS)) || \
(!strcmp(type, MNTTYPE_UDF)) || \
(!strcmp(type, MNTTYPE_REISER)) || \
(!strcmp(type, MNTTYPE_XFS)) \
)

char *qfextension[] = INITQFNAMES;
static char *qfname = QUOTAFILENAME;
static char qfullname[PATH_MAX];

/*
 * Check to see if a particular quota is to be enabled.
 */
hasquota(struct mntent *mnt, int type, char **qfnamep)
{
   char *option, *pathname, has_quota_file_definition;

   if (!CORRECT_FSTYPE(mnt->mnt_type))
      return (0);

   has_quota_file_definition = 0;

   if ((type == USRQUOTA) && (option = hasmntopt(mnt, MNTOPT_USRQUOTA)) != (char *)NULL) {
      if (*(pathname = option + strlen(MNTOPT_USRQUOTA)) == '=')
         has_quota_file_definition = 1;
   } else {
      if ((type == GRPQUOTA) && (option = hasmntopt(mnt, MNTOPT_GRPQUOTA)) != (char *)NULL) {
         if (*(pathname = option + strlen(MNTOPT_GRPQUOTA)) == '=')
            has_quota_file_definition = 1;
      } else {
         if ((type == USRQUOTA) && (option = hasmntopt(mnt, MNTOPT_QUOTA)) != (char *)NULL) {
            if (*(pathname = option + strlen(MNTOPT_QUOTA)) == '=')
               has_quota_file_definition = 1;
         } else {
            return(0);
         }
      }
   }

   if (has_quota_file_definition) {
      if ((option = strchr(++pathname, ',')) != (char *)NULL) 
         strncpy(qfullname, pathname, min((option - pathname), sizeof(qfullname)));
      else
         strncpy(qfullname, pathname, sizeof(qfullname));
   } else {
      (void) sprintf(qfullname, "%s%s%s.%s", mnt->mnt_dir,
                    (mnt->mnt_dir[strlen(mnt->mnt_dir) - 1] == '/') ? "" : "/",
                     qfname, qfextension[type]);
   }

   *qfnamep = strdup(qfullname);
   return (1);
}
