#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.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"


int get_file2(char *, char, int, int);



/* ------------------ FILE SET 1.1.7 以上の為 ----------------- */
int file_sets2( private_data_t * pd, char delim, int sk, int interval)
{
int stat;
int inA = 1;
int count, cho;
// char * tmp;

char * chA = (char *)calloc(IP_LEN, sizeof(char));
char * chB = (char *)calloc(IP_LEN, sizeof(char));
char * chC = (char *)calloc(IP_LEN, sizeof(char));

chA = safe_memcpy(chA, pd->rec.data, BUF_MAX);
count = strlen(pd->rec.data);
cho = mem_count(pd->rec.data,':');

// printf("file_sets2(): %s\n", pd->rec.data);

// if( NULL != strchr(pd->rec.data,':') && 3 <= cho && (count - cho) > 3 && count > 7 && 1 != mem_count(pd->rec.data, '#')){
//    chB = safe_memcpy(chB, strtok_r(chA, ":", &tmp), BUF_MAX);

inA = file_check(pd->rec.data);
stat = 1;
switch(inA){
   case 1 : stat = get_file2(pd->file.bat_filename, (char)delim, sk, interval);
           break;  
   case 2 : stat = get_file2(pd->file.scan_filename, (char)delim, sk, interval);
           break;  
   case 3 : stat = get_file2(pd->file.conf_filename, (char)delim, sk, interval);
           break;  
   case 4 : stat = get_file2(pd->file.stat_filename, (char)delim, sk, interval);
           break;  
   default : stat = -1;  // 意外の場合はエラー
           printf("file_sets2(): ないファイルを指定してます\n");
           socket_send(sk, "500NG: file name check err.\n", interval);
           break;
   }

free(chA);
free(chB);
free(chC);

return(stat);
}




/* ------------------ FILE SET 1.1.7 以上の為 ----------------- */
int get_file2(char * filename, char delim, int sk, int interval)
{
int ret;
// int fd;
struct stat stat_buf;
// FILE * fp;
char * rec;

rec = (char *)calloc(IP_LEN, sizeof(char));
ret = 0;

if(0 == stat(filename, &stat_buf)){
   fprintf(stderr,"get_file2(): It doesn't write it because there is a file. %s\n", filename);
   socket_send(sk, "500NG: not file status.\n", interval);
   ret = 0;
   }
else {
//   if((fp = fopen(filename, "w+"))!=NULL){
//      fd = fileno(fp);

      socket_send(sk, "200OK\n", interval);

//    swap_mem(data, (char)delim, '\n');
//    fprintf(fp,"%s",data);


      rec = alget_read(filename, rec, sk, interval, &ret, (char)delim, FILE_LEN, 1);


//      fclose(fp);
//      }
//   else{
//      fprintf(stderr,"new file Not open %s\n", filename);
//      socket_send(sk, "500NG: not file open.\n", interval);
//      ret = -1;
//      }
   fprintf(stderr,"get_file2(): The client wrote it because there was no file. %s\n", filename);
   ret = 0;
   }

free(rec);

return(ret);
}





