import click
import os

from ..cli import cli_command
from ..utils import load_file, template_string


@cli_command('paas-manifest', max_apps=1)
@click.option('--template', '-t', default='paas/manifest.j2',
              type=click.Path(exists=True),
              help="Manifest Jinja2 template file")
@click.option('--out-file', '-o',
              help="Output file, if empty the template content is printed to the stdout")
def paas_manifest(ctx, template, out_file):
    """Generate a PaaS manifest file from a Jinja2 template"""
    app = ctx.apps[0]

    if app not in ctx.variables:
        raise ValueError('Application configuration not found')

    templace_content = load_file(template)
    variables = {
        'environment': ctx.environment,
        'app': app.replace('_', '-')
    }
    variables.update(ctx.variables[app])

    manifest_content = template_string(templace_content, variables)

    if out_file is not None:
        with open(out_file, 'w') as f:
            f.write(manifest_content)
        os.chmod(out_file, 0o600)
    else:
        print(manifest_content)

@@ -93,16 +93,29 @@
 e_string
+, merge_dicts
 %0A%0A%0A@cli_
@@ -155,166 +155,8 @@
 =1)%0A
-@click.option('--template', '-t', default='paas/manifest.j2',%0A              type=click.Path(exists=True),%0A              help=%22Manifest Jinja2 template file%22)%0A
 @cli
@@ -301,18 +301,8 @@
 ctx,
- template,
  out
@@ -497,51 +497,8 @@
 ')%0A%0A
-    templace_content = load_file(template)%0A
     
@@ -598,29 +598,175 @@
   %7D%0A
+%0A
     
-variables.update(
+template_content = load_file('paas/%7B%7D.j2'.format(variables%5B'app'%5D))%0A%0A    variables = merge_dicts(variables, ctx.variables)%0A    variables = merge_dicts(variables, 
 ctx.
@@ -827,17 +827,17 @@
 g(templa
-c
+t
 e_conten
@@ -848,16 +848,40 @@
 ariables
+, templates_path='paas/'
 )%0A%0A    i

Update paas-manifest command to load per-app manifests