// zitherctl.c
// $Id: zitherctl.c,v 1.1.1.1 2007/09/19 05:49:54 sendan Exp $
// masashi shimakura

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

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

#define BUF_SLENC 512
#define BUF_LENC 1024
/* #define DEBUG_CTL */


int mail_grsend(char *, char *, char *, char *, char *, char *, char *, char *);
void initdaemon(void);

char ui[BUF_LENC];
char co[BUF_LENC];
char pr[BUF_LENC];
char aa[BUF_LENC];
char ne[BUF_LENC];
char * conf;
char * neg;
char * prog;
char * uid;
char * all;

int main(int argc, char * argv[])
{
int times, stat_return;
conf = co;
neg = ne;
prog = pr;
uid = ui;
all = aa;

char * swapsubject = (char *)calloc(2, sizeof(char));
char * swapsubject2 = (char *)calloc(2, sizeof(char));
char * swapdata = (char *)calloc(2, sizeof(char));

initdaemon();

if(argc < 10 || argc > 10){
   printf("------- zitherctl Vr1.1.2 is a program that starts zither. ------\n");
   printf("--------- Please start by the following options. -------\n");
   printf("zitherctl <1 zither path> <2 zither conf path> <3 zither neg.conf path> <4 exec UID> <5 restart interval> <6 mail server address> <7 mail from> <8 mailrcpt to ,,,> <9 server name> \n");
   exit(1);
   }

prog = argv[1];
conf = argv[2];
neg = argv[3];
uid = argv[4];
times = strtol(argv[5], (char **)NULL, 10);

if(2040 > ((int)strlen(conf) + (int)strlen(prog) + (int)strlen(neg) + (int)strlen(uid) + (int)strlen(" -c "))){
   memcpy(all, prog, (int)strlen(prog)+1);
   strncat(all, " -c ", 5);
   strncat(all, conf, (int)strlen(conf)+1);
   strncat(all, " -n ", 5);
   strncat(all, neg, (int)strlen(neg)+1);
   strncat(all, " -i ", 5);
   strncat(all, uid, (int)strlen(uid)+1);
   fprintf(stderr,"(exec options) %s\n", all);
   }
else{
   fprintf(stderr,"data long or short\n");
   exit(1);
   }

for(;;){
   stat_return = system(all);
   fprintf(stderr,"Reactivation in zither process stop and %d seconds\n", times);
   fprintf(stderr,"exec data %s\n", all);
   fprintf(stderr,"return stat %d\n", stat_return);


   // subject を作ります
   swapsubject2 = safe_memcpy(swapsubject2, MAIL_CTL_1, BUF_MAX);
// swapsubject2 = safe_ujtoj(swapsubject2);
// swapsubject2 = base64_kai(swapsubject2);
   swapsubject2 = mime_ujtoj(swapsubject2);

   swapsubject = safe_sprintf(swapsubject, BUF_MAX, "ZITHERCTL <%s> %s", "zither administrator", swapsubject2);

   // 本文をつくります
   swapdata = safe_sprintf(swapdata, BUF_MAX, "%s\n\n%s\n\n%s\n", MAIL_CTL_2, argv[9], MAIL_CTL_3);
   swap_mem(swapdata, '\n', (char)0x01);

   mail_grsend(argv[6],
           argv[7],
           argv[8],
           " ",
           swapdata,
           swapsubject,
           "NOT",
           "1");

   sleep(times);
   }

free(swapsubject);
free(swapsubject2);
free(swapdata);

return stat_return;
}  




