#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <linux/myxmap.h>
#include <linux/mtd/mtd.h>

int		mtd_fd;
u_int32_t	mtd_flags;

void
usage(char * argv0, int rc)
{
	fprintf(stderr, "usage: %s <mtd device> <enable/disable>\n", argv0);
	exit(rc);
}

void
show_flags(void)
{
	printf("mtd_flags<%08lx>: ", mtd_flags);
	printf("%cset ", mtd_flags & MTD_SET_BITS ? '+' : '-');
	printf("%cclear ", mtd_flags & MTD_CLEAR_BITS ? '+' : '-');
	printf("%cwriteable ", mtd_flags & MTD_WRITEABLE ? '+' : '-');
	printf("\n");
}

int
do_enable(char * arg)
{
	if (strcmp(arg, "writeable") == 0) {
		mtd_flags |= MTD_CLEAR_BITS;
		return(0);
	}
	return(-1);
}

int
do_disable(char * arg)
{
	if (strcmp(arg, "writeable") == 0) {
		mtd_flags &= ~MTD_WRITEABLE;
		return(0);
	}
	return(-1);
}

int
do_arg(char * arg)
{
printf("do_arg<%s>\n", arg);
	switch (arg[0]) {
	case '+':
		return( do_enable(&arg[1]) );
	case '-':
		return( do_disable(&arg[1]) );
	}
	return(-1);
}

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

	if (argc < 2) {
		usage(argv[0], 1);
	}

	if ((mtd_fd = open(argv[1], O_RDONLY)) == -1) {
		fprintf(stderr, "mtd dev<%s> ", argv[1]);
		perror("open failed");
		exit(errno);
	}

	if (ioctl(mtd_fd, MEMGETFLAGS, &mtd_flags) != 0) {
		perror("mtd ioctl MEMGETFLAGS error");
		close(mtd_fd);
		exit(errno);
	}
	show_flags();

	if (argc == 2) {
		close(mtd_fd);
		exit(0);
	}

	for (i=2; i<argc; i++) {
		if (do_arg(argv[i]) == -1) {
			close(mtd_fd);
			usage(argv[0], 1);
		}
	}
	show_flags();

	if (ioctl(mtd_fd, MEMSETFLAGS, &mtd_flags) != 0) {
		perror("mtd ioctl MEMSETFLAGS error");
		close(mtd_fd);
		exit(errno);
	}
	close(mtd_fd);
	exit(0);
}
