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

#include <linux/packet.h>

void setup_dev(char *device, char *pkt_device, int rem)
{
	struct stat dstat;
	int fd = open(pkt_device, O_RDONLY);
	unsigned int cmd = rem ? PACKET_DEL_DEV : PACKET_SET_DEV;

	printf("device %s, pkt_device %s\n", device, pkt_device);

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

	if (stat(device, &dstat) < 0) {
		perror("stat");
		return;
	}
	if (ioctl(fd, cmd, dstat.st_rdev) < 0) {
		perror("PACKET_SET_DEV");
		return;
	}
	printf("%s %s\n", rem ? "removed" : "setup", device);
}

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

	if (argc == 1)
		return 1;

	while ((c = getopt(argc, argv, "d")) != EOF) {
		switch (c) {
			case 'd':
				rem = 1;
				break;
			default:
				printf("pktsetup [-d] /dev/cdrom /dev/packetX\n");
		}
	}
	setup_dev(argv[optind], argv[optind + 1], rem);
	return 0;
}