#!/usr/bin/env python
#
# Copyright (c) 2015 Mark Kamichoff <prox@prolixium.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

import MySQLdb, sys, os

# MySQL info
dbhost="localhost"
dbuser="withings"
dbpass=""
dbname="withings"

def mrtgnormal():
	print os.popen('uptime').read(),
	print os.popen('hostname').read(),

def mrtgerror():
	print "0\n0"
	mrtgnormal()
	exit()

if len(sys.argv) == 1:
	mrtgerror()
else:
	db = MySQLdb.connect(user=dbuser,passwd=dbpass,db=dbname,host=dbhost)
	c = db.cursor()

	if sys.argv[1] == 'massbatt':
		c.execute("""SELECT (value.value*pow(10,value.unit))*1000,measure.battery FROM measure,value WHERE measure.id = value.measid AND value.type = 1 ORDER BY recvtime DESC LIMIT 1""")
		row = c.fetchone()
		if row != None:
			# mass is * 1000, since MRTG can't do FP
			print int(row[0])
			print row[1]
			mrtgnormal()
			c.close()
			db.close()
		else:
			c.close()
			db.close()
			mrtgerror()

	elif sys.argv[1] == 'reri':
		# re
		c.execute("""SELECT (value.value*pow(10,value.unit))*1000 FROM measure,value WHERE measure.id = value.measid AND value.type = 2 ORDER BY recvtime DESC LIMIT 1""")
		row = c.fetchone()
		if row != None:
			# mass is * 1000, since MRTG can't do FP
			print int(row[0])
		else:
			print 0

		# ri
		c.execute("""SELECT (value.value*pow(10,value.unit))*1000 FROM measure,value WHERE measure.id = value.measid AND value.type = 3 ORDER BY recvtime DESC LIMIT 1""")
		row = c.fetchone()
		if row != None:
			# mass is * 1000, since MRTG can't do FP
			print int(row[0])
		else:
			print 0

		mrtgnormal()
		c.close()
		db.close()
	else:
		c.close()
		mrtgerror()
