#! /usr/bin/perl
use DBI;
use File::Find;
use Archive::Zip;
use YAML;
#require "/etc/squarantine/squarantine.conf";
$conf = YAML::LoadFile("/etc/squarantine/squarantine.conf");
# print $conf->{WEBROOT};
open(FILE,">>/tmp/usbplug") or die;
    print FILE "--------------", "\n";
foreach my $key( keys %ENV ){
    print FILE "$key: $ENV{$key}", "\n";
}
close(FILE);
sub test {
  $sqlstr="insert into media (memo) values (\'".$_[0]."\')";
  my $sth = $dbh->prepare($sqlstr);
  $sth -> execute;
}

sub autodelete {
  $dir = $_[0];
# my $dir = '.';
  ##### /autorun.inf delete ########
  opendir(H_DIR,$dir) || die "no $dir: $!";
  while ($file = readdir(H_DIR)) {
    $filename = $file;
    $filename =~ s#.*/##;
    $filename =~ s/([a-zA-Z])/\L$1\E/g;
    if ( "autorun.inf" eq $filename ){
#    print $file."\n";
       unlink $dir."/".$file;
    }
  }
  closedir(H_DIR);
  ##### other delete ########
  find( \&wanted, ($dir) );
}
sub wanted {
  my $file = $File::Find::name;
  if ( $file =~ /\.(exe|com|cmd|bat|scr|pif|vbs|vbe|js|jse|wsf|wsh)$/i ){
  ##### execute file ########
#    print "execute: $file¥n";
     unlink $file;
  }
  if ( $file =~ /\.(zip)$/i ){
  ##### zip file ########
#    print "zip: $file¥n";
    if ( my $zip = Archive::Zip->new( $file )) { ;
      foreach $archived ($zip->memberNames) {
#        print "zipped: $archived\n";
         if ( $archived =~ /\.(exe|com|cmd|bat|scr|pif|vbs|vbe|js|jse|wsf|wsh)$/i ){
#           print "zipexecute: $file:$archived¥n";
            unlink $file;
         }
      }
    }
  }
}

