#! /usr/bin/env python
from __future__ import division

# standard library
import os
import zipfile

def main():
  """
  Create the .zip file for deployment to AWS Lambda
  """
  current_dir = os.path.dirname(os.path.realpath(__file__))
  dependencies = os.path.join(current_dir, 'dependencies')
  zip_path = os.path.join(current_dir, '_deploy', 'cling_deploy_package_for_lambda.zip')

  try:
    # try to put the zip file in a _deploy directory
    os.makedirs(os.path.dirname(zip_path))
  except Exception as err:
    # if not, put it in the current directory
    zip_path = os.path.join(current_dir, 'cling_deploy_package_for_lambda.zip')
  
  try:
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zfh:
      print "Creating zip file for deployment to AWS Lambda"

      # get the 3rd party dependencies first
      for root, dirs, files in os.walk(dependencies):
        for fn in files:
          if fn.endswith('.pyc') or fn in [ '.DS_Store' ]: continue
          
          current_path = os.path.abspath(os.path.join(root, fn))
          archive_path = current_path.replace(dependencies, '')
          zfh.write(current_path, archive_path)
          print "  + Added to archive: {}".format(archive_path)

      # get the project files
      for fn in os.listdir(current_dir):
        if fn.endswith('.py') or fn.endswith('.toml'):
          if fn in [ '.DS_Store', 'package_for_lambda.py' ]: continue

          current_path = os.path.join(current_dir, fn)
          archive_path = fn
          zfh.write(current_path, archive_path)
          print "  + Added to archive: {}".format(archive_path)
  except Exception as err:
    print "Could not create zip file. Threw exception: {}".format(err)

  file_size_in_mb = os.path.getsize(zip_path) / 1024 / 1024
  print "==================================================="
  print "Created {} Mb archive {}".format(file_size_in_mb, zip_path)
  print ""

if __name__ == '__main__': main()