 /*
  * ubusd_sigact.c
  * Copyright (C) Aitor Cuadrado Zubizarreta <aitor_czr@gnuinos.org>
  * 
  * simple-netaid is free software: you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  * Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  * 
  * simple-netaid is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  * See the GNU General Public License for more details.
  * 
  * You should have received a copy of the GNU General Public License along
  * with this program.  If not, see <http://www.gnu.org/licenses/>.
  * 
  * See the COPYING file.
  */


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

#include <libubox/ulog.h>
#include <libubox/usock.h>

#include "def.h"
#include "ubusd_sigact.h"
#include "ubusd.h"

/**
 * \brief Callback function for handling signals.
 * \param   sig   identifier of signal
 */
static void sig_handler(int signum)
{ 
   switch(signum) {
        
      case SIGHUP:
         ubusd_acl_load();
         break;
         
      case SIGTERM:
      case SIGINT:
      case SIGQUIT:
         {
           if( access( pid_file, F_OK ) == 0 ) {
              if (pid_fd != -1) {
                 int rc = lockf(pid_fd, F_ULOCK, 0);
                 if(rc != 0) exit(EXIT_FAILURE);
                 close(pid_fd);
              }
                     
              unlink(pid_file);
           }
          
           if( access( ubus_socket, F_OK ) == 0 ) {
              unlink(ubus_socket);
           }
         }  
         exit(EXIT_SUCCESS); /* we have been killed, exit gracefully. */
         
      default:
         break;
   }
}

void sigaction_init(void)
{
   struct sigaction sa;
   memset (&sa, 0, sizeof(sa));
     
   /*---------------- initialize signal handling ------------ */
   sa.sa_handler = sig_handler;
   sa.sa_flags = SA_RESTART;
   sigemptyset(&sa.sa_mask);
   sigaction(SIGHUP,  &sa, 0);
   sigaction(SIGTERM, &sa, 0);
   sigaction(SIGINT,  &sa, 0);
   sigaction(SIGQUIT, &sa, 0);
}
