#include  <stdio.h>
#include  <stdlib.h>
#include  <unistd.h>
#include  <sys/stat.h>
#include  <pthread.h>

int   unixtoasciitime( time_t, char * );
void  *send_mail();
void  *file_chk();

int  main()
{

  pthread_t  thr_id[2];
 
  while(1){
    pthread_create( &thr_id[0], NULL, &send_mail, NULL );
    pthread_create( &thr_id[1], NULL, &file_chk, NULL );
    pthread_join( thr_id[1], NULL );
    pthread_cancel( thr_id[0] );
    pthread_join( thr_id[0], NULL );
  }

  return 0;

}


void  *send_mail()
{

  int        yy, mm, next_unixtime, time_diff, slp_time, intvl, intvl_week, f_flg=0;
  char       fname[]="date.txt", next_asciitime[32]="", cmd[256]="";
  FILE       *fp;
  time_t     date;
  struct tm  get_time={0};
  
  if( (fp = fopen(fname, "r")) == NULL ){
    printf("%s open error!\n", fname);
    exit(EXIT_FAILURE);
  }
  
  fscanf(fp, "%d/%d/%d %d:%d:%d\n%d", &yy, &mm, &get_time.tm_mday,
	 &get_time.tm_hour, &get_time.tm_min, &get_time.tm_sec, &intvl_week);

  fclose(fp);

  get_time.tm_year = yy - 1900;   get_time.tm_mon  = mm - 1;

  time_diff = time(&date) - mktime(&get_time);

  intvl = 60 * 60 * 24 * 7 * intvl_week;

  while(1){
    if( f_flg == 0 ){
      if( time_diff >= 0 ){
	slp_time = intvl - time_diff;
	if( slp_time < 0 )
	  slp_time = intvl - time_diff % intvl;
      }else
	slp_time = -time_diff;
      f_flg = 1;
    }else
      slp_time = intvl;

    next_unixtime = time(&date) + slp_time;
    unixtoasciitime(next_unixtime, next_asciitime);

    printf("Next time is %s\n", next_asciitime);

    sleep(slp_time);

    sprintf(cmd, "echo '本文\\n次回は%sです。' | mail -s '件名' メールアドレス", next_asciitime);

    system(cmd);

  }

  return NULL;

}


void  *file_chk()
{

  char             filename[]="date.txt";
  struct stat      st[2];
  struct timespec  ts={0, 10000000};
  
  stat(filename, &st[0]);

  while(st[0].st_mtime >= st[1].st_mtime){
    stat(filename, &st[1]);
    nanosleep(&ts, NULL);
  }

  puts("Setting file is modified!");

  return NULL;

}


int  unixtoasciitime(time_t unixtime, char *asciitime){
  return strftime(asciitime, 32, "%Y/%m/%d %T (%a)", localtime(&unixtime));
}

