#!/usr/bin/env python

from tools import *
import sys, MySQLdb, getpass, re#, pexpect
from getopt import getopt

ini_file = 'mpmdb.ini'
ini_file = os.path.join(os.path.split(os.path.abspath(__file__))[0], ini_file)

def addGO(host='localhost', port=3306, root_name='', root_passwd='', user='webarray', passwd='webarray_password', GO=None):
	if root_passwd:
		db = MySQLdb.connect(host=host, user=root_name, passwd=root_passwd)
	else:
		db = MySQLdb.connect(host=host, user=root_name)
	cur = db.cursor()
	if GO: cur.execute('GRANT SELECT on %s.* to %s IDENTIFIED BY "%s"' % (GO, user, passwd) )
	db.commit()
	cur.close()
	db.close()

def saveGO(GO, fn=ini_file):
	if GO:
		ini_dict = readINI(fn)
		ini_dict['GO'] = {'name' : GO}
		saveINI(ini_dict, fn)

def exitUsage(s=None):
	if s: print s, '\n\n'
	print 'Run as root\n\nUsage: %s [-u MySQL_Manager_Name] [-p] GO_dbname\nnote: use "-p" only if password is needed\n' % os.path.split(sys.argv[0])[1]
	sys.exit(0)

if __name__ == '__main__': 
	exec get_dbstr() #open('DBSRC').read()
	
	# need to know dbname, table definitions
	optlist, args = getopt(sys.argv[1:], 'u:p')
	optdict = dict(optlist)

	# get db name first
	if len(args) != 1: exitUsage('Wrong parameters in command line!')
		
	# MySQL manager name and password
	if not optdict.get('-u', ''): root_name = getpass.getuser() #exitUsage()
	else: root_name = optdict['-u']
	if optdict.has_key('-p'): root_passwd = getpass.getpass()
	else: root_passwd = ''

	GO = args[0]
	if GO:
		try:
			addGO(root_name = root_name, root_passwd = root_passwd, user=user, passwd=passwd, GO=GO)
			saveGO(GO)
		except:
			print 'You need MySQL manager privilege to create database!\n\n'
			raise
