#include "arp_packet.h"

#define CLEAR(x) memset(&(x), 0x00, sizeof(x))

#define IFNAME "tap0"
// #define IFNAME "tun0"


#define BUFLEN 1600

static int tun_alloc(char *dev)
{
    struct ifreq ifr;
    int fd, err;

    if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
        perror("Cannot open TUN/TAP dev\n"
                    "Make sure one exists with "
                    "'$ mknod /dev/net/tun c 10 200'");
        exit(1);
    }

    CLEAR(ifr);

    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *
     *        IFF_NO_PI - Do not provide packet information
     */
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
    if( *dev ) {
        strncpy(ifr.ifr_name, dev, IFNAMSIZ);
    }

    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
        perror("ERR: Could not ioctl tun");
        close(fd);
        return err;
    }

    strcpy(dev, ifr.ifr_name);
    return fd;
}

// int check_ip(uint8_t * ip, int length){
	// if(length != TARGET_IP_A_S) return UNEQUAL;
	// int8_t pc2[4]={10,5,1,2};
	// for(size_t i = 0 ; i < length ; i++)
	// 	printf("%X, %X \n", ip[i], pc2[i]);
// 
	// for(size_t i = 0 ; i < length ; i++)
	// 	if(ip[i]!=pc2[i]) return FAILED;
	// return SUCCESS;
//} 
// 
int main (int argc, char *argv[]){

  char dev[IFNAMSIZ];
  int tun_fd;

	uint8_t local_ip[4] = {10, 5, 1, 10};
	uint8_t local_mac[6] = {0xD6,0x74,0x45,0xDC,0x5A,0xCD};


  if (argc > 1) {
    assert(strlen(argv[1]) < IFNAMSIZ);
    strcpy(dev, argv[1]);
  } else {
    strcpy(dev, IFNAME);
  }

  printf("device name: %s\n", dev);

  tun_fd = tun_alloc(dev);

  int running = 1;

  uint8_t buf[BUFLEN];
  while (running) {
    int nread;

    if ((nread = read(tun_fd, buf, BUFLEN)) < 0) {
      perror("ERR: Read from tun_fd");
      break;
    }
		// buf[nread] = '\0';
		printf("buf :");
		print_hex(buf, nread);

		mac_hdr hdr;
		pkt_data pkt;
		if(parse_arp_packet(&hdr, &pkt, buf, nread) == FAILED){
			perror("ERR: Cannot parse the packet");
		}
		if(receive_arp_packet(&hdr, &pkt, buf, nread, local_ip, local_mac) == FAILED){
			perror("ERR: Cannot process the packet");
		}
		if(send_arp_response(tun_fd, buf, nread, &pkt, &hdr) == FAILED){
			perror("ERR: Cannot send the response");
		}
		
    printf("Read %d bytes from device %s\n\n", nread, dev);
  }

  close(tun_fd);

  return EXIT_SUCCESS;
}
