#!/usr/bin/python
import MySQLdb
import sys
import getopt
import socket

hosts     = ['localhost','10.0.1.3','10.0.0.3']
port      = 3306
verbose   = False

def terminate():
    print "wqadd: wqadd <queuename>"
    sys.exit(1)

def conn_sql():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    for host in hosts:
        try:
            s.connect((host, port))
            s.shutdown(2)
            return(host)
        except:
            pass
    print "wqadd: Cannot connect to sql server, contact your DevOps."
    terminate()


options, remainder = getopt.getopt(sys.argv[1:], 'v', ['verbose'])

for opt, arg in options:
    if opt in ('-v', '--verbose'):
        verbose = True

if verbose:
    print 'OPTIONS   :', options
    print 'ARGV      :', sys.argv[1:]
    print 'VERBOSE   :', verbose
    print 'REMAINING :', remainder

if (len(sys.argv) < 2):
    print "wqadd: to few arguments."
    terminate()

wql_name = remainder[0]

try:
    host=conn_sql()
    db = MySQLdb.connect(host,"wq","wq","wq" )
except:
    print "Failed to connect to sql server, host(%s)" % (host)
    sys.exit(1)

cursor = db.cursor()

sql   = "INSERT INTO wql(wql_name) VALUES ('%s');" % (wql_name)
logit = "INSERT INTO wqlog(wqlog_name, wqlog_action, wqlog_datetime, wqlog_options) VALUES ('%s','%s',now(),'%s');" % (wql_name,'add','')

if verbose: 
   print sql
   print logit
#sys.exit(0)
try:
   cursor.execute(sql)
   cursor.execute(logit)
   db.commit()
except:
   db.rollback()
   print "wqnew: warning, this queue may exist (%s), no action." % (wql_name)
   sys.exit(1)

db.close()
sys.exit(0)
