#!/bin/bash

# Get readings.
v1=$(mopicli -v1|sed -e's/^Source.*: //')
v2=$(mopicli -v2|sed -e's/^Source.*: //')
diff=$(echo ${v1}-${v2}|bc)
batt=$(/usr/local/bin/batt|sed -e's/^.*V := \(.*\)%$/\1/')

# No PSU.
if [ "$v1" == "0" ]
then
  l=$(echo "$batt/0.002473263071122"|bc)
  h=$(echo "scale=0;$l/3600"|bc)
  m=$(echo "scale=0;($l-$h*3600)/60"|bc)
  s=$(echo "scale=0;($l-$h*3600-$m*60)/1"|bc)
  printf "Battery 0: Discharging, %i%%, %02i:%02i:%02i remaining\n" $batt $h $m $s 2>/dev/null
# PSU, but not charging, or gate stuck.
elif [ $diff -lt 500 ]
then
  l=$(echo "$batt/0.002473263071122"|bc)
  h=$(echo "scale=0;$l/3600"|bc)
  m=$(echo "scale=0;($l-$h*3600)/60"|bc)
  s=$(echo "scale=0;($l-$h*3600-$m*60)/1"|bc)
  printf "Battery 0: Discharging, %i%%, %02i:%02i:%02i remaining\n" $batt $h $m $s 2>/dev/null
# Charged.
elif [ "$v2" -gt "12250" ]
  then
  # Crashes widget if 100%
  echo "Battery 0: Full, 99%"
# Charging.
else
  l=$(echo "(100-$batt)/0.002414937140946"|bc)
  h=$(echo "scale=0;$l/3600"|bc)
  m=$(echo "scale=0;($l-$h*3600)/60"|bc)
  s=$(echo "scale=0;($l-$h*3600-$m*60)/1"|bc)
  printf "Battery 0: Charging, %i%%, %02i:%02i:%02i until charged\n" $batt $h $m $s 2>/dev/null
fi

# Keep dock widget happy.
echo "Battery 0: design capacity 11200 mAh, last full capacity 11200 mAh = 100%"