sub makeattfile {
  ### ARGMENT 1... nickname 2...mode no. ######
  my ($nickname);
  my ($dirname);
  my ($flags);
  my ($filename);
  my ($attentionfile);
  my ($templatefile);
  $nickname = $_[0];
  $flags = $_[1];
  #### MAKE ATTENTION DIRECTORY FILE #################
  $dirname = $nickname;
  $dirname =~ s/[<>:\*\?\|\"\/\\]//g;
  system("mkdir -p /var/squarantine/usbstorages/$dirname");

  #### MAKE ATTENTION FILE FROM TEMP FILE #################
  #  system("cp /var/squarantine/templates/未登録.html /var/squarantine/usbstorages/$dirname");
  #$templatefile = "/var/squarantine/www/templates/未登録.html";
  #$attentionfile  = "/var/squarantine/usbstorages/$dirname/未登録.html";
  while (defined($templatefile = </var/squarantine/www/templates/$flags\.*> )) {
    $filename = $templatefile;
    $filename =~ s#.*/##;           # get file name
    $attentionfile = "/var/squarantine/usbstorages/$dirname/$filename";

    open(FILE2 , ">$attentionfile" ) or die "attention file output error";
    open(FILE , "$templatefile" ) or die "tempate file open error";
    while (<FILE>) {
      s/\#\#ID\#\#/$id/g ;
      s/\#\#DEVNAME\#\#/$ENV{'DEVNAME'}/g ;
      s/\#\#WEBROOT\#\#/$conf->{WEBROOT}/g ;
      print FILE2 $_;
    }
    close(FILE);
    close(FILE2);
  }
}

$dbh = DBI->connect("DBI:mysql:$conf->{MYSQL_DB}", "$conf->{MYSQL_USER}", "$conf->{MYSQL_PASS}") || die "CONNECT ERROR $DBI::ERRSTR";
#test(0);
my $sth = $dbh->prepare("select nickname,memo,flags from media where id_serial=\'".$ENV{'ID_SERIAL'}."\' and flags > 0");
$sth->execute;
$num_rows = $sth->rows;
if ( 0 == $num_rows ){ 
################# MODE 0: IN REGIST NOT YET ###################
  my $sth = $dbh->prepare("select nickname,memo,flags from media where id_serial=\'".$ENV{'ID_SERIAL'}."\'");
  $sth->execute;
  $num_rows = $sth->rows;
  if ( 0 == $num_rows ){
    ##### FIRST PLUG ##### 
    $nickname = $ENV{'ID_SERIAL'};
    $nickname =~ s/[<>:\*\?\|\"\/\\]//g;
    $sqlstr="insert into media (id_serial,nickname,flags) values (\'".$ENV{'ID_SERIAL'}."\',\'".$nickname."\',0)";
    my $sth = $dbh->prepare($sqlstr);
    $sth -> execute;
  }
  ##### GET KEY #####
  my $sth = $dbh->prepare("select id,nickname from media where id_serial=\'".$ENV{'ID_SERIAL'}."\'");
  $sth->execute;
  $num_rows = $sth->rows;
  for ($i=0; $i<$num_rows; $i++) {
    @a = $sth->fetchrow_array;
    $id = $a[0];
    $nickname = $a[1];
  }
    #test("1");

  makeattfile($nickname,0);


} else {
############ GET INFO ###########
my $sth = $dbh->prepare("select id,id_serial,nickname,memo,flags from media where id_serial=\'".$ENV{'ID_SERIAL'}."\'");
  $sth->execute;
  $num_rows = $sth->rows;
  for ($i=0; $i<$num_rows; $i++) {
    @a = $sth->fetchrow_array;
    $id = $a[0];
    $id_serial = $a[1];
    $memo = $a[3];
    $flags = $a[4];
    $nickname = $a[2];
  }
  if ( 1 == $flags )
  { 
    #################  1: NOT PERMIT              ##################
    makeattfile($nickname,1);
  } elsif ( 2 == $flags ) {
    #################  2: STOP                    ##################
    makeattfile($nickname,2);
  } elsif ( 4 == $flags ) {
    #################  4: RESERVED                ##################
    makeattfile($nickname,4);
  } elsif ( 8 == $flags ) {
    #################  8: AUTO FORMAT             ##################
    makeattfile($nickname,8);
    system("mkfs.vfat $ENV{'DEVNAME'} > /var/log/squarantine.log");
    system("echo mkfs.vfat $ENV{'DEVNAME'} >> /var/log/squarantine.log");
    system("mkdir -p /mnt$ENV{'DEVNAME'}");
    #system("mount -o umask=000  $ENV{'DEVNAME'} /mnt$ENV{'DEVNAME'}");
    #system("ln -s /mnt$ENV{'DEVNAME'} /var/squarantine/usbstorages/$nickname");
    system("mount -o umask=000 $ENV{'DEVNAME'} /var/squarantine/usbstorages/$nickname");

  } elsif ( 16 == $flags ) {
    #################  16: MANUAL FORMAT          ##################
    makeattfile($nickname,16);
  } elsif ( 32 == $flags ) {
    #################  32: AUTO DELETE            ##################
    makeattfile($nickname,32);
    system("mkdir -p /mnt$ENV{'DEVNAME'}");
    system("mount $ENV{'DEVNAME'} /mnt$ENV{'DEVNAME'}");
    autodelete("/mnt".$ENV{'DEVNAME'});
    system("umount $ENV{'DEVNAME'}");
    system("mount -o umask=000 $ENV{'DEVNAME'} /var/squarantine/usbstorages/$nickname");

  } elsif ( 64 == $flags ) {
    #################  64: MANUAL DELETE          ##################
    makeattfile($nickname,64);
  } elsif ( 128 == $flags ) {
    #################  128: FREE TO ADMINISTRATOR ##################
    makeattfile($nickname,128);
  }


}
$sth->finish;
$dbh->disconnect;

