/*
 * bright - change brightness of screen of an Genesi Efika MX Smartbook.
 *
 * Without argument it reports current brightness.
 *
 * To set absolute brightness, give it a number.
 *
 * To set relative brightness use +n and -n.
 * 
 * Copyright (c) 2011 Michael Cardell Widerkrantz, mc at the domain
 * hack.org.
 *
 * Permission to use, copy, modify, and/or distribute this software
 * for any purpose with or without fee is hereby granted, provided
 * that the above copyright notice and this permission notice appear
 * in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define BRIGHTNOW "/sys/class/backlight/pwm-backlight/actual_brightness"
#define BRIGHTFILE "/sys/class/backlight/pwm-backlight/brightness"

void deltabright(char *strdelta);
int readbright(void);
void writebright(char *brightness);

int readbright(void)
{
    int fd;
    char strbright[4];
    int bright;
    
    if (0 > (fd = open(BRIGHTNOW, O_RDONLY)))
    {
        perror("open");
        exit(1);
    }

    read(fd, &strbright, 3);
    strbright[3] = '\0';
    bright = atoi(strbright);
    
    close(fd);
    
    return bright;
}

void deltabright(char *strdelta)
{
    int bright;
    int delta;
    char strbright[4];

    delta = atoi(strdelta);
    
    /* Read current brightness. */
    bright = readbright();

    /* Adjust. */
    bright += delta;
    snprintf(strbright, 4, "%d", bright);

    /* Set new brightness. */
    writebright(strbright);
}

void writebright(char *brightness)
{
    int fd;
    int len;
    
    if (0 > (fd = open(BRIGHTFILE, O_WRONLY)))
    {
        perror("open");
        exit(1);
    }

    len = strlen(brightness);

    if (len != write(fd, brightness, len))
    {
        perror("write");
        exit(1);
    }

    close(fd);
}

int main(int argc, char **argv)
{
    char *brightness;
    
    if (2 != argc)
    {
        /* Without arguments we report current brightness. */
        printf("Current brightness: %d\n", readbright());
        exit(0);
    }

    brightness = argv[1];

    if ('-' == brightness[0] || '+' == brightness[0])
    {
        deltabright(brightness);
    }
    else
    {
        writebright(brightness);
    }
    
    exit(0);
}
