#!/bin/sh

if ! modprobe -a helloioctl; then
	echo "Could not load module helloioctl.ko!"
	exit 1
fi

major=$(grep hello /proc/devices | cut -d ' ' -f1)
if [ -z "$major" ]; then
	echo "no major number found!"
	echo "helloioctl expected"
	exit 1
fi

device=/dev/mycustomhello

if ! mknod "$device" c "$major" 0; then
	echo "could not create device!"
	exit 1
fi

printf '%s' '
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#include "helloioctl.h"


int main(int argc, char **argv) {
	int fd;
	char buf[256];

	if ((fd = open(argv[1], O_RDWR)) < 0) {
		perror("open");
		return -1;
	}

	if (ioctl(fd, HELLO, buf) < 0) {
		perror("ioctl");
		return -1;
	}

	printf("%s\n", buf);

	return 0;
}' > userioctl.c

find /linux* -type f -name "helloioctl.h" -print0 | xargs -0 -I {} cp {} .

if ! [ -f helloioctl.h ]; then
	echo "helloioctl.h file not found!"
	echo "please include this file to your submission"
	exit 1
fi

if ! gcc userioctl.c ; then
	echo "can't compile user program to test ioctl!"
	echo "fix your header file!"
	exit 1
fi

if ! out=$(./a.out "$device"); then
	echo "error while running user program"
	exit 1
fi

if [ -z "$out" ] || ! printf "%s" "$out" | grep -i hello; then
	echo "hello string not found from userspace!"
	exit 1
fi

if ! rmmod helloioctl; then
	echo "Fail while unloading module"
	exit 1
fi
