transmission.pl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. # Includes
  5. use JSON;
  6. use Date::Parse;
  7. use File::Temp qw/ :mktemp /;
  8. use File::Basename;
  9. use FindBin qw($Bin);
  10. use lib $Bin;
  11. use Fetch;
  12. # Prototypes
  13. sub session($);
  14. sub fetch($);
  15. sub getSSE($);
  16. sub getDest($$$$);
  17. sub delTor($);
  18. sub guessExt($);
  19. sub processFile($$);
  20. sub unrar($$);
  21. sub localSeriesCleanup($);
  22. sub seriesCleanup($);
  23. sub readDir($$);
  24. sub runAndCheck(@);
  25. # Parameters
  26. my $maxAge = 2.5 * 86400;
  27. my $tvDir = '/mnt/media/TV';
  28. my $monitoredExec = '/Users/profplump/bin/video/torrentMonitored.pl';
  29. my $host = 'http://localhost:9091';
  30. my $url = $host . '/transmission/rpc';
  31. my $content = '{"method":"torrent-get","arguments":{"fields":["hashString","id","addedDate","comment","creator","dateCreated","isPrivate","name","totalSize","pieceCount","pieceSize","downloadedEver","error","errorString","eta","haveUnchecked","haveValid","leftUntilDone","metadataPercentComplete","peersConnected","peersGettingFromUs","peersSendingToUs","rateDownload","rateUpload","recheckProgress","sizeWhenDone","status","trackerStats","uploadedEver","uploadRatio","seedRatioLimit","seedRatioMode","downloadDir","files","fileStats"]}}';
  32. my $delContent = '{"method":"torrent-remove","arguments":{"ids":["#_ID_#"], "delete-local-data":"true"}';
  33. my $delSleep = 5;
  34. my $RAR_MIN_FILES = 4;
  35. # Debug
  36. my $DEBUG = 0;
  37. if ($ENV{'DEBUG'}) {
  38. $DEBUG = 1;
  39. }
  40. # Command-line parameters
  41. my ($force, $maxDays) = @ARGV;
  42. # Init
  43. my $fetch = Fetch->new();
  44. # Check availability of web interface
  45. $fetch->url($host);
  46. if ($DEBUG) {
  47. print STDERR "Checking for torrent web interface\n";
  48. }
  49. $fetch->fetch('nocheck' => 1);
  50. if ($fetch->status_code() != 200) {
  51. if ($DEBUG) {
  52. die("Transmission web interface not available\n");
  53. }
  54. exit(0);
  55. }
  56. # Fetch the list of paused (i.e. completed) torrents
  57. $fetch->url($url);
  58. $fetch->post_content($content);
  59. &fetch($fetch);
  60. my $torrents = decode_json($fetch->content());
  61. $torrents = $torrents->{'arguments'}->{'torrents'};
  62. # Process
  63. if ($DEBUG) {
  64. print STDERR "Processing torrents...\n";
  65. }
  66. foreach my $tor (@{$torrents}) {
  67. # Skip torrents that aren't yet done
  68. if ($tor->{'leftUntilDone'} > 0 || $tor->{'metadataPercentComplete'} < 1) {
  69. next;
  70. }
  71. # Only process recent files
  72. # Torrents created with magnet links have no dateCreated, so fake it with addedDate
  73. if ($tor->{'dateCreated'} < 946684800) {
  74. $tor->{'dateCreated'} = $tor->{'addedDate'};
  75. }
  76. if (!$force && $tor->{'dateCreated'} < time() - $maxAge) {
  77. my $age = (time() - $tor->{'dateCreated'}) / 86400;
  78. if ($DEBUG) {
  79. print STDERR 'Skipping old torrent: ' . $tor->{'name'} . ' (' . sprintf('%.0f', $age) . " days)\n";
  80. }
  81. next;
  82. }
  83. if ($DEBUG) {
  84. print STDERR 'Processing finished torrent: ' . $tor->{'name'} . "\n";
  85. }
  86. # Handle individual files and directories
  87. my $file = '';
  88. my @newFiles = ();
  89. my $path = $tor->{'downloadDir'} . '/' . $tor->{'name'};
  90. if (-d $path) {
  91. # State variables
  92. my $IS_RAR = '';
  93. my $IS_FAKE = 0;
  94. # Look for RAR files
  95. foreach my $file (@{ $tor->{'files'} }) {
  96. if ($file->{'name'} =~ /\.rar$/i) {
  97. $IS_RAR = $tor->{'downloadDir'} . '/' . $file->{'name'};
  98. last;
  99. }
  100. }
  101. # Check for password files
  102. foreach my $file (@{ $tor->{'files'} }) {
  103. if ($file->{'name'} =~ /passw(?:or)?d/i) {
  104. print STDERR 'Password file detected in: ' . $tor->{'name'} . "\n";
  105. $IS_FAKE = 1;
  106. last;
  107. }
  108. }
  109. # Check for single-file RARs
  110. if ($IS_RAR && scalar(@{ $tor->{'files'} }) < $RAR_MIN_FILES) {
  111. print STDERR 'Single-file RAR detected in: ' . $tor->{'name'} . "\n";
  112. $IS_FAKE = 1;
  113. }
  114. # Find media files in valid torrents
  115. if (!$IS_FAKE) {
  116. # Unrar if necessary
  117. if (defined($IS_RAR) && length($IS_RAR) > 0) {
  118. @newFiles = &unrar($IS_RAR, $path);
  119. }
  120. # Find exactly 1 media file
  121. my @files = ();
  122. my @tmpFiles = readDir($path, '/\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i');
  123. foreach my $file (@tmpFiles) {
  124. if ($file =~ /sample/i) {
  125. next;
  126. }
  127. push(@files, $file);
  128. }
  129. if (scalar(@files) != 1) {
  130. print STDERR 'Did not find exactly 1 media file in: ' . $path . "\n";
  131. foreach my $fn (@files) {
  132. print STDERR "\t" . $fn . "\n";
  133. }
  134. next;
  135. }
  136. $file = $files[0];
  137. } else {
  138. $file = '';
  139. }
  140. } else {
  141. $file = $path;
  142. }
  143. # Do all the normal file naming/copying/etc. if we found a file
  144. my $result = -1;
  145. if (defined($file) && length($file) > 0 && -r $file) {
  146. $result = &processFile($file, $path);
  147. }
  148. if (defined($result) && $result == 1) {
  149. if ($DEBUG) {
  150. print STDERR 'Torrent stored successfully: ' . $tor->{'name'} . "\n";
  151. }
  152. } elsif (defined($result) && $result == -1) {
  153. print STDERR 'Deleting bad torrent: ' . $tor->{'name'} . "\n";
  154. } else {
  155. print STDERR 'Error storing file "' . basename($file) . '" from torrent: ' . $tor->{'name'} . "\n";
  156. next;
  157. }
  158. # Delete any files we added
  159. foreach my $file (@newFiles) {
  160. if ($DEBUG) {
  161. print STDERR 'Deleting new file: ' . basename($file) . "\n";
  162. }
  163. unlink($file);
  164. }
  165. # Remove the source torrent (it's either copied or bad by this point)
  166. delTor($tor);
  167. }
  168. # Cleanup
  169. exit(0);
  170. # Grab the session ID
  171. sub session($) {
  172. my ($fetch) = @_;
  173. my %headers = ();
  174. ($headers{'X-Transmission-Session-Id'}) = $fetch->content() =~ /X\-Transmission\-Session\-Id\:\s+(\w+)/;
  175. $fetch->headers(\%headers);
  176. }
  177. sub fetch($) {
  178. my ($fetch) = @_;
  179. $fetch->fetch('nocheck' => 1);
  180. if ($fetch->status_code() != 200) {
  181. &session($fetch);
  182. $fetch->fetch();
  183. if ($fetch->status_code() != 200) {
  184. die('Unable to fetch: ' . $fetch->status_code() . "\n");
  185. }
  186. }
  187. }
  188. sub getSSE($) {
  189. my ($name) = @_;
  190. if ($DEBUG) {
  191. print STDERR 'Finding series/season/episode for: ' . $name . "\n";
  192. }
  193. my $season = 0;
  194. my $episode = 0;
  195. my $seasonBlock = '';
  196. if ($name =~ /(?:\b|_)(S\d{1,2}[_\s\.]?E\d{1,2})(?:\b|_)/i) {
  197. $seasonBlock = $1;
  198. ($season, $episode) = $seasonBlock =~ /S(\d{1,2})[_\s\.]?E(\d{1,2})/i;
  199. $season = int($season);
  200. $episode = sprintf('%02d', int($episode));
  201. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  202. $seasonBlock = $1;
  203. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  204. $season = int($season);
  205. $episode = sprintf('%02d', int($episode));
  206. } elsif ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  207. $seasonBlock = $1;
  208. my ($month, $day);
  209. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  210. $season = int($season);
  211. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  212. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  213. $seasonBlock = $1;
  214. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  215. $season = int($season);
  216. $episode = sprintf('%02d', int($episode));
  217. }
  218. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  219. if ($DEBUG) {
  220. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  221. }
  222. return;
  223. }
  224. # Assume the series titles comes before the season/episode block
  225. my $series = '';
  226. my $sIndex = index($name, $seasonBlock);
  227. if ($sIndex > 0) {
  228. $series = substr($name, 0, $sIndex - 1);
  229. $series = seriesCleanup($series);
  230. }
  231. if ($DEBUG) {
  232. print STDERR 'Series: ' . $series . ' Season: ' . $season . ' Episode: ' . $episode . "\n";
  233. }
  234. return ($series, $season, $episode);
  235. }
  236. sub getDest($$$$) {
  237. my ($series, $season, $episode, $ext) = @_;
  238. if ($DEBUG) {
  239. print STDERR 'Finding destintion for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  240. }
  241. # Find all our existing TV series
  242. my @shows = ();
  243. my %showsCan = ();
  244. open(SHOWS, '-|', $monitoredExec, 'STORE')
  245. or die("Unable to fork: ${!}\n");
  246. while (<SHOWS>) {
  247. chomp;
  248. my $orig = $_;
  249. my $clean = localSeriesCleanup($_);
  250. push(@shows, $clean);
  251. $showsCan{$clean} = $orig;
  252. }
  253. close SHOWS or die("Unable to read monitored series list: ${!} ${?}\n");
  254. # See if we can find a unique series name match
  255. my $sClean = seriesCleanup($series);
  256. my $sMatch = '\b' . $sClean . '\b';
  257. $series = '';
  258. foreach my $show (@shows) {
  259. # Match the folder name or the search_name
  260. my $coarse_match = 0;
  261. if ($show =~ /${sMatch}/i) {
  262. $coarse_match = 1;
  263. } else {
  264. my $search_name = '';
  265. my $file = $tvDir . '/' . $showsCan{$show} . '/search_name';
  266. if (-e $file) {
  267. open(FH, $file)
  268. or die('Unable to read search_name file: ' . $file . "\n");
  269. $search_name = <FH>;
  270. close(FH);
  271. }
  272. if ($search_name) {
  273. $search_name =~ s/^\s+//;
  274. $search_name =~ s/\s+$//;
  275. if ($search_name =~ /${sMatch}/i) {
  276. $coarse_match = 1;
  277. }
  278. }
  279. }
  280. # If we got a course match, continue checking
  281. if ($coarse_match) {
  282. # Enforce any secondary matching rules (for ambiguous titles)
  283. my $detail_match = 1;
  284. {
  285. my @lines;
  286. my $file = $tvDir . '/' . $showsCan{$show} . '/must_match';
  287. if (-e $file) {
  288. local ($/, *FH);
  289. open(FH, $file)
  290. or die('Unable to read must_match file: ' . $file . "\n");
  291. my @tmp = <FH>;
  292. close(FH);
  293. push(@lines, @tmp);
  294. }
  295. foreach my $line (@lines) {
  296. chomp($line);
  297. if (!eval('$sClean =~ m' . $line)) {
  298. if ($DEBUG) {
  299. print STDERR 'Skipping ' . $show . ' due to must_match failure for: ' . $line . "\n";
  300. }
  301. $detail_match = 0;
  302. last;
  303. }
  304. }
  305. }
  306. if (!$detail_match) {
  307. next;
  308. }
  309. # Bail if we find more than one matching series
  310. if (length($series) > 0) {
  311. print STDERR 'Matched both ' . $series . ' and ' . $show . "\n";
  312. return;
  313. }
  314. # If we're still around this is the first series title match
  315. $series = $show;
  316. }
  317. }
  318. if (length($series) < 1) {
  319. if ($DEBUG) {
  320. print STDERR 'No series match for: ' . $sMatch . "\n";
  321. }
  322. return;
  323. }
  324. # Lookup the canonical name from the matched name
  325. $series = $showsCan{$series};
  326. # Make sure we have the right season folder
  327. my $seriesDir = $tvDir . '/' . $series;
  328. my $seasonDir = $seriesDir . '/' . 'Season ' . $season;
  329. if (!-d $seasonDir) {
  330. print STDERR 'No season folder for: ' . $series . ' S' . $season . "\n";
  331. return;
  332. }
  333. # Bail if we already have this episode
  334. my @episodes = readDir($seasonDir, '/^\s*[\d\-]+\s*\-\s*/');
  335. foreach my $ep (@episodes) {
  336. $ep = basename($ep);
  337. my ($epNum) = $ep =~ /^\s*([\d\-]+)\s*\-\s*/;
  338. $epNum =~ s/^0+//;
  339. $episode =~ s/^0+//;
  340. if ($epNum eq $episode) {
  341. print STDERR 'Existing episode for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  342. return;
  343. }
  344. }
  345. # Construct the final path
  346. if (!defined($ext) || length($ext) < 1) {
  347. $ext = 'avi';
  348. }
  349. if ($episode =~ /^\d+$/) {
  350. $episode = sprintf('%02d', $episode);
  351. }
  352. my $dest = sprintf('%s/%s - NoName.%s', $seasonDir, $episode, $ext);
  353. if ($DEBUG) {
  354. print STDERR 'Destination: ' . $dest . "\n";
  355. }
  356. return $dest;
  357. }
  358. sub delTor($) {
  359. my ($tor) = @_;
  360. if ($DEBUG) {
  361. print STDERR 'Deleting torrent: ' . $tor->{'name'} . "\n";
  362. }
  363. # Sleep to avoid bugs in Transmission (i.e. multiple deletes fail)
  364. sleep($delSleep);
  365. # Construct the content
  366. my $id = $tor->{'hashString'};
  367. my $content = $delContent;
  368. $content =~ s/\#_ID_\#/${id}/;
  369. # Send the command
  370. &session($fetch);
  371. $fetch->post_content($content);
  372. &fetch($fetch);
  373. }
  374. sub guessExt($) {
  375. my ($file) = @_;
  376. # Believe most non-avi file extensions without checking
  377. # It's mostly "avi" that lies, and the checks are expensive
  378. my $ext = '';
  379. {
  380. my $orig_ext = basename($file);
  381. $orig_ext =~ s/^.*\.(\w{2,3})$/$1/;
  382. $orig_ext = lc($orig_ext);
  383. if ($orig_ext eq 'mkv' || $orig_ext eq 'ts') {
  384. $ext = $orig_ext;
  385. }
  386. }
  387. # Ask movInfo.pl about the demuxer
  388. if (!$ext) {
  389. my $demux = '';
  390. open(INFO, '-|', $ENV{'HOME'} . '/bin/video/movInfo.pl', $file, 'DEMUXER');
  391. while (<INFO>) {
  392. $demux .= $_;
  393. }
  394. close(INFO);
  395. $demux =~ s/^\s+//;
  396. $demux =~ s/\s+$//;
  397. # Grab a MIME type from file(1)
  398. my $mime = '';
  399. open(FILE, '-|', 'file', '-b', $file);
  400. while (<FILE>) {
  401. $mime .= $_;
  402. }
  403. close(FILE);
  404. $mime =~ s/^\s+//;
  405. $mime =~ s/\s+$//;
  406. $mime =~ s/\;.*$//;
  407. $mime =~ s/^video\///i;
  408. # Try to pick an extension we understand
  409. $ext = 'avi';
  410. if ($demux =~ /mkv/i || $mime =~ /Matroska/i) {
  411. $ext = 'mkv';
  412. } elsif ($demux =~ /asf/i || $mime =~ /\bASF\b/i) {
  413. $ext = 'wmv';
  414. } elsif ($mime =~ /\bZIP/i) {
  415. $ext = 'zip';
  416. } elsif ($mime =~ /\bAVI\b/i) {
  417. $ext = 'avi';
  418. } elsif ($demux =~ /mpegts/i) {
  419. $ext = 'ts';
  420. }
  421. }
  422. return $ext;
  423. }
  424. sub processFile($$) {
  425. my ($file, $path) = @_;
  426. if ($DEBUG) {
  427. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  428. }
  429. # Guess a file extension
  430. my $ext = &guessExt($file);
  431. # Delete WMV files -- mostly viruses
  432. if ($ext =~ /wmv/i) {
  433. print STDERR 'Declining to save WMV file: ' . basename($file) . "\n";
  434. return -1;
  435. }
  436. # Delete ZIP files -- mostly fake
  437. if ($ext =~ /zip/i) {
  438. print STDERR 'Declining to save ZIP file: ' . basename($file) . "\n";
  439. return -1;
  440. }
  441. # Allow multiple guesses at the series/season/episode
  442. my $dest = '';
  443. my $filename = basename($file);
  444. LOOP: {
  445. # Determine the series, season, and episode number
  446. my ($series, $season, $episode) = &getSSE($filename);
  447. if ( defined($series)
  448. && length($series) > 0
  449. && defined($season)
  450. && $season > 0
  451. && defined($episode)
  452. && length($episode) > 0
  453. && $episode ne '0')
  454. {
  455. # Find the proper destination for this torrent, if any
  456. $dest = &getDest($series, $season, $episode, $ext);
  457. }
  458. # Sanity/loop check
  459. if (!defined($dest) || length($dest) < 1) {
  460. # If there is no match but the torrent is a folder
  461. # retry the guess using the torrent path
  462. if ($file ne $path) {
  463. my $newName = basename($path);
  464. if ($newName ne $filename) {
  465. $filename = basename($path);
  466. redo LOOP;
  467. }
  468. }
  469. # Otherwise we just fail
  470. print STDERR 'No destination for: ' . basename($file) . "\n";
  471. return;
  472. }
  473. }
  474. # Copy with system tools
  475. my $tmp = mktemp($dest . '.XXXXXXXX');
  476. runAndCheck(('cp', $file, $tmp));
  477. rename($tmp, $dest);
  478. # Return success
  479. return 1;
  480. }
  481. sub unrar($$) {
  482. my ($file, $path) = @_;
  483. if ($DEBUG) {
  484. print STDERR 'UnRARing: ' . basename($file) . "\n";
  485. }
  486. # Keep a list of old files, so we can find/delete the output
  487. my @beforeFiles = readDir($path, undef());
  488. # Run the unrar utility
  489. my $pid = fork();
  490. if (!defined($pid)) {
  491. print STDERR "Unable to fork for RAR\n";
  492. return;
  493. } elsif ($pid == 0) {
  494. # Child
  495. close(STDOUT);
  496. close(STDERR);
  497. chdir($path);
  498. my @args = ('unrar', 'e', '-p-', '-y', $file);
  499. exec { $args[0] } @args;
  500. }
  501. # Wait for the child
  502. waitpid($pid, 0);
  503. # Compare the old file list to the new one
  504. my @newFiles = ();
  505. my @afterFiles = readDir($path, undef());
  506. foreach my $file (@afterFiles) {
  507. my $found = 0;
  508. foreach my $file2 (@beforeFiles) {
  509. if ($file eq $file2) {
  510. $found = 1;
  511. last;
  512. }
  513. }
  514. if (!$found) {
  515. push(@newFiles, $file);
  516. }
  517. }
  518. # Return the list of added files
  519. return @newFiles;
  520. }
  521. sub localSeriesCleanup($) {
  522. my ($name) = @_;
  523. $name =~ s/\.//g;
  524. return seriesCleanup($name);
  525. }
  526. sub seriesCleanup($) {
  527. my ($name) = @_;
  528. $name =~ s/\b(?:and|\&)\b/ /ig;
  529. $name =~ s/^\s*The\b//ig;
  530. if (!($name =~ /Being\W+Human/i) && !($name =~ /Top\W+Gear/i)) {
  531. $name =~ s/\bAU\b?\s*$//ig;
  532. $name =~ s/\bUS\b?\s*$//ig;
  533. $name =~ s/\([^\)]*\)//g;
  534. }
  535. $name =~ s/\[[^\]]*\]//g;
  536. $name =~ s/\{[^\}]*\}//g;
  537. $name =~ s/[\(\)]//g;
  538. $name =~ s/[\'\"]//g;
  539. $name =~ s/[^\w\s]+/ /g;
  540. $name =~ s/\b20[01][0-9]\s*$//;
  541. $name =~ s/_+/ /g;
  542. $name =~ s/\s+/ /g;
  543. $name =~ s/^\s*//;
  544. $name =~ s/\s*$//;
  545. return $name;
  546. }
  547. sub readDir($$) {
  548. my ($indir, $regex) = @_;
  549. # Allow optional use of a matching regex
  550. my $useRegex = 1;
  551. if (!defined($regex) || length($regex) < 1) {
  552. $useRegex = 0;
  553. }
  554. # Clean up the input directory
  555. $indir =~ s/\/+$//;
  556. my @files = ();
  557. if (!opendir(DIR, $indir)) {
  558. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  559. return;
  560. }
  561. foreach my $file (readdir(DIR)) {
  562. my $keep = 0;
  563. # Regex filter (if active)
  564. if (!$useRegex) {
  565. $keep = 1;
  566. } elsif (eval('$file =~ m' . $regex)) {
  567. $keep = 1;
  568. }
  569. # Construct a complete file path
  570. $file = $indir . '/' . $file;
  571. # Ignore directories
  572. if (-d $file) {
  573. $keep = 0;
  574. }
  575. # Save matching files
  576. if ($keep) {
  577. push(@files, $file);
  578. }
  579. }
  580. closedir(DIR);
  581. # Sorts the files before returning to the caller
  582. my @orderedFiles = ();
  583. @orderedFiles = sort(@files);
  584. # Return the file list
  585. return (@orderedFiles);
  586. }
  587. sub runAndCheck(@) {
  588. my (@args) = (@_);
  589. # Run
  590. system { $args[0] } @args;
  591. my $res = $?;
  592. # Die on any error
  593. if ($res == -1) {
  594. die('Unable to execute program: ' . join(' ', @args) . ': ' . $! . "\n");
  595. } elsif ($res & 127) {
  596. die('Child exited on signal: ' . join(' ', @args) . ': ' . ($res & 127) . "\n");
  597. } elsif ($res != 0) {
  598. die('Child exited with non-zero value: ' . join(' ', @args) . ': ' . ($res >> 8) . "\n");
  599. }
  600. # If we get here, all is well
  601. return 1;
  602. }