#!/usr/bin/perl # # 指定ディレクトリ以下の MP3ファイルを SDカードにランダムにコピーする # 「闇鍋」 # # Linuxのコマンドに依存しまくり # コピー先ディレクトリの MP3ファイルを消去するので注意 # ディレクトリ指定省略時のディレクトリ $source = "$ENV{'HOME'}/mp3"; # MP3ファイルがあるディレクトリ $dest = "/drv/sd"; # コピー先ディレクトリ $logfile = "$ENV{'HOME'}/yaminabe.log"; # 過去ログ $logmax = 150; # 過去ログの最大数 if ($ARGV[0]){ $source = $ARGV[0]; } if ($ARGV[1]){ $dest = $ARGV[1]; } $starttime = time; # 指定ディレクトリ以下の MP3ファイルを全て抽出 # findコマンドで済ませている open(FILE, "find $source -name \\*.mp3 -print |") or die; @file = ; close(FILE); # 過去ログ読み込み open(FILE, $logfile); @logs = ; close(FILE); if (@logs > $logmax){ splice(@logs, 0, @logs - $logmax); } if (@file == 0){ print "MP3 file not found.\n"; exit; } # コピー先の 全MP3ファイル削除 system("rm -f $dest/*.mp3"); system("sync"); srand(time); ©_file; print "\n"; system("df --sync -k $dest"); # 過去ログ書き込み open(FILE, ">$logfile"); while($file = shift(@logs)){ chomp($file); print FILE "$file\n"; } close(FILE); system("sync"); $time = time - $starttime; print "所要時間: $time秒\n"; exit; #--------------------------------------------------------- sub copy_file{ my($log); for ($i = 1; $i < 512; $i++){ if (! -e "$dest/$i.MP3"){ last; } } while(@file){ # ファイルリストの中からランダムに一つ選ぶ while(@file) { $n = &gen_rand(scalar(@file)); $file = splice(@file, $n, 1); chomp($file); if (@file > @logs){ # 過去ログとの比較 foreach $log (@logs){ chomp($log); if ($log eq $file){ $file = ""; last; } } if (!$file){ next; } # ダブっていたので次のファイルを捜す } if ((-s $file) < 10 * 1024 * 1024){ # 10MB以下のファイルをコピー last; } else { $file = ""; } } if (!$file){ last; } # コピー先に空きエリアがあるか調べる。dfコマンドで済ませている open(DF, "df --sync -k $dest |"); $line = ; $line = ; close(DF); @dat = split(/\s+/, $line); $free = $dat[3]; if ((-s $file) > ($free * 1024)){ last; } push(@logs, $file); # 過去ログ登録 if (@logs >= $logmax){ splice(@logs, 0, @logs-$logmax+1); } # コピー開始。cpコマンドで済ませている print "copying $i.MP3 "; system("cp \"$file\" $dest/$i.MP3"); &flush_cache; print "\n"; $i++; } } sub flush_cache { my($i); system("sync"); # 以下は USBカードリーダライタの動作が不安定な場合に有効にするといいかも =cmt for ($i = 1; $i <= 3; $i++){ if (-e "$dest/$i.MP3"){ system("cp $dest/$i.MP3 /dev/null > /dev/null"); } } =cut } #---------------------------------------- # 乱数発生 # /dev/random デバイスを使う sub gen_rand { my($rand, $data, $max); $max = $_[0]; open(RND, "/dev/random"); read(RND, $rand, 4); close(RND); $data = vec($rand, 0, 32); if ($max){ return $data % $max; } else { return $data; } }