import boto3
import json
import traceback
from botocore.client import Config

def handler(event, _context):
  code_pipeline = boto3.client("codepipeline")
  job_id = event["CodePipeline.job"]["id"]
  try:
    result = deploy(event)
    code_pipeline.put_job_success_result(jobId=job_id)
    return result
  except:
    traceback.print_exc()
    code_pipeline.put_job_failure_result(jobId=job_id)
    raise


def deploy(event):
  src_account = event["CodePipeline.job"]["accountId"]

  data = event["CodePipeline.job"]["data"]
  params = json.loads(data["actionConfiguration"]["configuration"]["UserParameters"])

  src_region = params["src_region"]
  dst_region = params["dst_region"]
  artifact = params["artifact"]
  dst_account = params["dst_account"]

  s3_location = data["inputArtifacts"][0]["location"]["s3Location"]
  s3_bucket = s3_location["bucketName"]
  s3_key = s3_location["objectKey"]
  target = s3_bucket.replace(src_region, dst_region)

  if dst_account:
    target = target.replace(src_account, dst_account)

  s3 = boto3.client("s3", region_name=dst_region, config=Config(signature_version="s3v4"))
  src = "%s/%s" % (s3_bucket, s3_key)
  s3.copy_object(Bucket=target, Key=artifact, CopySource=src, MetadataDirective="COPY", ACL="bucket-owner-full-control")

  return "Succeed"
