/* 
 * File:   launch_server.c
 * Author: blackpanther
 *
 * Created on October 28, 2010, 11:17 AM
 */

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

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include "shared_data.h"

#define MY_ID          "SERVER"

#define SECRET_KEY     8594.244

#define forkProgram(programPath,programName,order)\
    fork_id[order -1] = fork();                      \
    switch(fork_id[order -1])                        \
    {                                      \
        case -1:                           \
            perror("fork problem : ");     \
            return -5;                     \
            break;                         \
        case 0:                            \
            execl(programPath,programName,NULL);   \
            puts("Something is wrong, really really wrong..."); \
            printf("Cause ?");             \
            puts(programName);             \
            return -10;                    \
            break;                         \
        default:                           \
            printf("Launched program : "); \
            printf(programName);           \
            printf("\n");                  \
            break;                         \
    }                                      \

int main(void) {

    int     shm_id;
    double* shm_data;
    pid_t   fork_id[2];

    say(MY_ID,"");

    //Creation de la mémoire partagé pour stocker la clef secrete (double)
    shm_id = shmget(UNIQUE_SHM_KEY, sizeof(double), IPC_CREAT);
        handle(shm_id < 0,"shmget: ",-1);
        printf("SERVER -< Shm id : %d\n",shm_id);

    //On s'attache à la mémoire obtenu
    shm_data = shmat(shm_id, NULL, 0);
        printf("SERVER -< Shm at : %p\n",shm_data);
        handle(shm_data == (void *)-1,"shmat: ",-2);

    // On insère la clef
    *shm_data = SECRET_KEY;

    // On se détache de la mémoire
        handle(shmdt(shm_data) < 0,"shmdt: ",-3);
        printf("SERVER -< Shm dt : %p\n",shm_data);

    say(MY_ID,"Forking delegator...");
    forkProgram("./delegator","delegator",1);

    say(MY_ID,"Forking logger...");
    forkProgram("./logger","logger",2);

    waitpid(fork_id[0],NULL,0);
    waitpid(fork_id[1],NULL,0);

    //FIXME
    //printf("Well, now you got 1000sec to do  what you want...\n");
    //sleep(1000);

    say(MY_ID,"successfully terminated");

    return (EXIT_SUCCESS);
}

