#!/usr/bin/python
#
#    user-data - 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

try:
    provisioning_conf_fh = open('/etc/orchestra/conf.d/provisioning.conf', 'r')
except Exception:
    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('/var/lib/orchestra/cloud-init/user-data.tpl', 'r')
except Exception:
    exit(1)

output_string = "Content-type: text/plain\n\n"
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()

print output_string
