#!/usr/bin/python

from subprocess import Popen, PIPE
import json
import shlex
import sys
from itertools import izip
# read the argument string from the arguments file


def parseArgs(args_file):
    args_data = file(args_file).read()

    # for this module, we're going to do key=value style arguments
    # this is up to each module to decide what it wants, but all
    # core modules besides 'command' and 'shell' take key=value
    # so this is highly recommended

    arguments = shlex.split(args_data)
    args = {}
    for arg in arguments:

        # ignore any arguments without an equals in it
        if "=" in arg:

            (key, value) = arg.split("=")

            # if setting the time, the key 'time'
            # will contain the value we want to set the time to

            args[key] = value

    return args


def exitParamError(param):
    print json.dumps({
        "failed": True,
        "msg": "parameter %s is missing" % param
    })
    sys.exit(1)

def fail_json(param):
    print json.dumps({
        "failed": True,
        "msg": param
    })
    sys.exit(1)


def getPackageName(filePath):
    proc = Popen(["esxcli", "software", "sources", "vib", "list", "-d", filePath], stdout=PIPE)
    command_output = proc.communicate()[0]
    splitOut = shlex.split(command_output)
    splitOut = filter(lambda text: "--" not in text, splitOut)
    size = len(splitOut)
    software_info = dict(zip(splitOut[:size/2 + 1], splitOut[size/2 + 1:]))
    return software_info["Name"]


def checkIfPresent(name):
    proc = Popen(["esxcli", "software", "vib", "list"], stdout=PIPE)
    command_output = proc.communicate()[0]
    return name in command_output


def main():
    required_params = ["state", "name"]

    args_file = sys.argv[1]
    args = parseArgs(args_file)

    for param in required_params:
        if param not in args:
            exitParamError(param)

    output = "Nothing to do."

    if args["state"] == "present":
        packageName = getPackageName(args["name"])
        present = checkIfPresent(packageName)
        if not present:
            p = Popen(["esxcli", "software", "vib", "install", "-d", args["name"]], stdout=PIPE)
            output = p.communicate()[0]
            if p.returncode != 0:
                fail_json("Command failed with \n%s " % output)

    elif args["state"] == "absent":
        present = checkIfPresent(args["name"])
        if present:
            # fail_json(["esxcli", "software", "vib", "remove ", "--vibname", args["name"]])
            p = Popen(["esxcli", "software", "vib", "remove", "--vibname", args["name"]], stdout=PIPE)
            output = p.communicate()[0]
            if p.returncode != 0:
                if "No VIB matching VIB search specification" in  output:
                    print json.dumps({
                        "output": output,
                        "changed": False
                    })
                    sys.exit(0)
                else:
                    fail_json("Command failed with \n%s " % output)

    print json.dumps({
        "output": output,
        "changed": True
    })

if __name__ == '__main__':
    main()
