#!/usr/bin/env python

import argparse
import glob
import os
import platform
import subprocess
import sys

import lib.git as git

from lib.config import PLATFORM_KEY

SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
BOTO_DIR = os.path.join(SOURCE_ROOT, 'vendor', 'boto')

def main():
  args = parse_args()

  try:
    upload(args)
  except AssertionError as e:
    return e.message


def parse_args():
  parser = argparse.ArgumentParser(description='Upload distribution')
  parser.add_argument('-t', '--target_arch', default='x64', help='x64 or ia32')
  parser.add_argument('--upload_packaged_src', action='store_true',
                      help='Upload packaged source to s3')
  parser.add_argument('--chromium_version',
                      help='Chromium version for uploading packaged source to s3')
  return parser.parse_args()


def upload(args):
  os.chdir(SOURCE_ROOT)
  bucket, access_key, secret_key = s3_config()
  commit = git.get_head_commit(SOURCE_ROOT)

  if os.environ.has_key('MAS_BUILD'):
    platform = 'mas'
  else:
    platform = PLATFORM_KEY

  if args.upload_packaged_src:
    upload_files = ['src.tar.bz2']
    s3put(bucket, access_key, secret_key, SOURCE_ROOT,
          'libchromiumcontent/{0}/src/{1}'.format(PLATFORM_KEY, args.chromium_version),
          upload_files)
  else:
    upload_files = glob.glob('libchromiumcontent*.tar.bz2') + glob.glob('native-mksnapshot.tar.bz2')
    s3put(bucket, access_key, secret_key, SOURCE_ROOT,
          'libchromiumcontent/{0}/{1}/{2}'.format(platform, args.target_arch, commit),
          upload_files)


def s3_config():
  config = (os.environ.get('LIBCHROMIUMCONTENT_S3_BUCKET', ''),
            os.environ.get('LIBCHROMIUMCONTENT_S3_ACCESS_KEY', ''),
            os.environ.get('LIBCHROMIUMCONTENT_S3_SECRET_KEY', ''))
  message = ('Error: Please set the $LIBCHROMIUMCONTENT_S3_BUCKET, '
             '$LIBCHROMIUMCONTENT_S3_ACCESS_KEY, and '
             '$LIBCHROMIUMCONTENT_S3_SECRET_KEY environment variables')
  assert all(len(c) for c in config), message
  return config


def boto_path_dirs():
  return [
    os.path.join(BOTO_DIR, 'build', 'lib'),
    os.path.join(BOTO_DIR, 'build', 'lib.linux-x86_64-2.7')
  ]


def run_boto_script(access_key, secret_key, script_name, *args):
  env = os.environ.copy()
  env['AWS_ACCESS_KEY_ID'] = access_key
  env['AWS_SECRET_ACCESS_KEY'] = secret_key
  env['PYTHONPATH'] = os.path.pathsep.join(
      [env.get('PYTHONPATH', '')] + boto_path_dirs())

  boto = os.path.join(BOTO_DIR, 'bin', script_name)
  subprocess.check_call([sys.executable, boto] + list(args), env=env)


def s3put(bucket, access_key, secret_key, prefix, key_prefix, files):
  args = [
    '--bucket', bucket,
    '--prefix', prefix,
    '--key_prefix', key_prefix,
    '--multipart',
    '--grant', 'public-read'
  ] + files

  run_boto_script(access_key, secret_key, 's3put', *args)


if __name__ == '__main__':
  sys.exit(main())
