from __future__ import print_function

import json
import urllib
import boto3
import jenkins
import os

print('Loading lambda function')
s3 = boto3.client('s3')
# TODO: private IP of the EC2 instance where Jenkins is deployed, public IP won't work
jenkins_url = 'http://123.45.56.78:8080/'

# TODO: these environment variables should be encrypted in Lambda
username = os.environ['username']
password = os.environ['password']

def lambda_handler(event, context):
    
    # Get the S3 object and its filename from the S3 event 
    bucket = event['Records'][0]['s3']['bucket']['name']
    filename = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
    try:
        # Connect to Jenkins and build a job 
        server = jenkins.Jenkins(jenkins_url, username=username, password=password)
        server.build_job('Pipeline/Digiteum_File_Transfer', {'filename': filename})
        return 'Job Digiteum File Transfer started on Jenkins'
    except Exception as e:
        print(e)
        print('Cannot connect to Jenkins server or run build job')
        raise e

