#! python3
# -*- coding: utf-8 -*-
# ┌─────────────────────────────────────────────────────┐
# │ jsBuild 0.1 - A fiddler replacement in python       │
# ├─────────────────────────────────────────────────────┤
# │ Copyright (c) 2013 Amadeusguo                       │
# │ http://amadeus.herokuapp.com/                       │
# │ Licensed under the MIT license.                     │
# └─────────────────────────────────────────────────────┘

# Features:
# 1. build js ts css less jade
# 2. auto fix version number
# 3. play well with blackhole, zero configuration 
# 4. r.js dependency resolve
# 5. make inlines easy

# build.py: dev build
# build.py -p dist: make a release build
# build.py js/require.js css/reset.css: build a individual files

###############################################

import os
import sys
import argparse
import configparser
import shutil

from meteor.pipeline import Pipeline


help_msg = '''
PyTool to build a js project'

Usage:
    build.py: build all
    build.py js/a.js: build a single file

arguments:
    --profile
'''

CONFIG_FILE = 'meteor.cfg'

def config(parser):
    parser.set_defaults(func=action)
    parser.add_argument('files', metavar='file', type=str, nargs='*',
                       help='list of files to be processed')
    parser.add_argument('-p', '--profile', default='dev', help='build profile')

def action(args):
    # parse commandline arguments
    config = configparser.ConfigParser()
    config.read(CONFIG_FILE)

    # setup pipeline
    pipeline = Pipeline(args.profile, config)
    src_dir = pipeline.src_dir
    dest_dir = pipeline.dest_dir

    # empty build dir first
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)

    if args.files:
        for fname in args.files:
            # process files from commandline
            pipeline.add(fname)
    else:
        # process all files
        for root, dirs, files in os.walk(src_dir, topdown=True):
            for fname in files:
                if root == src_dir and fname == CONFIG_FILE:
                    # omit CONFIG_FILE in pipeline
                    continue
                pipeline.add(os.path.relpath(os.path.join(root, fname), src_dir))

        # process concat files
        for fname in config['concat']:
            pipeline.add(fname)

    pipeline.run()
