#!/usr/bin/env python3

import argparse
import json


# This is the location of the IaaS swagger
old_filename = "swagger/vra-catalog-deployment.json"
new_filename = "swagger/vra-catalog-deployment-fixed.json"


# Adds the apiVersion parameter to all the paths in the catalog, deployments,
def add_apiVersion(swagger):
    apiVersion_parameter = {
        "type": "string",
        "description": "The version of the API in yyyy-MM-dd format (UTC). For versioning information please refer to /catalog/api/about",
        "name": "apiVersion",
        "in": "query"
    }

    # Update all the paths to include apiVersion parameter
    for p in swagger['paths']:
        for method in swagger['paths'][p]:
            if 'parameters' in swagger['paths'][p][method]:
                param_list = swagger['paths'][p][method]['parameters']
                param_name_list = [d['name'] for d in param_list]
                if apiVersion_parameter['name'] not in param_name_list:
                    param_list.insert(0, apiVersion_parameter)
            else:
                swagger['paths'][p][method]['parameters'] = []
                swagger['paths'][p][method]['parameters'].append(apiVersion_parameter)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    args = parser.parse_args()

    # read in the swagger spec
    swagger = json.loads(open(old_filename).read())

    add_apiVersion(swagger)

    # Overwrite the swagger spec
    f = open(new_filename, "w")
    f.write(json.dumps(swagger, sort_keys=False, indent=2))
    f.write('\n')
