transmission.pl 16 KB

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