from __future__ import division, absolute_import, print_function

__all__ = ['copy_frameworks_main']

import os
import re
import shutil
from pathlib2 import Path
from .runner import *
from .logger import *
from .xcode import uuids_from_binary

def copy_frameworks_main():

    sym_root = Path(os.environ['SYMROOT'])
    valid_architectures = set(os.environ['VALID_ARCHS'].split(' '))
    input_file_count = int(os.environ['SCRIPT_INPUT_FILE_COUNT'])
    input_files = [Path(os.environ.get('SCRIPT_INPUT_FILE_{}'.format(index))) for index in range(0, input_file_count)]
    expanded_identity = os.environ['EXPANDED_CODE_SIGN_IDENTITY_NAME']
    built_products_dir = Path(os.environ['BUILT_PRODUCTS_DIR'])
    frameworks_folder_path = os.environ['FRAMEWORKS_FOLDER_PATH']
    frameworks_path = built_products_dir / frameworks_folder_path
    code_signing_allowed = os.environ['CODE_SIGNING_ALLOWED'] == 'YES'
    enable_bitcode = os.environ['ENABLE_BITCODE'] == 'YES'
    project_dir = Path(os.environ['PROJECT_DIR'])
    platform_display_name = os.environ['PLATFORM_DISPLAY_NAME']
    punic_builds_dir = project_dir / 'Carthage' / 'Build' / platform_display_name
    action = os.environ['ACTION']

    for input_path in input_files:

        logger.info('Processing: "{}"'.format(input_path.name))

        # We don't modify the input frameworks but rather the ones in the built products directory
        output_path = frameworks_path / input_path.name

        framework_name = input_path.stem

        logger.info('\tCopying framework "{}" to "$SYMROOT/{}"'.format(framework_name, output_path.relative_to(sym_root)))
        if output_path.exists():
            shutil.rmtree(str(output_path))
        shutil.copytree(str(input_path), str(output_path))

        framework_path = output_path

        if not code_signing_allowed:
            logger.info('\tCode signing not allowed. Skipping')
            continue

        binary_path = framework_path / framework_name

        # Find out what architectures the framework has
        output = runner.check_call(['/usr/bin/xcrun', 'lipo', '-info', binary_path])
        match = re.match(r'^Architectures in the fat file: (.+) are: (.+)'.format(binary_path), output)
        assert match.groups()[0] == str(binary_path)
        architectures = set(match.groups()[1].strip().split(' '))
        logger.info('\tArchitectures: {}'.format(list(architectures)))

        # Produce a list of architectures that are not valid
        excluded_architectures = architectures.difference(valid_architectures)

        # Skip if all architectures are valid
        if not excluded_architectures:
            continue

        # For each invalid architecture strip it from framework
        for architecture in excluded_architectures:
            logger.info('\tStripping "{}" from "{}"'.format(architecture, framework_name))
            output = runner.check_call(['/usr/bin/xcrun', 'lipo', '-remove', architecture, '-output', binary_path, binary_path])

            # Resign framework
            logger.info('\tResigning "{}"/"{}" with "{}"'.format(framework_name, architecture, expanded_identity))

        # Copy bcsymbolmap files from $PROJECT_DIRCarthage/Buil to $BUILT_PRODUCTS_DIR
        if enable_bitcode and action == 'install':
            uuids = uuids_from_binary(binary_path)
            for uuid in uuids:
                bcsymbolmap_path = punic_builds_dir / (uuid + '.bcsymbolmap')
                logger.info('\tCopying "$PROJECT_DIR/{}" to "$BUILT_PRODUCTS_DIR"'.format(bcsymbolmap_path.relative_to(project_dir)))
                shutil.copy(str(bcsymbolmap_path), str(built_products_dir))

        logger.info('\tCode signing: "$SYMROOT/{}"'.format(binary_path.relative_to(sym_root)))

        # noinspection PyUnusedLocal
        result = runner.check_call(['/usr/bin/xcrun', 'codesign', '--force', '--sign', expanded_identity, '--preserve-metadata=identifier,entitlements', binary_path])




@@ -1791,131 +1791,8 @@
 th%0A%0A
-        if not code_signing_allowed:%0A            logger.info('%5CtCode signing not allowed. Skipping')%0A            continue%0A%0A
     
@@ -1838,24 +1838,61 @@
 ework_name%0A%0A
+        if code_signing_allowed:%0A    
         # Fi
@@ -1935,16 +1935,20 @@
 ork has%0A
+    
         
@@ -2032,16 +2032,20 @@
         
+    
 match = 
@@ -2140,16 +2140,20 @@
         
+ 
+   
 assert m
@@ -2181,32 +2181,36 @@
 tr(binary_path)%0A
+    
         architec
@@ -2259,32 +2259,36 @@
 t(' '))%0A        
+   
+ 
 logger.info('%5CtA
@@ -2331,24 +2331,28 @@
 ectures)))%0A%0A
+    
         # Pr
@@ -2408,16 +2408,20 @@
         
+    
 excluded
@@ -2492,16 +2492,20 @@
         
+ 
+   
 # Skip i
@@ -2542,16 +2542,20 @@
         
+    
 if not e
@@ -2589,16 +2589,20 @@
         
+   
+ 
 continue
@@ -2603,16 +2603,20 @@
 ntinue%0A%0A
+    
         
@@ -2675,24 +2675,28 @@
 ork%0A        
+    
 for architec
@@ -2731,32 +2731,36 @@
 es:%0A            
+ 
+   
 logger.info('%5CtS
@@ -2822,16 +2822,20 @@
 _name))%0A
+    
         
@@ -2968,16 +2968,20 @@
         
+   
+ 
 # Resign
@@ -2983,32 +2983,36 @@
 esign framework%0A
+    
             logg
@@ -3107,24 +3107,433 @@
 identity))%0A%0A
+            logger.info('%5CtCode signing: %22$SYMROOT/%7B%7D%22'.format(binary_path.relative_to(sym_root)))%0A%0A            # noinspection PyUnusedLocal%0A            result = runner.check_call(%5B'/usr/bin/xcrun', 'codesign', '--force', '--sign', expanded_identity,%0A                '--preserve-metadata=identifier,entitlements', binary_path%5D)%0A        else:%0A            logger.info('%5CtCode signing not allowed. Skipping.')%0A%0A%0A
         # Co
@@ -4033,307 +4033,5 @@
 ))%0A%0A
-        logger.info('%5CtCode signing: %22$SYMROOT/%7B%7D%22'.format(binary_path.relative_to(sym_root)))%0A%0A        # noinspection PyUnusedLocal%0A        result = runner.check_call(%5B'/usr/bin/xcrun', 'codesign', '--force', '--sign', expanded_identity, '--preserve-metadata=identifier,entitlements', binary_path%5D)%0A%0A%0A
 %0A

Make it so that if signing is disabled bitcode files are still copied.