#! /usr/bin/perl
use DBI;
use POSIX 'strftime';
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|lnk)$/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|lnk)$/i ){
#           print "zipexecute: $file:$archived¥n";
            unlink $file;
         }
      }
    }
  }
}

sub makeattfile {
  ### ARGMENT 1... nickname 2...mode no. ######
  my ($nickname);
  my ($dirname);
  my ($flags);
  my ($docommand);
  my ($filename);
  my ($attentionfile);
  my ($templatefile);
  $nickname = $_[0];
  $flags = $_[1];
  $docommand = $_[2];
  #### MAKE ATTENTION DIRECTORY FILE #################
  $dirname = $nickname;
  $dirname =~ s/[<>:\*\?\|\"\/\\]//g;
  system("mkdir -p /var/squarantine/usbstorages/$dirname");
  if ( 4 == ( 4 & $flags )) { $pagecode = 4; } else { $pagecode = $flags; }
 
  #### 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";
  $action="";
  if (   1 == (    1 & $flags )) { $action = $action."「使用禁止」" }
  if (   2 == (    2 & $flags )) { $action = $action."「信頼済」" }
  if (   4 == (    4 & $flags )) { $action = $action."「操作前確認」" }
  if (   8 == (    8 & $flags )) { $action = $action."「削除ファイルをバックアップ」" }
  if (  16 == (   16 & $flags )) { $action = $action."「実行ファイル削除」" }
  if (  32 == (   32 & $flags )) { $action = $action."「検疫済ファイルを外部にコピー」" }
  if (  64 == (   64 & $flags )) { $action = $action."「フォーマット」" }
  if ( 128 == (  128 & $flags )) { $action = $action."「使用停止」" }
  if ( "" ne $docommand        ) { $action = $action."「コマンド実行」" }
  if ( 256 == (  256 & $flags )) { $action = $action."「検疫後共有公開」" }
  if ( 512 == (  512 & $flags )) { $action = $action."「持出可」" }

  while (defined($templatefile = </var/squarantine/www/templates/$pagecode\.*> )) {
    $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/\#\#ACTION\#\#/$action/g ;
      s/\#\#DEVNAME\#\#/$ENV{'DEVNAME'}/g ;
      s/\#\#FLAGS\#\#/$ENV{'FLAGS'}/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,distpath,distaccount,docommand 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];
    $distpath    = $a[5];
    $distaccount = $a[6];
    $docommand   = $a[7];
    $nickname    = $a[2];
    $ENV{'FLAGS'}       = $flags;
  }
  if ( 1 ==( 1 & $flags ) )
  { 
    #################  1: NOT PERMIT              ##################
    makeattfile($nickname,1,$docommand);
  } elsif ( 2 == ( 2 & $flags )) {
    #################  2: FREE TO ADMINSITRATOR   ##################
    makeattfile($nickname,2,$docommand);
  } elsif ( 4 == ( 4 & $flags )) {
        #################  16+4: MANUAL DELETE          ##################
        #################  32+4: MANUAL EXPORT          ##################
        #################  64+4: MANUAL FORMAT          ##################
        #################  etc                          ##################
        makeattfile($nickname,$flags,$docommand);
  } else { 
    if ( 16 == ( 16 & $flags )) {
        #################  16: AUTO DELETE            ##################
        makeattfile($nickname,16,$docommand);
        system("mkdir -p /mnt$ENV{'DEVNAME'}");
        system("mount $ENV{'DEVNAME'} /mnt$ENV{'DEVNAME'}");
        autodelete("/mnt".$ENV{'DEVNAME'});
        system("umount $ENV{'DEVNAME'}");
    }
    if ( 32 == ( 32 & $flags )) {
        #################  32: DATA EXPORT             ##################
        makeattfile($nickname,32,$docommand);
        system("mkdir -p /mnt$ENV{'DEVNAME'}");
        system("mount $ENV{'DEVNAME'} /mnt$ENV{'DEVNAME'}");
        system("smbmount $distpath /mnt/$id -o username=$distaccount");
        my $now = strftime "%Y%m%d-%H%M%S", localtime;
        system("mkdir -p /mnt/$id/$now");
        system("cp -a /mnt$ENV{'DEVNAME'}/* /mnt/$id/$now");
        system("umount $ENV{'DEVNAME'}");
    #    system("umount /mnt/$id");
    }
    if ( 64 == ( 64 & $flags )) {
        #################  64: AUTO FORMAT             ##################
        makeattfile($nickname,64,$docommand);
        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");
    }
    if ( "" ne $docommand ) {
     system($docommand);
    }
    if ( 128 == ( 128 & $flags )) {
      #################  128: STOP                    ##################
      makeattfile($nickname,128,$docommand);
    } else {
      if ( 256 == ( 256 & $flags )) {
        #################  256: MOUNT                   ##################
        if ( 512 == ( 512 & $flags )) {
        #################  512: WRITEABLE               ##################
          system("mount -o umask=000 $ENV{'DEVNAME'} /var/squarantine/usbstorages/$nickname");
        } else {
        #################     : READONLY               ##################
          system("mount -r -o umask=000 $ENV{'DEVNAME'} /var/squarantine/usbstorages/$nickname");
        }
      }
    }
  }
}
$sth->finish;
$dbh->disconnect;

