#!/usr/bin/env python
import argparse
import os
import sys
import cbc
import conda_build.metadata


#os.environ['CBC_HOME'] = os.path.abspath(os.path.join(os.path.dirname(cbc.__file__), 'tests/data/build'))
#sys.argv.append('--force-rebuild')
#sys.argv.append('tests/data/aprio.ini')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--force-rebuild', 
                        action='store_true', 
                        help='Do not stop if package already installed')
    parser.add_argument('--no-build', 
                        action='store_true',
                        help='Generate metadata from cbc configuration (useful for manual building)')
    parser.add_argument('cbcfile',
                        nargs='+', 
                        help='CBC metadata')
    args = parser.parse_args()
    
    # Initialize internal environment
    env = cbc.environment.Environment()
    
    # Convert cbcfile paths to absolute paths
    args.cbcfile = [ os.path.abspath(x) for x in args.cbcfile ]
    
    # Verify we have a file that exists
    for cbcfile in args.cbcfile:
        if not os.path.exists(cbcfile):
            print('{} does not exist.'.format(cbcfile))
            exit(1)
        elif not os.path.isfile(cbcfile):
            print('{} is not a file.'.format(cbcfile))
            exit(1)
    
    print('CBC_HOME is {0}'.format(env.cbchome))
    # Perform build(s)
    for cbcfile in args.cbcfile:
        print('Using cbc build configuration: {0}'.format(cbcfile))
        # Ensure the working directory remains the same throughout.
        os.chdir(env.pwd)
        
        metadata = cbc.meta.MetaData(cbcfile, env)
        metadata.env.mkpkgdir(metadata.local['package']['name'])
        metadata.render_scripts()
        metadata.copy_patches()

        print('Scripts written to {0}'.format(metadata.env.pkgdir))
        
        if args.no_build:
            continue
        
        print('Generating Conda metadata...')
        conda_metadata = conda_build.metadata.MetaData(env.pkgdir)
        
        if not args.force_rebuild:
            if cbc.utils.conda_search(conda_metadata.name()) == conda_metadata.dist():
                print('{0} metadata matches an installed package; increment the build number to rebuild or use --force-rebuild.'.format(conda_metadata.dist()))
                continue
        
        conda_builder_args = {'get_src': True, 'verbose': False}
        try:
            print('Initializing Conda build...')
            built = cbc.utils.conda_builder(metadata, conda_builder_args)
            if not built:
                print('Failure occurred building: {0}'.format(conda_metadata.dist()))
                continue
        except cbc.exceptions.CondaBuildError as cbe:
            print(cbe)
            continue
        
        print('Installing Conda package...')
        package_exists = cbc.utils.conda_search(conda_metadata.name())

        if not package_exists:
            cbc.utils.conda_install(conda_metadata.name())
        elif package_exists:
            if args.force_rebuild:
                cbc.utils.conda_reinstall(conda_metadata.name())
        
        print('')

@@ -305,16 +305,55 @@
 ain__':%0A
+    no_upload = ''%0A    use_local = ''%0A%0A
     pars
@@ -421,25 +421,24 @@
 ce-rebuild',
- 
 %0A           
@@ -470,17 +470,16 @@
 e_true',
- 
 %0A       
@@ -581,17 +581,16 @@
 -build',
- 
 %0A       
@@ -729,16 +729,352 @@
 ding)')%0A
+    parser.add_argument('--no-upload',%0A                        action='store_true',%0A                        help='Do not upload to anaconda.org (aka. binstar)')%0A    parser.add_argument('--use-local',%0A                        action='store_true',%0A                        help='Install built package from %5B...%5D/conda-bld/pkgs repository')%0A
     pars
@@ -1134,17 +1134,16 @@
 rgs='+',
- 
 %0A       
@@ -1211,20 +1211,16 @@
 _args()%0A
-    
 %0A    # I
@@ -1229,16 +1229,20 @@
 tialize 
+cbc 
 internal
@@ -1294,20 +1294,16 @@
 nment()%0A
-    
 %0A    # C
@@ -1405,20 +1405,16 @@
 cfile %5D%0A
-    
 %0A    # V
@@ -1712,20 +1712,140 @@
 exit(1)%0A
+%0A
     
+if args.no_upload:%0A        no_upload = '--no-binstar-upload'%0A%0A    if args.use_local:%0A        use_local = '--use-local'%0A
 %0A    pri
@@ -2104,24 +2104,16 @@
 nv.pwd)%0A
-        
 %0A       
@@ -2356,24 +2356,16 @@
 kgdir))%0A
-        
 %0A       
@@ -2400,32 +2400,24 @@
    continue%0A
-        
 %0A        pri
@@ -2518,24 +2518,16 @@
 pkgdir)%0A
-        
 %0A       
@@ -2606,23 +2606,16 @@
 metadata
-.name()
 ) == con
@@ -2660,25 +2660,16 @@
 int('%7B0%7D
- metadata
  matches
@@ -2806,32 +2806,24 @@
    continue%0A
-        
 %0A        con
@@ -2844,43 +2844,30 @@
 s = 
-%7B'get_src': True, 'verbose': False%7D
+%5Bno_upload, use_local%5D
 %0A   
@@ -3234,24 +3234,16 @@
 ontinue%0A
-        
 %0A       
@@ -3342,23 +3342,16 @@
 metadata
-.name()
 )%0A%0A     
@@ -3564,24 +3564,16 @@
 name())%0A
-        
 %0A       

Add arguments: --no-upload, --use-local