#include "melange.h"

void signal_ResetSignals();
void signal_SetSignals();
void signal_MainSignalHandler(int sigNum);
void signal_SignalBrokenPipe(int sigNum);
void signal_SignalHangUp(int sigNum);
void signal_SignalProgrammFault(int sigNum);
void signal_SignalKill(int sigNum);

void signal_SetSignals() {
   signal(SIGHUP,signal_SignalHangUp);
   signal(SIGURG,signal_SignalKill);
   
   signal(SIGBUS,signal_SignalProgrammFault);
   signal(SIGILL,signal_SignalProgrammFault);
   signal(SIGIOT,signal_SignalProgrammFault);
   signal(SIGFPE,signal_SignalProgrammFault);
   signal(SIGSEGV,signal_SignalProgrammFault);
   
   signal(SIGPIPE,signal_SignalBrokenPipe);
   
   signal(SIGINT,signal_MainSignalHandler);
   signal(SIGQUIT,signal_MainSignalHandler);
   signal(SIGABRT,signal_MainSignalHandler);
   signal(SIGALRM,signal_MainSignalHandler);
}

void signal_ResetSignals() {
   signal(SIGHUP,SIG_DFL);
   signal(SIGURG,SIG_DFL);
   signal(SIGTERM,SIG_DFL);
   signal(SIGBUS,SIG_DFL);
   signal(SIGILL,SIG_DFL);
   signal(SIGIOT,SIG_DFL);
   signal(SIGFPE,SIG_DFL);
   signal(SIGSEGV,SIG_DFL);
   signal(SIGPIPE,SIG_DFL);
   signal(SIGINT,SIG_DFL);
   signal(SIGQUIT,SIG_DFL);
   signal(SIGABRT,SIG_DFL);
   signal(SIGALRM,SIG_DFL);
}

void signal_MainSignalHandler(int sigNum) {
    snprintf(infoText, MAX_INFO_TEXT + 1,"melangeServerLoop()::SIGNAL #%d caught (non fatal): %s\r\n",sigNum,sys_siglist[sigNum]);
    *(infoText + MAX_INFO_TEXT) = '\0';    
    util_WriteLog(1,infoText);
}

void signal_SignalBrokenPipe(int sigNum) {
    snprintf(infoText, MAX_INFO_TEXT + 1,"melangeServerLoop()::SIGNAL #%d caught (BROKEN PIPE): %s\r\n",sigNum,sys_siglist[sigNum]);
    *(infoText + MAX_INFO_TEXT) = '\0';
    util_WriteLog(1,infoText);
}

void signal_SignalKill(int sigNum) {
    snprintf(infoText, MAX_INFO_TEXT + 1,"melangeServerLoop()::SIGNAL #%d caught (SHUTTING DOWN): %s\r\n",sigNum,sys_siglist[sigNum]);
    *(infoText + MAX_INFO_TEXT) = '\0';
    util_WriteLog(1,infoText);
    util_WriteMsgLog(infoText);
    admin_ShutDown();
    raise(SIGTERM);
}

void signal_SignalHangUp(int sigNum) {
    util_ResetLog(DEFAULT);
    snprintf(infoText, MAX_INFO_TEXT + 1,"melangeServerLoop()::SIGNAL #%d caught (HANGUP): %s\r\n",sigNum,sys_siglist[sigNum]);
    *(infoText + MAX_INFO_TEXT) = '\0';
    util_WriteLog(1,infoText);
    util_WriteMsgLog(infoText);
}

void signal_SignalProgrammFault(int sigNum) {
    snprintf(infoText, MAX_INFO_TEXT + 1,"melangeServerLoop()::SIGNAL #%d caught (FATAL PROGRAM ERROR, SHUTTING DOWN): %s\r\n",sigNum,sys_siglist[sigNum]);
    *(infoText + MAX_INFO_TEXT) = '\0';
    util_WriteLog(1,infoText);
    util_WriteMsgLog(infoText);
    admin_ShutDown();
    raise(SIGTERM);
}
