/*
	Cuckoo Clock (version 0.1)

	Written by Anicka Bernathova <anicka@anicka.net>
	
	Many thanks to ViNiL for brilliant idea :-)

	This software may be freely distributed and used according to the terms
        of the GNU General Public License version 2.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/cdrom.h>
#include <syslog.h>

void
log_err(char* errmsg)
{
	openlog("cuckoo",LOG_PID,LOG_DAEMON);
	syslog(LOG_ALERT, errmsg);
	closelog();
}

void
daemonize(void)
{
	pid_t pid, sid;
	int i;

	pid=fork();
	
	if (pid<0)
		exit(1);
	if (pid>0)
		exit(0);
	sid=setsid();
	if (sid<0)
		exit(1);
	for (i=0; i<=2;i++) 
		close(i);
	i=open("/dev/null",O_RDWR); 
	dup(i); 
	dup(i);
	umask(027);
	if (chdir("/")<0)
		exit(1);
}

int 
main(int argc, char **argv)

{
	time_t t; 
	struct tm* lt;
	int i, cuckoo;
	char* device;

	if (argc<2)
		device="/dev/cdrom";
	else
		device=argv[1];

	daemonize();

	while (1){
	
		time(&t);

		lt=localtime(&t);

		if (lt->tm_min<59){
			sleep(60);
			continue;
		}
		
		sleep(60-lt->tm_sec);
		time(&t);
		t+=5; /* hack - we might wake up too early */
		lt=localtime(&t);			
		if (lt->tm_hour==0 || lt->tm_hour==12)
			cuckoo=12;
		else
			cuckoo=lt->tm_hour%12;
		int fd = open(device, O_RDONLY|O_NONBLOCK);
        	if (fd <0){
			log_err("Cannot open device");
                	exit(1);
		}

		for(i=0; i<cuckoo; i++){
			ioctl(fd, CDROMEJECT);
			sleep(1);
			ioctl(fd, CDROMCLOSETRAY);
		}

		close(fd);
	}
	return 0;
}

