#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
from shutil import copyfile, copy
from pkg_resources import Requirement, resource_filename
from glob import glob

FOLDERS = [
    'rctl_shelf/counters/',
    'rctl_recipes/',
    'korg_patterns/',
    'plot_app/',
    'config/',
    'testruns/',
    'reports/'
]

CARS_FOLDERS = [
    'scenarios/supercars/'
]

FILES = [
    ('aogaeru', 'rctl_shelf/counters/*'),
    ('aogaeru', 'rctl_recipes/*'),
    ('aogaeru', 'korg_patterns/*'),
    ('plot',    'plot_app/*'),
    ('plot',    'plot_app/lib/*'),
    ('plot',    'plot_app/css/*'),
    ('plot',    'plot_app/img/*')
]

CARS_FILES = [
    ('aogaeru', 'README.md'),
    ('aogaeru', 'config/*'),
    ('aogaeru', 'scenarios/supercars/*')
]


def init_folders(folders):
    """Create the specified folders in the current directory."""
    for f in folders:
        if not os.path.exists(f):
            os.makedirs(f)


def init_files(files):
    """Create the specified folders in the current directory."""
    for p in files:
        dest = os.path.dirname(p[1])
        for f in glob(resource_filename(Requirement.parse(p[0]), p[1])):
            if os.path.isfile(f):
                if not os.path.exists(dest):  # create destination folder
                    os.makedirs(dest)
                copy(f, dest)
                print 'fn: %s to: %s' % (f, dest)


def usage():
    """Print the script's usage guide."""
    print 'Usage: aogaeru init [cars]'
    print "init = initialize the current folder with the aogaeru seed"
    print "cars = if you want the supercars demo scenarios and configuration"


if __name__ == '__main__':
    try:
        if len(sys.argv) == 2 and sys.argv[1] == 'init':
            init_folders(FOLDERS)
            init_files(FILES)
        elif len(sys.argv) == 3 and sys.argv[1] == 'init' and sys.argv[2] == 'cars':
            init_folders(FOLDERS)
            init_files(FILES)
            init_folders(CARS_FOLDERS)
            init_files(CARS_FILES)
        else:
            usage()
    except Exception as e:
        print 'Exception: %s' % e
