add proper error handling for all final exec calls
[hband-tools.git] / user-tools / rcmod
blob2f18254a45ca96c93016269b4e870735bf0e61fd
1 #!/usr/bin/env perl
3 =pod
5 =head1 NAME
7 rcmod - Run a given command and modify its Return Code according to the rules given by the user
9 =head1 SYNOPSIS
11 rcmod [<FROM>=<TO> [<FROM>=<TO> [...]]] <COMMAND> [<ARGS>]
13 =head1 DESCRIPTION
15 If I<COMMAND> returned with code I<FROM> then rcmod(1) returns with I<TO>.
16 I<FROM> may be a comma-delimited list.
17 Keyword B<any> means any return code not specified in I<FROM> parameters.
18 Keyword B<same> makes the listed exit codes to be preserved.
20 rcmod any=0 1=13 2,3=same user-command
22 It runs I<user-command>, then exits with status 13 if I<user-command> exited
23 with 1, 2 if 2, 3 if 3, and 0 for any other return value.
25 If I<COMMAND> was terminated by a signal, rcmod(1) exits with 128 + signal number
26 like bash(1) does.
28 =head1 SEE ALSO
30 reportcmdstatus(1), sigdispatch(1)
32 =cut
35 use POSIX;
36 use Pod::Usage;
38 %RCmap = ();
40 while(@ARGV)
42 if(my ($from, $to) = $ARGV[0] =~ /^([\d,]+|any)=(\d+|same)$/)
44 shift @ARGV;
46 for my $inner_rc (split /,/, $from)
48 my $outer_rc = $to;
49 $outer_rc = $inner_rc if $to eq 'same';
50 $RCmap{$inner_rc} = $outer_rc;
53 else
55 last;
59 system @ARGV;
60 $status = ${^CHILD_ERROR_NATIVE};
62 if(WIFSIGNALED($status))
64 $mystatus = 128 + WTERMSIG($status);
66 else
68 $mystatus = WEXITSTATUS($status);
72 if(exists $RCmap{$mystatus})
74 $mystatus = $RCmap{$mystatus};
76 elsif(exists $RCmap{'any'})
78 $mystatus = $RCmap{'any'};
81 exit $mystatus;