/*

                                   _JNJ`                        
                               .JNMH`                           
                              JMMF`       `;.                   
                            .NMM)          `MN.                 
                            MMM)            (MML                
                           (MMM`             MMML               
                     M  I  D  N  I  G  H  T    C  o  D  E       
                           (NMMF             MHNH               
                            NMML            .MMM                
                             NMML          .NMH                 
                              4MMNL       .#F                   
                               `4HNNL_   `                      
                                   `"""`                        

                          Copyright (C) 2004-2007
       "Ian (Larry) Latter" <ian dot latter at midnightcode dot org>

    Midnight Code is a registered trademark of Ian Latter.

    This program 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, and mirrored at the Midnight Code web
    site; as at version 2 of the License only.
  
    This program 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
    (version 2) along with this program; if not, write to the Free
    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA, or see http://midnightcode.org/gplv2.txt

*/

/* configd.c :: Midnight Code network config example program		*/


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>


#include <libmidnightcode.h>


int
main(int argc, char **argv) {
  int cfg_control;
  int cfg_deadpeer;
  int cfg_protocol;
  char cfg_config_file_name[128] = "\0";
  struct in_addr cfg_to_host;
  int cfg_port;
  int cfg_help = 0;
  void * tmp_void_p;
  struct midnightcode_config_head_t * config_list_head_p;
  struct midnightcode_socket_head_t * sockets;
  struct midnightcode_socket_element_t * socket;
  struct midnightcode_socket_element_t * socket_client;
  struct midnightcode_webint_message_t message;
  struct midnightcode_webint_message_t * message_p;
  char * buffer;
  int buffer_len;
  int buffer_total;
  int found_client;
  time_t time_start;
  time_t time_stop;
  int time_taken;
  int got_size_bundle;
  char size_bundle[32];
  int ret_i;


 
  // Prepare switches
  struct midnightcode_switch_t switches[] = {
    { "p", "port", "Port to listen on / connect to (98)",
      MIDNIGHTCODE_PARSE_TYPE_INT, 0, 0, &cfg_port },
    { "u", "udp", "Use UDP instead (TCP)",
      MIDNIGHTCODE_PARSE_TYPE_NONE, 0, 0, &cfg_protocol },
    { "c", "config_file", "Config file, to work from",
      MIDNIGHTCODE_PARSE_TYPE_STRING, 128, 0, &cfg_config_file_name },
    { "r", "raw_socket", "Use CONTROL_RAW -v- CONTROL_MIDNIGHTCODE",
      MIDNIGHTCODE_PARSE_TYPE_NONE, 0, 0, &cfg_control },
    { "dp", "deadpeer", "Enable DPD (CONTROL_MIDNIGHTCODE only)",
      MIDNIGHTCODE_PARSE_TYPE_NONE, 0, 0, &cfg_deadpeer },
    { "h", "help", "Display this help/usage screen",
      MIDNIGHTCODE_PARSE_TYPE_NONE, 0, 0, &cfg_help },
    { 0 }
  };



  // Set-up initial values;
  memset(&cfg_config_file_name, 0, sizeof(cfg_config_file_name));
  memset(&cfg_to_host, 0, sizeof(struct in_addr));
  cfg_control = 0;
  cfg_deadpeer = 0;
  cfg_port = MIDNIGHTCODE_WEBINT_PORT;
  cfg_protocol = 0;

  got_size_bundle = 0;
  memset(&size_bundle, 0, sizeof(size_bundle));



  // Process switches
  if((ret_i = midnightcode_switch_process(argc, argv, switches)) != 0) {
    fprintf(stdout, "\n");
    midnightcode_logo(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON);
    midnightcode_license(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON, 
      MIDNIGHTCODE_LICENSE_TEXT_COPYRIGHT);
    fprintf(stdout, "    Error in switches, switch \"%s\" is unkown"
      " at parameter number %d.\n\n", argv[ret_i], ret_i);
    midnightcode_switch_usage(MIDNIGHTCODE_SWITCH_STYLE_SOFT, argv[0],
      switches);
    exit(1);
  }
  if(cfg_help) {
    midnightcode_logo(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON);
    midnightcode_license(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON, 
      MIDNIGHTCODE_LICENSE_TEXT_COPYRIGHT);
    midnightcode_switch_usage(MIDNIGHTCODE_SWITCH_STYLE_SOFT, argv[0],
      switches);
    exit(1);
  }
  fflush(stdout);



  // Process license and logo
  midnightcode_logo(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON);
  midnightcode_license(0, MIDNIGHTCODE_COLOUR_STYLE_BLOOD_MOON, 
    MIDNIGHTCODE_LICENSE_TEXT_ALL);



  // Program title
  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_H1,
    MIDNIGHTCODE_STATUS_STYLE_NORMAL, "Config daemon example: %s", argv[0]);

  fprintf(stdout, "\n");
  fflush(stdout);




  // Validate user params
  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                           MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                           "Validating user parameters");
  if(!strlen(cfg_config_file_name)) {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
    fprintf(stdout, "\n");
    exit(1);
  }
  midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);



  // Config structure initialisation
  midnightcode_list_init(config_struct_head, midnightcode_config_element_t);
  tmp_void_p = (void *)&config_struct_head;
  config_list_head_p = tmp_void_p;


  // Load config file
  if(midnightcode_init_config_load(cfg_config_file_name,
    config_list_head_p, 0) != 0) {
    fprintf(stdout, "\n");
    exit(1);
  }



  // Resolve user settings
  if(cfg_control == 0) {
    cfg_control = MIDNIGHTCODE_SOCKET_CONTROL_MIDNIGHTCODE;
  } else {
    cfg_control = MIDNIGHTCODE_SOCKET_CONTROL_RAW;
  }
  if(cfg_deadpeer == 0) {
    cfg_deadpeer = MIDNIGHTCODE_SOCKET_DPD_DISABLE;
  } else {
    cfg_deadpeer = MIDNIGHTCODE_SOCKET_DPD_DISABLE;
    if(cfg_control == MIDNIGHTCODE_SOCKET_CONTROL_MIDNIGHTCODE)
      cfg_deadpeer = MIDNIGHTCODE_SOCKET_DPD_ENABLE;
  }
  if(cfg_protocol == 0) {
    cfg_protocol = MIDNIGHTCODE_SOCKET_PROTOCOL_TCP;
  } else {
    cfg_protocol = MIDNIGHTCODE_SOCKET_PROTOCOL_UDP;
  }







  // Socket Initialisation
  midnightcode_list_init(socket_struct_head, midnightcode_socket_element_t);
  tmp_void_p = (void *)&socket_struct_head;
  sockets = tmp_void_p;

  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                           MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                           "Initialising socket library");
  if(midnightcode_socket_initialise(sockets) < 0) {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
    fprintf(stdout, "\n");
    exit(1);
  } else {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
  }

  time_taken = 0;


  // Initialise listener socket
  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                           MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                           "Installing listener socket");
  if(midnightcode_socket_open(&socket,
    cfg_control,
    cfg_deadpeer,
    1, MIDNIGHTCODE_SOCKET_DIR_LISTEN,
    cfg_protocol, "127.0.0.1", cfg_port) < 0) {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
    fprintf(stdout, "\n");
    exit(1);
  } else {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
  }


  while(1) {

    // find a client connection
    found_client = 0;

    while(!found_client) {

      socket_client = NULL;

      if(cfg_protocol == MIDNIGHTCODE_SOCKET_PROTOCOL_UDP) {
        if(socket->direction != MIDNIGHTCODE_SOCKET_DIR_RECEIVE)
          continue;
        socket_client = socket;
        found_client = 1;
        continue;
      }

      if(cfg_protocol == MIDNIGHTCODE_SOCKET_PROTOCOL_TCP) {
        midnightcode_list_for_each(socket_client, sockets) {
          if(socket_client->state != MIDNIGHTCODE_SOCKET_STATE_OPERATIONAL)
            continue;
          if(socket_client->ipv4_remote.s_addr != 0 &&
            socket_client->port_remote != 0) {
            found_client = 1;
            break;
          }
        }
      }

      usleep(MIDNIGHTCODE_SOCKET_POLL_TIME);
    }



    // If only one client is going to be accepted, kill the listener
    if(cfg_protocol == MIDNIGHTCODE_SOCKET_PROTOCOL_TCP) {

      // Closing listener socket
      /*
      midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                               MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                               "Closing listener socket");
      if(midnightcode_socket_close(socket)) {
        midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
        fprintf(stdout, "\n");
        exit(1);
      } else {
        midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
      }
      */

    }



    // Have client connection
    midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                             MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                             "Have client connection; %s:%d -[%d]-> %s:%d",
                             socket_client->ipv4_remote_s,
                             socket_client->port_remote,
                             socket_client->state,
                             socket_client->ipv4_local_s,
                             socket_client->port_local);
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);



    // Start timer
    buffer_total = 0;
    time(&time_start);
    


    // Read socket data
    buffer = NULL;
    while(socket_client->state == MIDNIGHTCODE_SOCKET_STATE_OPERATIONAL) {



      // Reset
      usleep(MIDNIGHTCODE_SOCKET_POLL_TIME);
      if(buffer != NULL)
        free(buffer);
      buffer = NULL;
      buffer_len = 0;



      // Read socket data
      ret_i = midnightcode_socket_read_block(socket_client,
                &buffer, &buffer_len, 1, MIDNIGHTCODE_SOCKET_IO_NONBLOCKING);
      if(ret_i <= 0)
        continue;



      // Keep track of totals
      buffer_total += buffer_len;



      // Receive data
      message_p = &message;

      midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                               MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                               "Received data block");
      midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);

      midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                               MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                               "Decoding config protocol query");
      if(midnightcode_webint_membrane(MIDNIGHTCODE_WEBINT_MEMBRANE_DECODE,
        &buffer, &buffer_len, &message_p) == 0) {
        midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);

        midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_BLURB,
                                 MIDNIGHTCODE_STATUS_STYLE_UNKNOWN,
                                 "Q=%d T=%d S=%d [%s]",
                                 message_p->query, message_p->type,
                                 message_p->buffer_size, message_p->buffer);

      } else {
        midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
      }
      free(buffer);
      buffer = NULL;
      buffer_len = 0;



      // Translate
      switch(message_p->query) {

        case MIDNIGHTCODE_WEBINT_QUERY_GET:

          memset(message_p, 0, sizeof(struct midnightcode_webint_message_t));

          // Dump config into response buffer
          midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                                   MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                                   "Exporting config to protocol buffer");
          if(midnightcode_config_write(config_list_head_p,
            &message_p->buffer, &message_p->buffer_size,
            MIDNIGHTCODE_CONFIG_TYPE_NEWSET, 0) != 0) {
            midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
          } else {
            midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);

            // Return response
            message_p->query = MIDNIGHTCODE_WEBINT_QUERY_ACK;
            message_p->type = 0;

            midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                                     MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                                     "Encoding config protocol response");
            if(midnightcode_webint_membrane(MIDNIGHTCODE_WEBINT_MEMBRANE_ENCODE,
              &buffer, &buffer_len, &message_p) != 0) {
              midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
            } else {
              midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);

              midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                                       MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                                       "Sending data block");
              if(midnightcode_socket_write_block(socket_client,
                buffer, buffer_len, MIDNIGHTCODE_SOCKET_IO_BLOCKING) <= 0) {
                midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
              } else {
                midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
              }

              if(buffer_len > 0) {
                buffer_len = 0;
                free(buffer);
                buffer = NULL;
              }
            }
          }
          if(message_p->buffer_size > 0) {
            message_p->buffer_size = 0;
            free(message_p);
          }
          break;


        case MIDNIGHTCODE_WEBINT_QUERY_ACK:

          // Closing client socket
          midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                                   MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                                   "Closing client socket");
          if(midnightcode_socket_close(socket_client)) {
            midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_WARN);
          } else {
            midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
          }
          break;

       }

    }



    // Stop timer
    time(&time_stop);
    time_taken = (int)(time_stop - time_start);
    if(time_taken < 1)
      time_taken = 1;



    found_client = 0;
  }



  // Socket shutdown
  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_TEXT,
                           MIDNIGHTCODE_STATUS_STYLE_NORMAL,
                           "Shutdown socket library");
  if(midnightcode_socket_shutdown(sockets) < 0) {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_FAIL);
    fprintf(stdout, "\n");
    exit(1);
  } else {
    midnightcode_status_flag(MIDNIGHTCODE_STATUS_FLAG_OKAY);
  }



  // Transfer rate
  fprintf(stdout, "\n");
  midnightcode_status_text(MIDNIGHTCODE_STATUS_TYPE_BLURB,
                           MIDNIGHTCODE_STATUS_STYLE_UNKNOWN,
    "%d bytes in %d seconds = %02.2fMbytes/sec",
    buffer_total, time_taken,
    (float)((float)buffer_total / (float)(time_taken)) / (float)1000000);
  fprintf(stdout, "\n");


  exit(0);
}
