#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sched.h>

// "Modulate" LED or backlight brightness

char* bright;
int bright_len;
char* dark;
int dark_len;
int microseconds_bright;
int microseconds_dark;
int f;

char* file;

static void signal_handler() {
    f = open(file, O_WRONLY);
    write(f, bright, bright_len);
    close(f);
    exit(0);
}


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

    if(argc!=7) {
	printf("Usage: andrback /sys/class/leds/.../brightness 255 0  0 33333 0 (once?)\n");
	return 1;
    }

    bright = argv[2];
    bright_len = strlen(bright);
    dark = argv[3];
    dark_len = strlen(dark);
    microseconds_bright = atoi(argv[4]);
    microseconds_dark = atoi(argv[5]);
    int once = atoi(argv[6]);
    
    file = argv[1];
  
    struct sigaction sa = {signal_handler};
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    struct sched_param sp = { 10 };
    sched_setscheduler(0, SCHED_FIFO, &sp);

    for(;;) {
        f = open(file, O_WRONLY);
        write(f, bright, bright_len);
        close(f);

        if(microseconds_bright) { usleep(microseconds_bright); }
        
        f = open(file, O_WRONLY);
        write(f, dark, dark_len);
        close(f);

        if (once) break;
        
        usleep(microseconds_dark);
    }
}
