# vqconfig.py

'''
Module to parse config file in ~/.vquery
Do not edit this file. Make your changes in ~/.vquery
'''

import sys
import re
import getpass
from os.path import expanduser
from os import chmod

def getconfig(config_id="default"):
	if config_id is None:
		config_id = "default"

	# Set the file path.
	home = expanduser("~")
	file_path = home + "/.vquery"

	try:
		# Open the config file.
		config_file = open(file_path, "r")
	except Exception as error:
		# If no config file found, create one.
		if str(error).find("No such file"):
			print("WARNING: No config file found.")
			createconfig(file_path)
	else:
		# Config structure.
		config = { "server": None, "port": None, "username": None, "password": <PASSWORD> }

		# Populate config structure.
		for line in config_file:
			# Find the config identifier within brackets.
			id = line[line.find("[")+1:line.find("]")]
			# If no match on config id, skip this line.
			if id != config_id:
				continue
			# Remove the id and brackets.
			line = line.split("]",1)[1]
			# Partition the line.
			line = line[0:-1].partition(': ')
				
			if line[0] in config.keys():
				config[line[0]] = line[2]

		config_file.close()

		try:
			# Set port to 443 if not specified.
			if config['port'] is None:
				config['port'] = "443"
			# Check for unpopulated keys.
			#for value in config.values():
			#	if not value:
			#		raise Exception("Entries missing.")
			# Turn port number to int.
			config['port'] = int(config['port'])
		except Exception as error: 
			print("WARNING: Error parsing config file. Try editing or deleting %s" % file_path)
			print(error)
			exit()
		else:
 			return config

def createconfig(file_path):
	config_content = [
	"# vQuery configuration\n",
	"#\n",
	"# You can add connection profiles by adding your own [tags] in this file.\n",
	"# This is useful if you have several vCenter deployments you frequently connect to.\n",
	"# Example usage: vq vm --vc=site2\n",
	"#\n",
	"# If you don't specify a password, you will be prompted to type it whenever you run a command.\n",
	"#\n",
	"# The [default] tag makes up your default params, which is the default site to use if no specific vCenter is specified.\n",
	"#\n",
	"[default]server: yourhost\n",
	"[default]port: 443\n",
	"[default]username: you@yourhost\n",
	"[default]password: <PASSWORD>",
	"[site2]server: someotherhost\n",
	"[site2]port: 443\n",
	"[site2]username: you@someotherhost\n",
	"[site2]password: <PASSWORD>"]

	try:
		config_file = open(file_path, "w")
		for c in config_content:
			config_file.write(c)
		config_file.close()
		chmod(file_path, 0o600)
	except Exception as error:
		print(error)
	else:
		print("INFO: Default config file created. Make sure to edit %s" % file_path)
	finally:
		sys.exit()

