make getpeername() return the original socket address which before it was intercepted
[hband-tools.git] / admin-tools / check-battery
bloba91eb9a6a01e1db443ea18ea9957f852fd2ec180
1 #!/usr/bin/env perl
3 $0 =~ s/^.*\/([^\/]+)$/$1/;
5 if(not $ENV{'BATTERY_LOW_ACTION'})
7 die "$0: Set BATTERY_LOW_ACTION environment to a command.\n";
9 if(not $ENV{'BATTERY_TIME_THRESHOLD'} and not $ENV{'BATTERY_PERCENTAGE_THRESHOLD'})
11 die "$0: Set BATTERY_TIME_THRESHOLD and/or BATTERY_PERCENTAGE_THRESHOLD environment to at most how many remaining sec or percentage will trigger the action.\n";
13 if(not $ENV{'MIN_UPTIME'})
15 die "$0: Set MIN_UPTIME environment to prevent firing action shortly after reboot.\n";
19 open my $fh, '/proc/uptime' or die "$0: $!";
20 ($uptime) = <$fh> =~ /(\d+)/;
21 close $fh;
23 if($uptime <= $ENV{'MIN_UPTIME'})
25 exit 0;
29 $highest_remaining_sec = undef;
30 $highest_percent = undef;
31 $batteries_with_sufficient_charge = 0;
34 open my $pipe, '-|', 'acpi', '-ab' or die "$0: $!";
35 while(<$pipe>)
37 chomp;
38 $remaining_sec = undef;
39 $remaining_time = undef;
40 $percent = undef;
41 my $battery_may_have_insufficient_charge = 1;
43 if(/Adapter/)
45 if(/on-line/)
47 warn "$0: $_: No action.\n";
48 exit 0;
50 next;
52 if(/(\d\d+):(\d\d):(\d\d) remaining/)
54 my ($hour, $min, $sec) = ($1, $2, $3);
55 $remaining_sec = $hour * 3600 + $min * 60 + $sec;
56 if($remaining_sec > $highest_remaining_sec)
58 $highest_remaining_sec = $remaining_sec;
59 $highest_remaining_time = "$hour:$min:$sec";
62 if(/(\d+)%/)
64 $percent = $1;
65 if($percent > $highest_percent)
67 $highest_percent = $percent;
71 my $sufficient_time = undef;
72 my $sufficient_percent = undef;
74 if($ENV{'BATTERY_TIME_THRESHOLD'} and defined $remaining_sec)
76 $sufficient_time = $remaining_sec >= $ENV{'BATTERY_TIME_THRESHOLD'} ? 1 : 0;
78 if($ENV{'BATTERY_PERCENTAGE_THRESHOLD'} and defined $percent)
80 $sufficient_percent = $percent >= $ENV{'BATTERY_PERCENTAGE_THRESHOLD'} ? 1 : 0;
83 if((not defined $sufficient_time or $sufficient_time) and (not defined $sufficient_percent or $sufficient_percent))
85 $battery_may_have_insufficient_charge = 0;
88 if(not $battery_may_have_insufficient_charge)
90 $batteries_with_sufficient_charge++;
93 close $pipe;
96 $message = sprintf "remaining percentage: %s%%, remaining time: %s, batteries with enough capacity: %d.", $highest_percent // "unknown", $highest_remaining_time // "unknown", $batteries_with_sufficient_charge;
99 if($batteries_with_sufficient_charge < 1)
101 my $command = $ENV{'BATTERY_LOW_ACTION'};
102 warn "$0: $message Running '$command'.\n";
103 system $command;
105 else
107 warn "$0: $message No action.\n";