#!/usr/bin/perl -w

use HTTP::Lite;
use threads;

$node = "/home/hoge/shingetsu/saku/run/node.txt";
$search = "/home/hoge/shingetsu/saku/run/search.txt";
$www = "/home/hoge/shingetsu/saku/www";

$auto = 1;

@nodelist = ();

sub read_nodelist($) {
  my ($list, @in);
  $list = $_[0];
  open IN, $list or die("$list not found.");
  @in = <IN>;
  close IN;
  foreach (@in) {
    chomp $_;
    if ($_ =~ /node\.shingetsu\.info/){ next; }
    $_ =~ s|/server\.cgi$||;
    $_ =~ s|^|http://|;
    push (@nodelist, $_);
  }
}

sub flash_filelist {
  my $file;
  @filelist = ();
  opendir DIR, $www;
  while ($file = readdir DIR){
    push(@filelist, $file);
  }
  close DIR;
}

sub local_check($){
  my $file = $_[0];
  foreach (@filelist) {
    if ($file eq $_){ error_exist($file); }
  }
}

sub error_exist($) {
  my $file = $_[0];
  print "$file は $www に存在しています。\n",
        "プログラムを終了します。\n";
  exit 1;
}

sub _search($) {
  my ($file, $http, $req);
  $file = $_[0];
  $http = new HTTP::Lite;
  $req->{'method'} = 'HEAD';
  $req = $http->request("$file");
  if ($req == 200){
    if ($auto){ download($file); }
    else { print "Hit! $file\n"; exit 0; }
  }
}

sub search($) {
  my $file = $_[0];
  foreach (@nodelist) {
    $thread{$_} = threads->new(\&_search, "$_/$file");
  }
  foreach (@nodelist) {
    $thread{$_}->join;
  }
}

sub download($) {
  my ($url, $http, $req, $file);
  $url = $_[0];
  $file = $url;
  $file =~ s|http://[^/]+/(.+)|$1|;
  local_check($file);
  $http = new HTTP::Lite;
  $req = $http->request("$url");
  if ($req == 200){
    open OUT, ">$www/$file";
    #open OUT, ">$file";
    print OUT $http->body();
    close OUT;
  }
  exit 0;
}

sub help {
  print "usage: $0 [search/get] filename.ext\n";
  exit 1;
}

sub main {
  my $arg = shift @ARGV;
  flash_filelist;

  if (!(defined $arg)){ help; }
  if ("$arg" eq "get"){
    $file = shift @ARGV;
    if (!(defined $file)){ help; }
    download($file);
  } elsif ("$arg" eq "search"){
    $arg = shift @ARGV;
    if (!(defined $arg)){ help; }
  }

  local_check($arg);
  read_nodelist($node);
  read_nodelist($search);
  search($arg);

  exit 0;
}

main;
