#!/usr/bin/python
import MySQLdb,sys

dbhost = 'svn.localpages.com'
dbuser = 'getuser'
dbpass = 'rsQHWpMjm3'
dbname = 'pusher'

def getrepopath(pid):
	db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
	c = db.cursor()
	c.execute("SELECT repopath FROM pushers WHERE id=%s",(pid,))
	repopath = c.fetchone()
	c.close()
	return repopath[0]

def gethosts(pid,pushtype):
	db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
	c = db.cursor()
	c.execute("""SELECT servergroup_id,remotepath FROM pushergroups \
		WHERE pusher_id=%s AND pushtype=%s""", (pid,pushtype))
	servergroup,remotepath = c.fetchone()
	c.execute("""SELECT INET_NTOA(servers.ip) FROM servers WHERE servers.id IN \
		(SELECT server_id FROM servergroupmaps WHERE group_id=%s) AND servers.enabled=1""", (servergroup,))
	hosts = c.fetchall()
	c.close()
	return [(i[0],remotepath) for i in hosts]

def getexcludefile(pid):
	db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
	c = db.cursor()
	c.execute("SELECT excludefile FROM pushers WHERE id=%s",(pid,))
	excludefile = c.fetchone()
	c.close()
	return excludefile[0]

def getchown(pid):
	db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
	c = db.cursor()
	c.execute("SELECT chown FROM pushers WHERE id=%s",(pid,))
	chown = c.fetchone()
	c.close()
	return chown[0]

def getclusterips(cid=None):
	db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
	c = db.cursor()
	if not cid:
		c.execute("SELECT id,name FROM servergroups")
		print "id - name\n"
		for id,name in c.fetchall():
			print "%s - %s" % (id,name)
		cid = raw_input("\nWhich cluster id? ")
	c.execute("SELECT INET_NTOA(s.ip) FROM servers AS s, servergroups AS sg, servergroupmaps AS sgm \
		WHERE s.id=sgm.server_id AND sg.id=sgm.group_id AND sg.id=%s AND s.enabled=1",(cid,))
	ips = [i[0] for i in c.fetchall()]
	c.close()
	return ips

if __name__ == "__main__":
	if len(sys.argv) > 1:
		if sys.argv[1] == 'repopath':
			print getrepopath(sys.argv[2])
		elif sys.argv[1] == 'hosts':
			pid,pushtype = sys.argv[2:]
			hosts = gethosts(pid,pushtype)
			print " ".join(["%s|%s"%(i,j) for i,j in hosts])
		elif sys.argv[1] == 'excludefile':
			print getexcludefile(sys.argv[2])
		elif sys.argv[1] == 'chown':
			print getchown(sys.argv[2])
		elif sys.argv[1] == 'clusterips':
			cid = None
			if len(sys.argv) == 3:
				cid = sys.argv[2]
			print "\n".join(getclusterips(cid))
	else:
		print "Usage: get.py <command> <args>   Note: <required> [optional]"
		print "Commands: repopath <pusherid>"
		print "          hosts <pusherid> <pushtype>"
		print "          excludefile <pusherid>"
		print "          chown <pusherid>"
		print "          clusterips [clusterid]"
