#!/bin/bash

# ==========================================================================
# SCRIPT: s3_upload_file.sh
# DESCRIPTION: Uploads a local file to a specified Amazon S3 bucket using AWS CLI.
#              This script is useful for automating the transfer of files
#              from a local machine or a server to S3 storage.
#
# USE CASE SCENARIO:
# A data pipeline generates daily reports locally, and these reports need
# to be uploaded to an S3 bucket for archival and further processing.
# This script can be integrated into a cron job or a larger workflow to
# automate the upload process.
#
# PREREQUISITES:
# 1.  **AWS CLI:** The AWS Command Line Interface must be installed and configured
#     with credentials that have the necessary permissions.
# 2.  **IAM Permissions:** The principal executing this script must have:
#     - `s3:PutObject` on the target S3 bucket.
# 3.  **Existing Resources:**
#     - A target S3 bucket where the file will be uploaded.
#     - A local file to be uploaded.
#
# HOW TO USE:
# 1.  **Save the script:** Save this content as `s3_upload_file.sh`.
# 2.  **Make it executable:** `chmod +x s3_upload_file.sh`
# 3.  **Configure variables:** Open the script and update the `--- Configuration Variables ---`
#     section with your specific environment details.
# 4.  **Prepare your local file:** Ensure the file you want to upload exists.
# 5.  **Run from your terminal:** `./s3_upload_file.sh`
#
# IMPORTANT CONSIDERATIONS:
# - For very large files, `aws s3 cp` automatically handles multipart uploads.
# - Ensure proper error handling and retry mechanisms for production-grade scripts.
# ==========================================================================

# --- Configuration Variables (REPLACE with your actual values) ---
BUCKET_NAME="my-target-s3-bucket"      # Name of the S3 bucket to upload the file to (e.g., "my-data-archive")
LOCAL_FILE_PATH="/path/to/your/local/file.txt" # Path to the local file to upload (e.g., "./documents/report.pdf")
S3_KEY=""                         # Optional. S3 key (path) for the uploaded file.
                                     # If empty, the basename of the local file will be used as the S3 key.
AWS_REGION="us-east-1"                 # AWS region of the S3 bucket
# ----------------------------------------------------------------

echo "Starting S3 file upload process in region ${AWS_REGION}...\n"

# ==========================================================================
# STEP 1: Validate the existence of the local file.
# The script cannot proceed if the source file does not exist.
# ==========================================================================
echo ">>> Step 1: Checking for local file: '${LOCAL_FILE_PATH}'...\n"
if [ ! -f "${LOCAL_FILE_PATH}" ]; then
    echo "Error: Local file not found at '${LOCAL_FILE_PATH}'. Please ensure the file exists. Exiting.\n"
    exit 1
fi
echo "   Local file '${LOCAL_FILE_PATH}' found.\n"

# ==========================================================================
# STEP 2: Determine the S3 key (destination path) for the uploaded file.
# If not provided in S3_KEY, use the basename of the local file.
# ==========================================================================
if [ -z "${S3_KEY}" ]; then
    S3_KEY=$(basename "${LOCAL_FILE_PATH}")
    echo "   S3 key not provided. Using local filename as S3 key: '${S3_KEY}'.\n"
else
    echo "   Using provided S3 key: '${S3_KEY}'.\n"
fi

echo ">>> Step 3: Uploading '${LOCAL_FILE_PATH}' to s3://${BUCKET_NAME}/${S3_KEY}...\n"

# ==========================================================================
# STEP 3: Perform the file upload to S3 using `aws s3 cp`.
# `aws s3 cp` handles multipart uploads for large files automatically.
# ==========================================================================
aws s3 cp "${LOCAL_FILE_PATH}" "s3://${BUCKET_NAME}/${S3_KEY}" --region "${AWS_REGION}" || { echo "Error: aws s3 cp command failed. Exiting.\n"; exit 1; }

# Check the exit code of the last command.
if [ $? -eq 0 ]; then
    echo "Successfully uploaded '${LOCAL_FILE_PATH}' to s3://${BUCKET_NAME}/${S3_KEY}.\n"
else
    echo "Error: Failed to upload file to S3. Please check the logs above for details.\n"
    exit 1
fi

echo "=== S3 file upload completed successfully. ===\n"
