#!/usr/bin/env bash
#
# Copyright (C) 2016 Denis 'GNUtoo' Carikli <GNUtoo@no-log.org>
#
# 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 3 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.

psql="psql -q"

get_sysfs_dir()
{
    batt_dirs=""
    for dir in $(ls -d /sys/class/power_supply/*) ; do
        if [ ! -f "${dir}"/type ] ; then
            continue
        fi
        if [ "$(cat "${dir}"/type)" != "Battery" ] ; then
            continue
        fi
        batt_dirs+="${dir}"
    done

    nr_batt_dirs="$(echo "${batt_dirs}" | wc -l)"

    if [ "${nr_batt_dirs}" -eq 1 ] ; then
        echo "${batt_dirs}"
        exit 0
    fi

    # We don't support multiple batteries yet
    return 1
}



get_sysfs()
{
  file="$(get_sysfs_dir)/$1"
  if [ -f "${file}" ] ; then
      printf "%s\n" "$(cat ${file})"
      return 0;
  else
      return 1;
  fi
}

get_battery_sql_id()
{
    ${psql} \
	--tuples-only --no-align private \
	-c "SELECT id FROM battery \
	WHERE model_name = '$(get_sysfs \"model_name\")' \
	AND manufacturer = '$(get_sysfs \"manufacturer\")' \
	AND serial_number = '$(get_sysfs \"serial_number\")' \
	AND technology = '$(get_sysfs \"technology\")' \
	;"
}

get_battery_from_sql()
{
    sql_id="$(get_battery_sql_id)"
    if [ -n "${sql_id}" ] ; then
	${psql} private -c 'SELECT * FROM battery WHERE id = '"${sql_id};"
    fi
}


add_battery_to_sql()
{
    sql_id="$(get_battery_sql_id)"
    if [ -n "${sql_id}" ] ; then
	return 0 ;
    fi

    ${psql} private -c "INSERT INTO battery			\
	 (model_name, manufacturer, serial_number, technology,	\
	  energy_full_design, energy_full,			\
	  charge_full_design, charge_full) VALUES (		\
	  '$(get_sysfs \"model_name\")',				\
	  '$(get_sysfs \"manufacturer\")',			\
	  '$(get_sysfs \"serial_number\")',			\
	  '$(get_sysfs \"technology\")',				\
	  $(get_sysfs \"energy_full_design\"),			\
	  $(get_sysfs \"energy_full\"),				\
	  $(get_sysfs \"charge_full_design\"),			\
	  $(get_sysfs \"charge_full\"));			\
	  "
}

dummy_add_battery_to_sql()
{
    echo "${psql} private -c INSERT INTO battery		\
	 (model_name, manufacturer, serial_number, technology,	\
	  energy_full_design, energy_full,	   		\
	  charge_full_design, charge_full) VALUES (		\
	  '$(get_sysfs \"model_name\")',				\
	  '$(get_sysfs \"manufacturer\")',			\
	  '$(get_sysfs \"serial_number\")',			\
	  '$(get_sysfs \"technology\")',				\
	  $(get_sysfs \"energy_full_design\"),			\
	  $(get_sysfs \"energy_full\")				\
	  $(get_sysfs \"charge_full_design\"),			\
	  $(get_sysfs \"charge_full\"));			\
	  " | sed 's#\t##g' | sed 's# \+# #g'
}

print_remaining_battery_capacity()
{
    capacity="$(get_sysfs "capacity")"
    if [ -n "${capacity}" ] ; then
	printf "%s%% of charge\n" "-> ${capacity}"
    else
	printf "No battery detected\n"
  fi
}

print_remaining_battery_energy()
{
    energy_full_design="$(get_sysfs "energy_full_design")"
    energy_full="$(get_sysfs "energy_full")"
    if [ -n "${energy_full_design}" -o -n "${energy_full}" ] ; then
        percent="$(expr $(expr 100 \* ${energy_full}) / ${energy_full_design})"
        printf \
            "   %s Wh: %s%% of original battery\n" \
            "$(expr ${energy_full} / 1000000)" \
            "${percent}"
    fi
}

print_remaining_battery_charge()
{
    charge_full_design="$(get_sysfs "charge_full_design")"
    charge_full="$(get_sysfs "charge_full")"
    if [ -n "${charge_full_design}" -o -n "${charge_full}" ] ; then
        percent="$(expr $(expr 100 \* ${charge_full}) / ${charge_full_design})"
        printf \
            "   %s Ah: %s%% of original battery\n" \
            "$(expr ${charge_full} / 1000000)" \
            "${percent}"
    fi
}

log_remaining_percentage()
{
  shift 1
  if [ $# -gt 0 ] ; then
    echo -n "$@: "
  fi
  printf "%s %s\n" "$(date): " "$(print_remaining_battery_capacity)"
}

usage()
{
  echo "Usage: $0"
  echo "       $0 log [message]"
  echo "       $0 continuous-log <sleep-time> [message]"
  echo "       $0 add-to-sql [dry-run]"
  echo "       $0 get-from-sql"
  exit 1
}

if [ $# -eq 0 ] ; then
 print_remaining_battery_capacity
 print_remaining_battery_energy
 print_remaining_battery_charge
elif [ $# -gt 1 -a "$1" = "continuous-log" ] ; then
    sleep_time="$2"
    shift 1
    while true; do
	log_remaining_percentage "$@"
	sleep "${sleep_time}"
    done
elif [ $# -gt 1 -a "$1" = "log" ] ; then
 log_remaining_percentage "$@"
elif [ $# -eq 1 -a "$1" = "add-to-sql" ] ; then
    add_battery_to_sql
elif [ $# -eq 2 -a "$1" = "add-to-sql" -a "$2" = "dry-run" ] ; then
    dummy_add_battery_to_sql
elif [ $# -eq 1 -a "$1" = "get-from-sql" ] ; then
    get_battery_from_sql
else
   usage
fi
