#!/bin/bash
#
# This file is part of the battery-stats package.
# Copyright (C) 2013-2016 Petter Reinholdtsen <pere@hungry.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
#
# Inspired by
# http://www.ifweassume.com/2013/08/the-de-evolution-of-my-laptop-battery.html
# See also
# http://blog.sleeplessbeastie.eu/2013/01/02/debian-how-to-monitor-battery-capacity/

logfile=/var/log/battery-stats.csv

files="manufacturer \
    model_name \
    technology \
    serial_number \
    status \
    cycle_count \
    energy_now \
    energy_full \
    energy_full_design \
    charge_now \
    charge_full \
    charge_full_design \
    "

TEMP=$(getopt --name collect-csv --options o: --longoptions output: -- "$@")
eval set -- "$TEMP"
while true; do
    case "$1" in
        -o|--output)
            logfile="$2"; shift 2; continue
            ;;
        --) # no more arguments to parse
            break
            ;;
        *)
            printf "Unknown option %s\n" "$1"
            exit 1
            ;;
    esac
done

if [ ! -e "$logfile" ] ; then
    (
        printf "timestamp,when,"
        for f in $files; do
            printf "%s," $f
        done
        echo
    ) > "$logfile"
fi

log_battery() {
    printf "%s,%s," "$(date +%s)" "$(date --iso-8601=seconds)"
    for f in $files; do
        for file in $(echo $f | tr / " "); do
            if [ -e $file ] ; then fexist=$file; else fexist= ; fi
        done
        if [ "$fexist" ] && [ -e "$fexist" ] ; then
            printf "%s," "$(cat $fexist | sed -s 's/\(.* .*\)/"\1"/' )"
        else
            printf ","
        fi
    done
}

cd /sys/class/power_supply

for bat in $(find -L . -maxdepth 1 -name "BAT*" -type d); do
    # Print complete message in one echo call, to avoid race condition
    # when several log processes run in parallel.
    (cd $bat && echo $(log_battery)) >> "$logfile"
done
