
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>

#include"zither.h"
#include<almemsys/almemsys.h>
#include"jpreturn.h"


extern global_data_t gd;


int life_thread(private_data_t * pd)
{
long int intime = 0;
long int oldtime = 0; 
int lostime = 0;
int count = 0;
char * swapsubject = (char *)calloc(IP_LEN, sizeof(char));
char * swapdata = (char *)calloc(IP_LEN, sizeof(char));

pthread_detach(pthread_self());

#ifdef LIFE_DEBUG
printf("LIFE_DEBUG: life_therad(): THREAD_START> %s\n", pd->rec.def_user);
#endif

oldtime = pd->life.in_life[0];

for(count = (pd->life.life_int + pd->life.life_los + 1); count > 0; count--){
   sleep(1);
   #ifdef LIFE_DEBUG
   printf("LIFE_DEBUG: life_thread(): THREAD_SLEEP_COUNT> %s count=%d life_cancel=%d\n",
     pd->rec.def_user, count, pd->life.cancel);
   #endif
   if( pd->life.cancel == -1 ){
      free(swapsubject);
      free(swapdata);
      return 0;
      }
   }

#ifdef LIFE_DEBUG
printf("LIFE_DEBUG: life_thread(): THREAD_TIME_STAT> %s oldtime=%ld in_life=%ld\n",
  pd->rec.def_user, oldtime, pd->life.in_life[0]);
#endif

if(oldtime == pd->life.in_life[0]){
   intime = (long int)time(NULL);
   lostime = intime - pd->life.in_life[0];

   #ifdef LIFE_DEBUG
   printf("LIFE_DEBUG: life_therad(): ERR_MAIL_SEND (2)> %s\n", pd->rec.def_user);
   #endif

   if(gd.md.in_mailonoff == 1){
      pd->life.swap4 = safe_sprintf(pd->life.swap4, BUF_MAX,
       "%s %d %s", CLIENT_HEAD_1, lostime, CLIENT_HEAD_2);

      // subject を作ります
      swapsubject = make_subject(swapsubject, CLIENT_BODY_6, pd->rec.def_user);

      // 本文をつくります
      swapdata = safe_sprintf(swapdata, BUF_MAX, "%s\n\n%s t\n\n%s\n", pd->rec.info, pd->life.swap4, CL_VAR);
      swap_mem(swapdata, '\n', (char)0x01);

      mail_grsend(pd->mail.server,
               pd->mail.from,
               pd->mail.rcptto,
               pd->mail.cc,
               swapdata,
               swapsubject,
               "NOT",
               "2");
      }

   }

#ifdef LIFE_DEBUG
printf("LIFE_DEBUG: life_therad(): THREAD_STOP> %s\n", pd->rec.def_user);
#endif

free(swapsubject);
free(swapdata);

return 0;
}









