#!/usr/bin/env python

#
# Reads a template file, and substitutes %%expressions%% by values.
# The credentials are fetched from a credentials remote server through SSH.
# The configuration output file is printed to stdout
#
# Usage: ./genconfig <template file> > <config file>
#

import os
import re
import subprocess
import sys

#
# Helper functions
#

def execute_and_display (command):
	"""Executes a command and return the result as a trimmed string"""
	proc = subprocess.Popen(command, stdout=subprocess.PIPE)
	(out, err) = proc.communicate()
	return out.strip()

#
# Creditentials functions
#

def get_ssh_server ():
	"""Gets the SSH server to query credentials"""
	return os.getenv('SSH_SERVER', "localhost")

def get_credential (credential_id, credential_property):
	"""Gets the relevant property of the specified credential"""
	return execute_and_display([
		"ssh",
		get_ssh_server(),
		"getcredentials",
		credential_id,
		credential_property
	])

#
# Templates functions
#

def print_config_from_template (filename):
	"""Prints filename with config parameters substitution"""
	with open(filename) as f:
		for line in f:
			print substitute_parameters(line),

def substitute_parameters (text):
	"""Substitutes parameters in text"""
	pattern = re.compile(r"%%(.*?)%%")
	return re.sub(pattern, substitute_parameter, text)

def substitute_parameter (matchObj):
	"""
	Callback for the substitute regexp replacement method.

	Substitutes the specified parameter
	"""
	parameter = matchObj.group(1).split(".")

	if parameter[0] == "credentials":
		return get_credential(parameter[1], parameter[2])

	sys.stderr.write("Unknown parameter: " + parameter[0])
	return ""

#
# Procedural code
#

if len(sys.argv) != 2:
	print "Usage: genconfig <template file>"
	sys.exit(1)

print_config_from_template(sys.argv[1])
