#!/usr/bin/env python
#-*- encoding: utf-8 -*-
#
# This file belongs to coshsh.
# Copyright Gerhard Lausser.
# This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from optparse import OptionParser
import sys
import os
import shutil
from subprocess import Popen, PIPE, STDOUT
from tempfile import gettempdir
import time
from logging import INFO, DEBUG

sys.dont_write_bytecode = True
try:
    import coshsh
except Exception:
    if 'COSHSH_HOME' in os.environ:
        coshsh_home = os.environ['COSHSH_HOME']
    else:
        coshsh_home = os.path.join(os.path.dirname(__file__), '..')
        os.environ['COSHSH_HOME'] = coshsh_home
    sys.path.append(coshsh_home)
    try:
        import coshsh
    except Exception:
        print "Could not load package coshsh. Check your PYTHONPATH"
        sys.exit(3)

from coshsh.generator import Generator
from coshsh.util import substenv
from coshsh.configparser import CoshshConfigParser


class GeneratorMessage(object):
    def __init__(self, message):
        self.message = message

class WarningMessage(GeneratorMessage):
    pass

class CriticalMessage(GeneratorMessage):
    pass

class OkMessage(GeneratorMessage):
    pass


if __name__ == '__main__':
    VERSION = "1.0"


    parser = OptionParser(
        "%prog [options] --cookbook cookbookfile [--recipe recipe]",
        version="%prog " + VERSION)
    parser.add_option('--cookbook', action='store',
                      dest="cookbook_file",
                      help='Config file')
    parser.add_option('--recipe', action='store',
                      dest="default_recipe",
                      help="Only create a cookbook for <recipe>")
    parser.add_option('--template', action='store',
                      dest="template_name",
                      help="Build a template hierarchy for this service profile")
    parser.add_option('--debug', action='store_const',
                      const="debug",
                      default="info",
                      dest="default_log_level",
                      help="Output additional messages on stdout")

    opts, args = parser.parse_args()
    generator = coshsh.generator.Generator()
    if opts.cookbook_file:
        cookbook = coshsh.configparser.CoshshConfigParser()
        cookbook.read(opts.cookbook_file)
        if cookbook._sections == {}:
            print "Bad or missing cookbook file : %s " % opts.cookbook_file
            sys.exit(2)
            
        recipes = []
        if not opts.template_name:
            parser.error("Which template hierarchy should i create? Use --template")
        if opts.default_recipe:
            recipes = [opts.default_recipe.lower()]
        else:
            try:
                recipes = [s.strip().lower() for s in cookbook.get("defaults", "recipes").split(",")]
            except Exception:
                recipes = []
        if "defaults" in cookbook.sections() and "log_dir" in [c[0] for c in cookbook.items("defaults")]:
            log_dir = dict(cookbook.items("defaults"))["log_dir"]
            log_dir = re.sub('%.*?%', coshsh.util.substenv, log_dir)
        elif 'OMD_ROOT' in os.environ:
            log_dir = os.path.join(os.environ['OMD_ROOT'], "var", "coshsh")
        else:
            log_dir = gettempdir()

        if opts.default_log_level and opts.default_log_level.lower() == "debug" or "defaults" in cookbook.sections() and "log_level" in [c[0] for c in cookbook.items("defaults")] and cookbook.items("defaults")["log_level"].lower() == "debug":
            generator.setup_logging(logdir=log_dir, scrnloglevel=DEBUG)
        else:
            generator.setup_logging(logdir=log_dir, scrnloglevel=INFO)

        for recipe in [section for section in cookbook.sections() if section.startswith('recipe_')]:
            if recipe.replace("recipe_", "", 1).lower() in recipes:
                generator.add_recipe(name=recipe.replace("recipe_", "", 1), **dict(cookbook.items(recipe)))
    else:
        parser.error("Please use option -c/--cookbook")
    if args:
        parser.error("Does not accept any argument. Use option -c/--cookbook")

    for recipe in generator.recipes.values():
        #recipe.collect()
        basedir = recipe.objects_dir + "/static/service_templates"
        if os.path.exists(recipe.objects_dir):
            if not os.path.exists(recipe.objects_dir + "/static"):
                os.mkdir(recipe.objects_dir + "/static")
            if not os.path.exists(recipe.objects_dir + "/static/service_templates"):
                os.mkdir(recipe.objects_dir + "/static/service_templates")

        template = opts.template_name
        created = False
        while template.find("_") != -1:
            template, sep, tail = template.rpartition("_")
            output = "define service {\n  name %s\n  use %s\n  register 0\n}\n" % (template + sep + tail, template)
            template_file = os.path.join(basedir, template + sep + tail + ".cfg")
            if not os.path.exists(template_file):
                print "create %s" % template_file
                with open(template_file, "w") as f:
                    f.write(output)
                    created = True
            else:
                print "confirm %s" % template_file
        if created and os.path.exists(recipe.objects_dir + '/static/.git'):
            save_dir = os.getcwd()
            os.chdir(recipe.objects_dir + '/static')
            process = Popen(["git", "add", "."], stdout=PIPE, stderr=STDOUT)
            output, unused_err = process.communicate()
            retcode = process.poll()
            commitmsg = time.strftime("%Y-%m-%d-%H-%M-%S") + " create template %s" % (template, )
            process = Popen(["git", "commit", "-a", "-m", commitmsg], stdout=PIPE, stderr=STDOUT)
            output, unused_err = process.communicate()
            retcode = process.poll()
            print output
            os.chdir(save_dir)

