#!/bin/bash

# A script to create an S3-triggered Lambda function for generating thumbnails.

# --- Configuration ---
REGION="us-east-1"
RANDOM_SUFFIX=$(head /dev/urandom | tr -dc a-z0-9 | head -c 8)
SOURCE_BUCKET="my-source-images-${RANDOM_SUFFIX}"
DEST_BUCKET="my-destination-thumbnails-${RANDOM_SUFFIX}"
LAMBDA_FUNCTION_NAME="S3ThumbnailGenerator"
IAM_ROLE_NAME="LambdaS3ThumbnailRole"
POLICY_NAME="LambdaS3ThumbnailPolicy"
LAMBDA_CODE_FILE="thumbnail_generator.py"
ZIP_FILE="function.zip"

# --- 1. Create IAM Role and Policy ---
echo "Creating IAM Role and Policy..."

# Trust policy for Lambda
TRUST_POLICY_JSON=$(cat <<-EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
)

# Create the role
ROLE_ARN=$(aws iam create-role \
  --role-name $IAM_ROLE_NAME \
  --assume-role-policy-document "$TRUST_POLICY_JSON" \
  --query 'Role.Arn' --output text)

echo "IAM Role created with ARN: $ROLE_ARN"

# Permissions policy for Lambda to access S3 and CloudWatch Logs
POLICY_JSON=$(cat <<-EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::$SOURCE_BUCKET/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::$DEST_BUCKET/*"
        }
    ]
}
EOF
)

# Create and attach the policy
POLICY_ARN=$(aws iam create-policy \
    --policy-name $POLICY_NAME \
    --policy-document "$POLICY_JSON" \
    --query 'Policy.Arn' --output text)
aws iam attach-role-policy --role-name $IAM_ROLE_NAME --policy-arn $POLICY_ARN

echo "IAM Policy created and attached to the role."
# It can take a few moments for the IAM role to be usable.
echo "Waiting for IAM role to propagate..."
sleep 10

# --- 2. Create S3 Buckets ---
echo "Creating S3 buckets..."
aws s3api create-bucket --bucket $SOURCE_BUCKET --region $REGION
aws s3api create-bucket --bucket $DEST_BUCKET --region $REGION
echo "Source bucket: $SOURCE_BUCKET"
echo "Destination bucket: $DEST_BUCKET"

# --- 3. Package and Create Lambda Function ---
echo "Packaging and creating Lambda function..."
zip $ZIP_FILE $LAMBDA_CODE_FILE

aws lambda create-function \
  --function-name $LAMBDA_FUNCTION_NAME \
  --runtime python3.9 \
  --zip-file fileb://$ZIP_FILE \
  --handler thumbnail_generator.lambda_handler \
  --role $ROLE_ARN \
  --timeout 30 \
  --memory-size 256 \
  --environment "Variables={DESTINATION_BUCKET=$DEST_BUCKET}"

# Clean up local zip file
rm $ZIP_FILE

# --- 4. Configure S3 Trigger ---
echo "Configuring S3 trigger..."
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
LAMBDA_ARN="arn:aws:lambda:$REGION:$ACCOUNT_ID:function:$LAMBDA_FUNCTION_NAME"

# Add permission for S3 to invoke the Lambda function
aws lambda add-permission \
  --function-name $LAMBDA_FUNCTION_NAME \
  --statement-id "S3InvokePermission" \
  --action "lambda:InvokeFunction" \
  --principal s3.amazonaws.com \
  --source-arn "arn:aws:s3:::$SOURCE_BUCKET"

# Create the notification configuration
NOTIFICATION_JSON=$(cat <<-EOF
{
  "LambdaFunctionConfigurations": [
    {
      "LambdaFunctionArn": "$LAMBDA_ARN",
      "Events": ["s3:ObjectCreated:*"],
      "Filter": {
        "Key": {
          "FilterRules": [
            {"Name": "suffix", "Value": ".jpg"},
            {"Name": "suffix", "Value": ".png"}
          ]
        }
      }
    }
  ]
}
EOF
)

aws s3api put-bucket-notification-configuration \
  --bucket $SOURCE_BUCKET \
  --notification-configuration "$NOTIFICATION_JSON"

echo "--- S3-triggered Lambda setup complete! ---"
echo "Upload a .jpg or .png file to the '$SOURCE_BUCKET' bucket to trigger the function."
echo "Check the '$DEST_BUCKET' bucket for the generated thumbnail."
