#!/usr/bin/python
#
#    orchestra-generate-cloud-init - Generate user-data needed by cloud-init
#
#    Copyright (C) 2011 Canonical
#
#    Author:
#               Marc Cluet <marc.cluet@canonical.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import random
import string
import ConfigParser
import StringIO
import re
import getopt
import sys

def usage():
    print "Usage: orchestra-generate-cloud-init -f [input template] -o [output file]"
    exit(2)

# Capture incoming args
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:f:", ["help", "output=", "file="])
except getopt.GetoptError, err:
    print str(err)
    usage()
    exit(2)

outputfile = None
inputfile = '/var/lib/orchestra/cloud-init/user-data.tpl'
for o, a in opts:
    if o in ("-f", "--file"):
        inputfile = a
    elif o in ("-o", "--output"):
        outputfile = a
    elif o in ("-h", "--help"):
        usage()
    else:
        usage()

try:
    provisioning_conf_fh = open('/etc/orchestra/conf.d/provisioning.conf', 'r')
except Exception:
    print "Can't find configuration file at /etc/orchestra/conf.d/provisioning.conf"
    usage()
    exit(1)
provisioning_conf = ConfigParser.ConfigParser()
provisioning_conf.readfp(StringIO.StringIO(''.join(i.lstrip() for i in provisioning_conf_fh.readlines())))
provisioning_conf_fh.close()

# Start reading the user-data.tpl
try:
    user_data_fh = open(inputfile, 'r')
except Exception:
    exit(1)

output_string = ""
for user_data_line in user_data_fh.readlines():
    re_exp = re.compile('.*@@(?P<tag>.*?)@@.*')
    re_line = re_exp.search(user_data_line)
    try:
        in_value = re_line.group('tag')
    except Exception:
        output_string += user_data_line
        continue
    line_print = False
    for config_item in provisioning_conf.items('provisioning'):
        if in_value == config_item[0]:
            output_string += string.replace(user_data_line, '@@' + in_value + '@@', config_item[1])
            line_print = True
    if line_print is False:
        output_string += user_data_line

user_data_fh.close()

if outputfile == None:
    print output_string
else:
    try:
        output_data_fh = open(outputfile, 'w')
    except Exception:
        print "Can't open file %s for writing" % outputfile
        exit(1)
    output_data_fh.write(output_string)
    output_data_fh.close()

