aboutsummaryrefslogtreecommitdiff
path: root/on-battery-time.sh
blob: 6e901dc113c65d85b6a21a38ea3c4b835e68dc5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/bin/sh
# File: /usr/local/bin/on-battery-time.sh
# Author: bgstack15
# Startdate: 2019-06-09 22:35
# Title: Report how long this system has been on battery or AC power
# Package: on-battery-time
# Purpose:
# History:
# Usage:
# Reference:
#    https://stackoverflow.com/questions/12199631/convert-seconds-to-hours-minutes-seconds/18683834#18683834
# Improve:
# Dependencies:
#    bc
#    date
#    the udev rules from 99-on-battery-time.rules
# Documentation:

OBT_INFILE=/var/log/battery.log

# FUNCTIONS
convertsecs() {
    _h=$( expr $1 / 3600 )
    _m=$( expr $1  % 3600 / 60 )
    _s=$( expr $1 % 60 )
    printf "%02d:%02d:%02d\n" ${_h} ${_m} ${_s}
}

# learn most recent utility time
last_utility_time="$( { tac "${OBT_INFILE}" | awk '/utility power/{print $2}' ; echo 0 ; } | head -n1 )"

# learn most recent battery time
last_battery_time="$( { tac "${OBT_INFILE}" | awk '/on battery/{print $2}' ; echo 0 ; } | head -n1 )"

# learn current time
OBT_current_time="$( date "+%s" )"

if test ${last_utility_time} -ge ${last_battery_time} ;
then
   OBT_last="${last_utility_time}"
   OBT_phrase="utility power"
else
   OBT_last="${last_battery_time}"
   OBT_phrase="on battery"
fi

OBT_seconds="$( printf "%s-%s\n" "${OBT_current_time}" "${OBT_last}" | bc )"

printf "%s seconds: %s\n" "${OBT_phrase}" "${OBT_seconds}"
convertsecs "${OBT_seconds}"
bgstack15