transmission.pl 17 KB

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