#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <linux/packet.h>

void setup_dev(char *pkt_device, char *device, int rem)
{
	int pkt_fd = open(pkt_device, O_RDONLY), dev_fd;
	unsigned int cmd = rem ? PACKET_TEARDOWN_DEV : PACKET_SETUP_DEV;

	if (!rem) {
		if ((dev_fd = open(device, O_RDONLY | O_NONBLOCK)) < 0) {
			perror("open device");
			return;
		}
	}
		
	printf("device %s, pkt_device %s\n", device, pkt_device);

	if (pkt_fd < 0) {
		perror("packet open");
		return;
	}

	if (ioctl(pkt_fd, cmd, dev_fd) < 0) {
		perror("PACKET_SET_DEV");
		return;
	}
	printf("%s %s\n", rem ? "removed" : "setup", pkt_device);
}

void usage(void)
{
	printf("pktsetup /dev/packet0 /dev/hdd\tsetup device\n");
	printf("pktsetup -d /dev/packet0\ttear down device\n");
}

int main(int argc, char **argv)
{
	int rem = 0, c;

	if (argc == 1) {
		usage();
		return 1;
	}

	while ((c = getopt(argc, argv, "d")) != EOF) {
		switch (c) {
			case 'd':
				rem = 1;
				break;
			default:
				usage();
				exit(1);
		}
	}
	setup_dev(argv[optind], argv[optind + 1], rem);
	return 0;
}
