#!/usr/bin/env python

import os

import click
import yaml
from fnmatch import fnmatch
import shutil

def ensure_dir(dir):
    try:
        os.makedirs(dir)
    except OSError:
        pass

CURDIR = os.path.dirname(os.path.realpath(__file__))

LIBRARY_PATH = os.path.join(CURDIR, 'fuel-library')
RESOURCE_TMP_WORKDIR = os.path.join(CURDIR, 'tmp/resources')
ensure_dir(RESOURCE_TMP_WORKDIR)
RESOURCE_DIR = os.path.join(CURDIR, 'resources')

class Task(object):

    def __init__(self, task_data, task_path):
        self.data = task_data
        self.src_path = task_path
        self.name = self.data['id']
        self.type = self.data['type']

    @property
    def dst_path(self):
        return os.path.join(RESOURCE_TMP_WORKDIR, self.data['id'])

    @property
    def actions_path(self):
        return os.path.join(self.dst_path, 'actions')

    @property
    def meta_path(self):
        return os.path.join(self.dst_path, 'meta.yaml')

    def meta(self):
        data = {'id': self.data['id'],
                'handler': 'puppetv2',
                'version': '8.0',
                'inputs': self.inputs()}
        return yaml.safe_dump(data, default_flow_style=False)

    @property
    def actions(self):
        """yield an iterable of src/dst
        """
        yield os.path.join(self.src_path, self.data['id'] + '.pp'), os.path.join(self.actions_path, 'run.pp')

    def inputs(self):
        return {}


def get_files(base_dir, file_pattern='*tasks.yaml'):
    for root, _dirs, files in os.walk(base_dir):
        for file_name in files:
            if fnmatch(file_name, file_pattern):
                yield root, file_name

def load_data(base, file_name):
    with open(os.path.join(base, file_name)) as f:
        return yaml.load(f)

def preview(task):
    print 'PATH'
    print task.dst_path
    print 'META'
    print task.meta()
    print 'ACTIONS'
    for action in task.actions():
        print 'src=%s dst=%s' % action

def create(task):
    ensure_dir(task.dst_path)
    ensure_dir(task.actions_path)
    with open(task.meta_path, 'w') as f:
        f.write(task.meta())
    for src, dst in task.actions:
        shutil.copyfile(src, dst)

@click.group()
def main():
    pass

@main.command(help='converts tasks into resources')
@click.argument('tasks', nargs=-1)
@click.option('-t', is_flag=True)
@click.option('-p', is_flag=True)
def t2r(tasks, t, p):
    for base, task_yaml in get_files(LIBRARY_PATH + '/deployment'):
        for item in load_data(base, task_yaml):
            task = Task(item, base)
            if task.type != 'puppet':
                continue

            if task.name in tasks or tasks is ():
                if p:
                    preview(task)
                else:
                    create(task)

if __name__ == '__main__':
    main()

@@ -434,16 +434,118 @@
 rces')%0A%0A
+%0Adef clean_resources():%0A    shutil.rmtree(RESOURCE_TMP_WORKDIR)%0A    ensure_dir(RESOURCE_TMP_WORKDIR)%0A%0A
 class Ta
@@ -742,16 +742,269 @@
 type'%5D%0A%0A
+    @property%0A    def manifest(self):%0A        after_naily = self.data%5B'parameters'%5D%5B'puppet_manifest'%5D.split('osnailyfacter/')%5B-1%5D%0A        return os.path.join(%0A            LIBRARY_PATH, 'deployment', 'puppet', 'osnailyfacter',%0A            after_naily)%0A%0A
     @pro
@@ -1637,60 +1637,21 @@
 eld 
-os.path.join(self.src_path, self.data%5B'id'%5D + '.pp')
+self.manifest
 , os
@@ -2677,29 +2677,102 @@
 ue)%0A
-def t2r(tasks, t, p):
+@click.option('-c', is_flag=True)%0Adef t2r(tasks, t, p, c):%0A    if c:%0A        clean_resources()
 %0A   
@@ -3027,18 +3027,18 @@
 r tasks 
-is
+==
  ():%0A   

Fix path to manifest