#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <string.h> 
#include <sys/types.h> 
#include <netinet/in.h> 
#include <netdb.h> 
#include <sys/socket.h> 
#include <sys/wait.h> 

/*whattodo */
#define DELETE_ALL 2 // Delete all entries
#define FORWARD 1 //Forward
#define DROP 0 //Drop


/*filter ids */
#define SRC_PORT 1 // (16 bits)
#define DST_PORT 2
#define SRC_ADDR 3 // (32 bits)
#define DST_ADDR 4
#define PROTOCOL 5 //  (8 bits)

struct Filter{
  int policy_id; //which policy it belongs to
  int filter_id; //type of filter (e.g src port)
  int filter_value; //either contains the value or the address (pointer) to the value
  int filter_mask; //applies if masks are necessary (we know if its necessary by looking at the policy_id
};

struct Admin_struct{
  int whattodo;
  int numfilters;
  struct Filter filts[6];
};

int main(int argc, char *argv[]){
 FILE* fileptr;
 struct Admin_struct new_policy;      
 int i = 0;
 char* s = malloc(3*sizeof(struct Admin_struct));
 char* ptr;

 if((fileptr = fopen("packet_output" , "r")) == NULL){
    printf("Cannot open packet_output\n");
  }

 // char *fgets(char *s, int size, FILE *stream);
 
 if(fgets(s, 3*sizeof(struct Admin_struct), fileptr) == NULL){
   printf("Could not read the packet in\n");
 }
 
 //printf("This is the string we just read in: \n %s \n", s);
 
 /* Call Strtok to parse values in the packet */
 //  char *strtok(char *s, const char *delim);
 
 ptr = strtok(s, " ");
 new_policy.whattodo = atoi(ptr);
 printf("What to do = %d\n", new_policy.whattodo);

 ptr = strtok(NULL, " ");
 new_policy.numfilters = atoi(ptr);
 printf("Numfilters = %d\n", new_policy.numfilters);

 for(i = 0; i <new_policy.numfilters; i++){
    ptr = strtok(NULL, " ");
    new_policy.filts[i].policy_id = atoi(ptr);
    printf("Policy_id = %d\n", new_policy.filts[i].policy_id);
    ptr = strtok(NULL, " ");
    new_policy.filts[i].filter_id = atoi(ptr);
    printf("Filter_id = %d\n", new_policy.filts[i].filter_id);
  
    if(new_policy.filts[i].filter_id ==3 || new_policy.filts[i].filter_id ==4){
        ptr = strtok(NULL, " ");
	sscanf(ptr, "%x", &new_policy.filts[i].filter_value);
	printf("IP address values is %x \n",new_policy.filts[i].filter_value);
	ptr = strtok(NULL, " ");
	sscanf(ptr, "%x", &new_policy.filts[i].filter_mask);
	printf("IP mask values is %x \n",new_policy.filts[i].filter_mask);
    }
    else{
        ptr = strtok(NULL, " ");  
	new_policy.filts[i].filter_value = atoi(ptr);
	printf("IP port/protocol value is %x \n",new_policy.filts[i].filter_value);
	ptr = strtok(NULL, " ");
	new_policy.filts[i].filter_mask = atoi(ptr);
	printf("IP port/protocol mask is %x \n",new_policy.filts[i].filter_value);
    }
 }
 free(s);

}
