#!/usr/bin/env python
# coding=utf-8
# Pake: Pythonic Make
# Copyright 2010 MyFreeWeb
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os, sys, re
import yaml
import pakeapi

def make(file, target):
    fstr = file.read().replace('\n', '\n\n')
    # Multi-target support
    for a in xrange(fstr.count('target:')):
        b = re.findall('target*: (\w+)', fstr)[0]
        fstr = fstr.replace('target: ' + b, 'target%s: %s' % (a, b))
        
#    print fstr
    main = yaml.load(fstr)
    
    variables = {} # Overrides from cmdline
    try:
        if deft: n = 1 # If 1st arg was entered by user, var overrides are from 2nd
        else: n = 0 # Else - from 1st
        for arg in sys.argv[n:]:
            a = arg.split('=')
            variables[a[0]] = a[1]
    except: pass # no overrides if not specified
    
    obj = pakeapi.Paker(main, variables)
    obj.run_target(target)

if __name__ == '__main__':
    try:
        if not re.match('\w+=\w+', sys.argv[1]): # If 1st arg is not variable
            target = sys.argv[1] # It is target
            deft = False # So it was entered by user
        else: raise KeyError
    except: # And if there's no vars or/and no target
        target = 'default' # We use default
        deft = True # And it is not entered by user
        
    make(open('Pakefile', 'r'), target)
