/* this is a simple program to return the state of the
 * the two xtouch screens
 */

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define FILE_MODE	O_RDWR
#define GNOME_LOG_FILE	"/var/log/ventana/gnome-state.log"



int main(int argc, char* argv[])
{
   char file_state;
   int fd;
   int n;
   char state_spawned = '1';
   char state_not_spawned = '0';
   char readVar[10];

    if ((fd = open(GNOME_LOG_FILE, FILE_MODE)) < 0) {
    	/* create our log file */
    	if ((fd = creat(GNOME_LOG_FILE, FILE_MODE)) < 0) {
    		printf("couldn't create file. exiting\n");
    		exit(0);
    		// write the state into the file
    		write(fd, &state_not_spawned, 1);
    	}
    }

	printf("usage: gnome-spawned [state]\n");
        printf("[state]: no arg == check state\n");
        printf("       :  0 == set state to zero - 2nd gnome not spawned\n");
        printf("       :  1 == set state to one - 2nd gnome spawned\n");

   /* the first argument is used keep track of our state */
   if (argc == 1) {
   	/* environment variable is polling for the state of the 2nd
   	 * gnome session
   	 */
   	 if (lseek(fd, 0, SEEK_SET) == -1) {
   	 	printf("seek error\n");
   	 	exit(0);
   	 }
   
	 memset(readVar, 0, 10);
	
   	 if ((n = read(fd, readVar, 10)) < 0) {
   	 	printf("read error\n");
   	 	exit(0);
   	 }
   
	if (strcmp(readVar, "ON") == 0) {
		printf("ON..........\n");
		return 1;
	}
	if (strcmp(readVar, "OFF") == 0) {
		printf("OFF.........\n");
		return 0;
	}
			
   }	

   if (argc == 2) {
   	/* set state */
   	
   	file_state = (char) atoi(argv[1]);
	printf("file state: %x\n", file_state);
   	
   	 if (lseek(fd, 0, SEEK_SET) == -1) {
   	 	printf("seek error\n");
   	 	exit(0);
   	 }
   	 
	if (file_state) {

		if ((n = write(fd, "ON", 3)) != 3) {
   	 		printf("wrote error\n");
   	 		exit(0);
   	 	}

	} else {
   
	 	if ((n = write(fd, "OFF", 4)) != 4) {
   	 		printf("wrote error\n");
   	 		exit(0);
   	 	}
 	}
   	 return file_state;	 	
   }


}
