#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>

#include <daemonize.h>

/*
 * Les outils
 */
static void signal_handler(int sig){
    char msg[200];
    sprintf(msg,"process %d signal %d trapped\n", getpid(), sig);
    log_signal_message("/tmp/daemonize.log", msg);

    switch(sig){
    case SIGUSR1:
        // signal USR1
        break;
    case SIGUSR2:
        // Signal USR2
        break;
    case SIGHUP:
        // Reload conf and reinitialize processus
        break;
    case SIGINT:
        // CTRL+C
    case SIGTERM:
        // Terminate : kill -15
        exit(0);
        break;
    }
}

#define array_len(a) ( sizeof(a) / sizeof(a[0]) )

int main(int ac, char** av)
{
    /*
     * Daemonize
     */
    daemonize();
    
    /*
     * Trapper les signaux pour fermer correctement le programme
     */
    int les_signaux_ign[] = { SIGCHLD, SIGTSTP, SIGTTOU, SIGTTIN };
    int les_signaux[] = { SIGHUP, SIGTERM, SIGINT };
    size_t n;

    n = array_len(les_signaux_ign);
    for(int i = 0; i < n; i++)
    {
    	if (signal(les_signaux_ign[i],SIG_IGN) == SIG_ERR)
    	{
            printf("\ncan't catch signal %d\n", les_signaux_ign[i]);
            return 1;
        }
    }

    n = array_len(les_signaux);
    for(int i = 0; i < n; i++)
    {
        if (signal(les_signaux[i],signal_handler) == SIG_ERR)
        {
            printf("\ncan't catch signal %d\n", les_signaux[i]);
            return 1;
        }
    }

    for(;;) { sleep(10); }

    return 0;
}
