#!/usr/bin/python

# py3 since dbus does not seem to always be available in py2

# py3 since dbus does not seem to always be available in py2

try:
    import dbus
except:
    # without dbus, just exit
    exit(0)

try:
    bus = dbus.SystemBus()
    bat0_object = bus.get_object('org.freedesktop.UPower',
                          '/org/freedesktop/UPower/devices/battery_BAT0')
    bat0 = dbus.Interface(bat0_object, 'org.freedesktop.DBus.Properties')
except:
    # without accessible battery, just exit
    exit(0)

print( bat0.Get("org.freedesktop.UPower.Device", "Percentage") )
print( bat0.Get("org.freedesktop.UPower.Device", "Time to empty") ) # in seconds, only available if state=2
print( bat0.Get("org.freedesktop.UPower.Device", "state") ) #0=charged, 1=charging, 2=discharging
print( bat0.Get("org.freedesktop.UPower.Device", "energy rate") ) # in watts

print( bat0.Get("org.freedesktop.UPower.Device", "Time to full") )

import logging
import logging.handlers
import argparse
import sys
import time

def set_syslog():
    try:
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        formatter = logging.Formatter("%(pathname)s: %(message)s")

        handler = logging.handlers.SysLogHandler(address = '/dev/log')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    except Exception:
        logging.critical("Failed to configure syslog handler")
        sys.exit(1)
    return logger

def uptime(logger):
    try:
        uptime_file = open('/proc/uptime', 'r')
        uptime_data = uptime_file.read().split()
        uptime_file.close()
    except Exception as e:
        logger.critical(e)
        sys.exit(1)

    up_and_idle_seconds = {}
    up_and_idle_seconds['uptime'] = int(round(float(uptime_data[0])))
    up_and_idle_seconds['idletime'] = int(round(float(uptime_data[1])))

    return up_and_idle_seconds

def print_for_graphite(scheme, metrics, logger):
    now = time.time()
    try:
        for metric in metrics:
            print "%s.%s %d %d" % (scheme, metric, metrics[metric], now)
    except Exception as e:
        logger.critical(e)
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-s', '--scheme',
        default = 'uptime',
        dest    = 'graphite_scheme',
        help    = 'Metric Graphite naming scheme, text to prepend to metric',
        metavar = 'SCHEME')

    args = parser.parse_args()

    logger = set_syslog()
    metrics = uptime(logger)
    print_for_graphite(args.graphite_scheme, metrics, logger)

if __name__ == '__main__':
    main()