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

#define VIBRATOR_DEV "/dev/vibrator"

#define VIBRATOR_MAJOR	108
#define VIBRATOR_IOCTL_BASE	0xbb
#define VIBRATOR_ENABLE		_IOW (VIBRATOR_IOCTL_BASE,1,int)
#define VIBRATOR_DISABLE	_IO (VIBRATOR_IOCTL_BASE,2)

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

	int arg;


	/* take exacly one argument */
	if (argc != 2) {
		fprintf(stderr, "usage: %s <level>\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	arg = atoi(argv[1]);
	if (arg < 0) {
		fprintf(stderr, "invalid argument: %s\n", argv[1]);
		exit(EXIT_FAILURE);
	}

	fd = open(VIBRATOR_DEV,  O_RDWR);
	if (fd < 0) {
		perror(VIBRATOR_DEV);
		exit(EXIT_FAILURE);
	}

	if (arg == 0) {
		ret = ioctl(fd, VIBRATOR_DISABLE, &arg);
		if (ret < 0) {
			fprintf(stderr, "cannot disable vibrator\n");
			exit(EXIT_FAILURE);
		}
	} else {
		if (arg > 4)
			arg = 4;

		arg = arg - 1;

		ret = ioctl(fd, VIBRATOR_ENABLE, &arg);
		if (ret < 0) {
			fprintf(stderr, "cannot set vibrator level\n");
			exit(EXIT_FAILURE);
		}
	}

	close(fd);
	exit(EXIT_SUCCESS);
}

