/*
 * backlight.c - ipod backlight switching tool
 * 
 * The functions have been taken from podzilla's CVS source code 
 * and put together for use as a standalone app.
 * Took functions from podzilla and wrapped that main() function 
 * around it - by Thomas Perl <thp@perli.net>.
 *
 * Usage: Call without parameters to toggle backlight
 *        Call with _any_ parameters to switch backlight on
 *
 * HOW TO COMPILE IT:
 *  arm-elf-gcc -o backlight -Wall -elf2flt backlight.c
 * 
 * Copyright (C) 2004 Bernard Leach
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

#define FBIOGET_BACKLIGHT	_IOR('F', 0x24, int)
#define FBIOSET_BACKLIGHT	_IOW('F', 0x25, int)

#define FB_DEV_NAME		"/dev/fb0"
#define FB_DEVFS_NAME		"/dev/fb/0"

int ipod_set_backlight(int backlight);
int ipod_get_backlight(void);
static int ipod_ioctl(int request, int *arg);

int
main(int argc, char **argv)
{
	/**
	 * no parameters = toggle backlight
	 * any parameters = switch backlight on
	 **/
	
	if( argc == 1)
		ipod_set_backlight( !ipod_get_backlight());
	else
		ipod_set_backlight( 1);
	
	return 0;
}

int ipod_get_backlight(void)
{
	int backlight;

	if (ipod_ioctl(FBIOGET_BACKLIGHT, &backlight) < 0) {
		return -1;
	}

	return backlight;
}

int ipod_set_backlight(int backlight)
{
	if (ipod_ioctl(FBIOSET_BACKLIGHT, (int *) backlight) < 0) {
		return -1;
	}

	return 0;
}

static int ipod_ioctl(int request, int *arg)
{
	int fd;

	fd = open(FB_DEV_NAME, O_NONBLOCK);
	if (fd < 0) fd = open(FB_DEVFS_NAME, O_NONBLOCK);
	if (fd < 0) {
		return -1;
	}
	if (ioctl(fd, request, arg) < 0) {
		close(fd);
		return -1;
	}
	close(fd);

	return 0;
}

