#!/usr/bin/env python
"""
Tool to interact with HAProxy.

Notes
=====

haproxyctl looks for a configuration file on the following places:
1) Global: /etc/haproxyctl/haproxyctl.conf
2) User: ~/.haproxyctl.conf
3) Command line options.

This order is important, since options in the global file will
get overriden by the ones in the user config file, which in turn 
will get overriden by the command line options."""

import os
import sys
import argparse
from ConfigParser import ConfigParser

from haproxy.conn import HaPConn
from haproxy import cmds

VERBOSE = False
GCONFIG="/etc/haproxyctl/"
UCONFIG=os.path.expanduser("~/.")

def process_config_files():
    config_opts = {}
    cfgp = ConfigParser()

    for cfg in [GCONFIG, UCONFIG]:
        cfgf = "".join((cfg, "haproxyctl.conf"))
        if os.path.exists(cfgf):
            cfgp.read(cfgf)
            for k, v in cfgp.items("global"):
                config_opts[k] = v

    return config_opts

def logger(msg):
    if VERBOSE:
        print msg

def main(args):
    logger("Starting with args: ")
    logger(args)

    cmdline = {'backend' : args.backend, 
               'weight' : args.weight,
               'server' : args.server}

    cmdMap = {"info" : cmds.showInfo,
              "enable" : cmds.enableServer,
              "disable" : cmds.disableServer,
              "get-weight" : cmds.getWeight,
              "servers" : cmds.listServers,
              "set-weight" : cmds.setWeight}

    if args.list_commands:
        print "Available commands:"
        for c in cmdMap.keys():
            print "\t", c, " - ", cmdMap[c].getHelp()
        return 2

    cCmd = cmdMap.get(args.command, None)

    if cCmd:
        if args.help_command:
            print args.command, " - ", cCmd.getHelp()
        else:

            if not args.socket:
                print "HAProxy socket not found. Must provide a socket file"
                return 3

            h_so = HaPConn(args.socket)

            if h_so:
                print h_so.sendCmd(cCmd(**cmdline))
            else:
                print "Could not open socket"
    else:
        print "Need to specify a backend."

    return 0
    
if __name__ == "__main__":
    
    st = "store_true"
    cfo = process_config_files()
    opts = argparse.ArgumentParser(description="Tool to interact with HAProxy", prog="haproxyctl")

    opts.add_argument("-v", "--verbose", help="Be verbose.", action=st, default=cfo.get('verbose', False))
    opts.add_argument("-c", "--command", help="Type of command. Default info", default="info")
    opts.add_argument("-l", "--list-commands", help="Lists available commands.", action=st)
    opts.add_argument("-H", "--help-command", help="Shows help for the given command.", action=st)
    opts.add_argument("-s", "--server", help="Attempt action on given server.", default=None)
    opts.add_argument("-b", "--backend", help="Set backend to act upon.", default=cfo.get('backend', None))
    opts.add_argument("-k", "--socket", help="Socket to talk to HAProxy.", default=cfo.get('socket', None))
    opts.add_argument("-w", "--weight", help="Specify weight for a server.")

    args = opts.parse_args()
    VERBOSE = args.verbose

    sts = main(args)
    sys.exit(sts)
