#include <stdio.h>
#include <stdlib.h>
#include <rsbac/types.h>
#include <rsbac/aci_data_structures.h>
#include <rsbac/getname.h>
#include <rsbac/syscalls.h>
#include <rsbac/error.h>

int main(int argc, char ** argv)
{
  int attr_list[RSBAC_IPC_NR_ATTRIBUTES] = RSBAC_IPC_ATTR_LIST;
  int res = 0;
  char tmp1[80],tmp2[120];
  int j;
  union rsbac_attribute_value_t value;
  union rsbac_target_id_t tid;
  enum rsbac_ipc_type_t ipc_target;
  enum rsbac_attribute_t attr;
  struct rsbac_ipc_t ipc_id;
  rsbac_pid_t pid;
  int    sid;
  
  if ((argc == 5)||(argc == 6))
    {
      strcpy(tmp2,argv[0]);
      if(   ((ipc_target = get_ipc_target_nr(argv[1])) == I_none)
         || (ipc_target == I_sock)
        )
        {
          fprintf(stderr, "%s: Invalid IPC type %s!\n", tmp2, argv[1]);
          exit(1);
        }
      ipc_id.type = ipc_target;
      if((ipc_target == I_sockid) && (argc == 6))
        {
          pid = strtol(argv[2],0,0);
          sid = strtol(argv[3],0,0);
          ipc_id.id.id_nr = rsbac_create_ipc_sock_id(pid,sid);
          argv++;
        }
      else
          ipc_id.id.id_nr = strtol(argv[2],0,0);

      attr = get_attribute_nr(argv[3]);
      if(attr == A_none)
        {
          fprintf(stderr, "%s: Invalid Attribute %s!\n", tmp2, argv[3]);
          exit(1);
        }
      tid.ipc = ipc_id;

      value.dummy = strtol(argv[4],0,0);
      res = rsbac_set_attr(T_IPC, &tid, attr, &value);
      if(res)
        {
          if((res > -RSBAC_EPERM) || (res < -RSBAC_EDECISIONMISMATCH))
            {
              fprintf(stderr, "%s: Error: %s\n", argv[0], strerror(-res));
            }
          else
            {
              get_error_name(tmp1,res);
              fprintf(stderr, "%s: error: %s\n", tmp2, tmp1);
            }
          exit(1);
        }
      else
        {
          printf("%i\n",value.dummy);
          exit(0);
        }
    }
  else
    {
      printf("%s (RSBAC %s)\n***\n", argv[0], VERSION);
      printf("Use: %s (sockid process-id socket-fd)|(ipc-type id) attribute value\n",
             argv[0]);  
      printf("- ipc-types: sem, msg, shm, sockid,\n");
      printf("- attribute (string) and value = see following list:\n");
      for (j=0;j<RSBAC_IPC_NR_ATTRIBUTES;j++)
        {
          get_attribute_name(tmp1,attr_list[j]);
          get_attribute_param(tmp2,attr_list[j]);
          printf("%s \t%s\n",tmp1,tmp2);
        }
    }
  exit(1);
}
