
#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 pthread_mutex_t name_mutex;
extern global_data_t gd;


int midremove_logi(private_data_t * pd)
{
int stat;
int mucount;
int middleid;
int ret;

mucount = 0;
middleid = -1;
ret = 0;

char * swap = (char *)calloc(IP_LEN, sizeof(char));
char * buf = (char *)calloc(BUF_LEN, sizeof(char));

int ustat = self_memcmp(pd->rec.user, pd->rec.def_user); 
int astat = self_memcmp(pd->rec.user, "administrator");
int cgstat = self_memcmp(pd->rec.user, "cgiuser");

stat = 0; 

#ifdef MID_BUG
printf("MID_BUG: midremove_logi(): in\n");
#endif

// 認証のある普通のユーザーの場合
if(ustat == 0 && astat != 0 && cgstat != 0){ 
   // 送られてきたデータに大きさがある。
   if(3 < strlen(pd->rec.data)){

      safe_pthread_mutex_lock(&name_mutex);
      for(mucount = 0; mucount < gd.td.midcount; mucount++){
         if(0 == self_memcmp(gd.td.middle_name[mucount], pd->rec.data)){
            gd.td.middle_id[mucount] = 0;
            gd.td.middle_name[mucount] = null_free(gd.td.middle_name[mucount]);
            middleid = mucount;
            /* 名前が登録されているので、そのIDをけす */
            #ifdef MID_BUG
            printf("MID_BUG: scan_block(2): MID同じ名前のブロックが既に登録済みです <%s> mucount<%d>\n",
              gd.td.middle_name[mucount], mucount);
            #endif

            break;
            }
         } /* for() */
      pthread_mutex_unlock(&name_mutex);


      if(middleid > -1){
         swap = safe_sprintf(swap, BUF_LEN,"200 %d %d\n", mucount, gd.td.middle_id[mucount]);
         stat = socket_send(gd.ms.sk[pd->rec.fdno], swap, (pd->life.life_int + pd->life.life_los + 15));
         }
      else{
         stat = socket_send(gd.ms.sk[pd->rec.fdno], "500 NIR no user().\n", (pd->life.life_int + pd->life.life_los + 15));
         }

      }
      // データの内容がへん
   else{
      stat = socket_send(gd.ms.sk[pd->rec.fdno], "500 NIR data size(1).\n", (pd->life.life_int + pd->life.life_los + 15));
      }

   #ifdef LOG_OUT
   safe_pthread_mutex_lock(&con_mutex);
   log_out(gd.fp.con_fd, pd->rec.user, pd->rec.com, pd->rec.data,
   "200 OK It doesn't write it.", (unsigned char *)gd.ms.inip_addr[pd->rec.fdno]);
   pthread_mutex_unlock(&con_mutex);
   #endif
   }
else{
   stat = socket_send(gd.ms.sk[pd->rec.fdno], "500 NG NIR command(3).\n", (pd->life.life_int + pd->life.life_los + 15));
   #ifdef LOG_OUT
   safe_pthread_mutex_lock(&con_mutex);
   log_out(gd.fp.con_fd, pd->rec.user, pd->rec.com, pd->rec.data,
    "500 NG NIR command.", (unsigned char *)gd.ms.inip_addr[pd->rec.fdno]);
   pthread_mutex_unlock(&con_mutex);
   #endif
   } 


#ifdef MID_BUG
printf("MID_BUG: midremove_logi(): out\n");
#endif

free(swap);
free(buf);
return(stat);
}





