package org.getopentest.actions.s3;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;
import org.getopentest.base.TestAction;

/**
 * Upload the contents of a file into an AWS S3 bucket.
 */
public class PutS3Object extends TestAction {

    @Override
    public void run() {
        super.run();

        String awsCredentialsProfile = this.readStringArgument("awsProfile", null);
        String accessKey = this.readStringArgument("accessKey", null);
        String secretKey = this.readStringArgument("secretKey", null);
        String bucket = this.readStringArgument("bucket");
        String objectKey = this.readStringArgument("objectKey");
        String sourceFilePath = this.readStringArgument("sourceFile");

        File sourceFile = new File(sourceFilePath);
        if (sourceFile.exists()) {
            try {
                AmazonS3 s3Client = null;

                if (awsCredentialsProfile != null) {
                    s3Client = new AmazonS3Client(
                            new ProfileCredentialsProvider(awsCredentialsProfile));
                } else if (accessKey != null && secretKey != null) {
                    s3Client = new AmazonS3Client(
                            new AWSStaticCredentialsProvider(
                                    new BasicAWSCredentials(accessKey, secretKey)));
                } else {
                    s3Client = new AmazonS3Client();
                }

                s3Client.putObject(new PutObjectRequest(bucket, objectKey, sourceFile));
            } catch (Exception ex) {
                throw new RuntimeException(String.format(
                        "Failed to upload file \"%s\" to S3 bucket \"%s\"",
                        sourceFilePath,
                        bucket), ex);
            }
        } else {
            throw new RuntimeException(String.format(
                    "Source file \"%s\" doesn't exist",
                    sourceFilePath));
        }
    }
}
