/*************************************************** */
/* Rule Set Based Access Control                     */
/*                                                   */
/* Author and (c) 1999-2010: Amon Ott <ao@rsbac.org> */
/*                                                   */
/* Last modified: 25/Jan/2010                        */
/*************************************************** */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <rsbac/types.h>
#include <rsbac/getname.h>
#include <rsbac/syscalls.h>
#include <rsbac/error.h>
#include <rsbac/helpers.h>
#include <rsbac/aci_data_structures.h>
#include "nls.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define ROOM 10

const char   set_prog[] = "attr_set_group";
__s64 attr_list[RSBAC_GROUP_NR_ATTRIBUTES] = RSBAC_GROUP_ATTR_LIST;
int allgroup = 0;
int verbose = 0;
int numeric = 0;
rsbac_list_ta_number_t ta_number = 0;
FILE * tfile;
char * filename = NULL;
union rsbac_target_id_t       tid;
union rsbac_attribute_value_t value;

char * progname;

int def_attr[RSBAC_GROUP_NR_ATTRIBUTES] = {
      RSBAC_RC_GENERAL_TYPE, /* rc_type */
  };

void use()
    {
      printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
      printf(gettext("Use: %s [flags] [groupname(s)]\n"), progname);  
      printf(gettext(" -h = this help, -- = no more flags,\n"));
      printf(gettext(" -a = process all groups, -v = verbose,\n"));
      printf(gettext(" -T file = read file/dirname list from file (- for stdin),\n"));
      printf(gettext(" -n = show numeric gid not groupname,\n"));
      printf(gettext(" -o target-file = write to file, not stdout,\n"));
      printf(gettext(" -A = list attributes and values,\n"));
      printf(gettext(" -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
    }

int process(rsbac_gid_t group, char * name)
  {
    int res = 0;
    char tmp1[RSBAC_MAXNAMELEN],tmp2[RSBAC_MAXNAMELEN];
    char intname[RSBAC_MAXNAMELEN];
    int j;

    tid.group = group;
    if(verbose)
      {
        if(name)
          printf(gettext("# Processing group %s\n"), name);
        else {
          if (RSBAC_GID_SET(group))
            printf(gettext("# Processing group %u/%u\n"),
                   RSBAC_GID_SET(group), RSBAC_GID_NUM(group));
          else
            printf(gettext("# Processing group %u\n"), RSBAC_GID_NUM(group));
        }
      }
    if(numeric || !name) {
      if (RSBAC_GID_SET(group))
        sprintf(intname, "%u/%u", RSBAC_GID_SET(group), RSBAC_GID_NUM(group));
      else
        sprintf(intname, "%u", RSBAC_GID_NUM(group));
    } else
      strcpy(intname,name);
    for (j=0;j < RSBAC_GROUP_NR_ATTRIBUTES;j++)
      {
        value.dummy = -1;
        res = rsbac_get_attr(ta_number, get_attr_module(attr_list[j]), T_GROUP, &tid, attr_list[j], &value, 0);
        if(res)
          {
            if(   (errno != RSBAC_EINVALIDMODULE)
               && (   verbose
                   || (errno != RSBAC_EINVALIDTARGET)
                  )
              )
              {
                get_error_name(tmp1,res);
                get_attribute_name(tmp2,attr_list[j]);
                fprintf(stderr, "%s (%s): %s\n",
                        intname, tmp2, tmp1);
                          
              }
          }
        else
          {
            switch(attr_list[j])
              {
                default:
                  if(value.dummy != def_attr[j])
                    fprintf(tfile,
                            "%s -V %u %s %s %i\n",
                            set_prog,
                            RSBAC_VERSION_NR,
                            intname,
                            get_attribute_name(tmp1,attr_list[j]),
                            value.dummy);
              }
          }
      }
    return(res);
  }

int main(int argc, char ** argv)
{
  int res = 0;
  char tmp1[RSBAC_MAXNAMELEN],tmp2[RSBAC_MAXNAMELEN],tmp3[RSBAC_MAXNAMELEN];
  rsbac_gid_t group;
  int i,j;
  FILE * listfile = NULL;
  char * filelistname = NULL;
  u_int stopflags = FALSE;

  locale_init();

  progname = argv[0];
  {
    char * env = getenv("RSBAC_TA");

    if(env)
      ta_number = strtoul(env,0,0);
  }
  while((argc > 1) && (argv[1][0] == '-') && !stopflags)
    {
      char * pos = argv[1];
      pos++;
      while(*pos)
        {
          switch(*pos)
            {
              case '-':
                stopflags = TRUE;
                break;
              case 'h':
                use();
                return 0;
              case 'v':
                verbose++;
                break;
              case 'a':
                allgroup=1;
                break;
              case 'n':
                numeric=1;
                break;
              case 'o':
                if(argc > 2)
                  {
                    filename = argv[2];
                    argv++;
                    argc--;
                  }
                else
                  fprintf(stderr, gettext("%s: missing filename for parameter %c\n"), progname, *pos);
                break;
              case 'T':
                if(argc > 2)
                  {
                    filelistname = argv[2];
                    argv++;
                    argc--;
                  }
                else
                  fprintf(stderr, gettext("%s: missing filename for parameter %c\n"), progname, *pos);
                break;
              case 'A':
                printf(gettext("- attributes and values in backup = see following list:\n"));
                for (j=0;j<RSBAC_USER_NR_ATTRIBUTES;j++)
                  {
                    get_switch_target_name(tmp1, get_attr_module(attr_list[j]));
                    get_attribute_name(tmp2,attr_list[j]);
                    get_attribute_param(tmp3,attr_list[j]);
                    printf("[%-4s] %s\n\t%s\n",tmp1,tmp2,tmp3);
                  }
                exit(0);
              case 'N':
                if(argc > 2)
                  {
                    ta_number = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  {
                    fprintf(stderr, gettext("%s: missing transaction number value for parameter %c\n"), progname, *pos);
                    exit(1);
                  }
                break;
              default:
                fprintf(stderr, gettext("%s: unknown parameter %c\n"), progname, *pos);
                exit(1);
            }
          pos++;
        }
      argv++;
      argc--;
    }

  if (   (argc > 1)
      || allgroup
      || filelistname
     )
    {
      if(!filename)
        tfile = stdout;
      else
        {
          if (!(tfile=fopen(filename,"w")))
            {
              fprintf(stderr, gettext("opening target file returned error: %s\n"),
                              strerror(errno));
            }
        }
      tid.group = RSBAC_ALL_GROUPS;
      if(allgroup)
        {
          int count;
          rsbac_gid_t * id_array;

          if(verbose)
            printf(gettext("# %s: processing all groups\n"), progname);
          count = rsbac_list_all_group(ta_number, NULL, 0);
          error_exit(count);
          count += ROOM;
          id_array = malloc(count * sizeof(*id_array));
          if(!id_array)
            error_exit(-ENOMEM);
          count = rsbac_list_all_group(ta_number, id_array, count);
          if(verbose)
            printf(gettext("# %s: %i targets\n"), progname, count);
          if(count > 0)
            {
              qsort(id_array, count, sizeof(*id_array), rsbac_group_compare);
              for(i=0; i < count ; i++)
                {
                  if(!get_group_name(ta_number, id_array[i], tmp1))
                    process(id_array[i], tmp1);
                  else
                    process(id_array[i], NULL);
                }
            }
        }
      else
        {
          if(filelistname)
            {
              if(!strcmp(filelistname, "-"))
                listfile = stdin;
              else
                if (!(listfile=fopen(filelistname,"r")))
                  {
                    fprintf(stderr, gettext("opening target list file returned error: %s\n"),
                            strerror(errno));
                    exit(1);
                  }
            }
          if(verbose)
            {
              printf(gettext("# %s: %i targets\n"), progname, argc - 2);
              if(filelistname)
                printf(gettext("# - plus targets from file %s\n"), filelistname);
            }
          for (i=1;i < argc;i++)
            {
              if(rsbac_get_gid_name(ta_number, &group, tmp1, argv[i]))
                {
                  fprintf(stderr, gettext("%s: Invalid Group %s!\n"),
                          progname, argv[i]);
                }
              else
                process(group, tmp1);
            }
          if(filelistname)
            {
              char item[4096];
              int last;

              while(fgets(item, 4095, listfile))
                {
                  if(!*item)
                    continue;
                  last = strlen(item) - 1;
                  if(item[last] == '\n')
                    item[last] = 0;
                  if(*item)
                    {
                      if(rsbac_get_gid_name(ta_number, &group, tmp1, item))
                        {
                          fprintf(stderr, gettext("%s: Invalid Group %s!\n"),
                                  progname, item);
                        }
                      else
                        process(group, tmp1);
                    }
                }
              fclose(listfile);
            }
        }
      if(tfile != stdout)
        fclose(tfile);
    }
  else
    {
      use();
      return 1;
    }
  return (res);
}
