#!/usr/bin/env python
import os
import sys
import pickle
import logging.config

import yaml
import kajiki

def main():
    with open('deployme.yml', 'rb') as fp:
        config = yaml.load(fp)
    with open(sys.argv[1]) as fp:
        context = pickle.load(fp)
    loader = kajiki.FileLoader(
        base=os.getcwd(),
        reload=False,
        force_mode='text',
        autoescape_text=False)
    for tpl in config['templates']:
        deploy_template(loader, context, **tpl)
    for command in config['run']:
        os.system(command)

def deploy_template(loader, context, template, target, mode):
    print 'Deploy %s to %s with mode 0%o' % (template, target, mode)
    Template = loader.import_(template)
    with open(target, 'wb') as fp:
        for part in Template(context):
            fp.write(part)


if __name__ == '__main__':
    main()
