#!/usr/bin/perl

use Socket;
use mailer;

$datafile = "./dat.txt";
$tempfile = "./temp.txt";
$mail_server = "mb.2ch.net";
$mail_address = 'testkun@docomo.ne.jp';
$from_address = 'testkun@2ch.net';
$title = "スレッド更新";
$sleep_time = 300;
$| = 1;

open (FILE,"$datafile");
@DATA = <FILE>;
close (FILE);
while (){
 &checker;
 sleep ($sleep_time);
}

sub checker {
 ($sec,$min,$hour,$day,$mon,$temp,$temp,$temp,$temp) = localtime(time);
 $mon = ($mon + 1);
 if ($mon  < 10){$mon = "0$mon"; }
 if ($day  < 10){$day = "0$day"; }
 if ($sec  < 10){$sec = "0$sec"; }
 if ($min  < 10){$min = "0$min"; }
 if ($hour < 10){$hour= "0$hour";}
 print $mon."-".$day." ".$hour.":".$min." : Checking...";
 open (FILE,"$tempfile");
 @TIME = <FILE>;
 close (FILE);
 open (FILE,">$tempfile");
 $modify = "";
 $count = -1;
 foreach $line (@DATA) {
  $count++;
  $line =~ s/\n//g;
  $line =~ s/\r//g;
  $line =~ s/\t+/\t/g;
  ($name,$dat_name) = split (/\t/,$line);
  if ("$name" eq ""){next;}
  ($hostname,$filename) = split (/\//,$dat_name,2);
  $filename = "/" . $filename;
  $addr = (gethostbyname("$hostname"))[4];
  $socket_name = pack("S n a4 x8", 2, 80, $addr);
  socket(S, 2, 1, 0);
  connect(S, $socket_name);
  binmode(S);
  select(S);
  $|=1;
  select(stdout);
  print S "HEAD ".$filename." HTTP/1.1\r\nHost: ".$hostname."\r\n";
  print S "Connection: close \r\nUser-Agent: Monazilla/1.00 (2ch_dat_checker/1.0)\r\nAccept: */* \r\nAccept-Language: ja\r\n\r\n";
  while (<S>) {
   if ($_ !~ /Last-Modified/) {next;}
   $_ =~ s/Last-Modified: //g;
   $_ =~ s/\r//g;
   $_ =~ s/\n//g;
   $TIME[$count] =~ s/\n//g;
   if ("$_" ne "$TIME[$count]"){
    $modify = $modify . $name . "\n";
   }
   print FILE $_ . "\n";
  }
  close (S);
 }
 close(FILE);
 print "done. / ";
 if ("$modify" ne ""){
  $value = "更新状況----\n  ".$mon."-".$day." ".$hour.":".$min."\n".$modify."\n\n2ch datchecker";
  $ret=mailer($mail_server,$mail_address,$from_address,$title,$value);
  print "sendmail : ";
  if ("$ret" eq "1"){print "success.\n";}
  else {print "error.\n";}
 }
 else {
  print "sleep...\n";
 }
}
