#!/bin/bash

# ==========================================================================
# SCRIPT: git_update_keys.sh
# DESCRIPTION: Updates a specified file in a local Git repository with new AWS IAM
#              credentials (read from a JSON file), then commits and pushes the
#              changes to the remote repository. This script is designed to be
#              used after an IAM access key rotation to update application
#              configuration files securely.
#
# USE CASE SCENARIO:
# After rotating an IAM user's access keys, an application's configuration file
# (e.g., `aws_credentials.json` or a Terraform variable file) needs to be updated
# in a Git repository (Bitbucket/GitHub) to reflect the new credentials. This
# script automates that update, commit, and push process.
#
# PREREQUISITES:
# 1.  **Git:** Git must be installed and configured on the system running this script.
# 2.  **Local Repository:** The Git repository must be cloned locally and accessible.
# 3.  **Git Credentials:** Git credentials must be configured for the remote repository
#     (e.g., via SSH keys, credential helper) to allow pushing changes.
# 4.  **New Key File:** A JSON file containing the new AWS IAM credentials (e.g., generated
#     by `iam_rotate_access_key.sh`). This file should be securely stored.
# 5.  **jq:** The `jq` command-line JSON processor must be installed (`sudo apt-get install jq` or `brew install jq`).
#
# HOW TO USE:
# 1.  **Save the script:** Save this content as `git_update_keys.sh`.
# 2.  **Make it executable:** `chmod +x git_update_keys.sh`
# 3.  **Configure variables:** Open the script and update the `--- Configuration Variables ---
#     section with your specific environment details.
# 4.  **Run from your terminal:** `./git_update_keys.sh`
#
# IMPORTANT CONSIDERATIONS:
# - **SECURITY:** The `KEY_FILE_PATH` contains sensitive information. Ensure it is
#   protected and deleted after use if not needed for other purposes.
# - This script assumes the file to update is a JSON file and will attempt to parse
#   and update specific keys (`aws_access_key_id`, `aws_secret_access_key`). Adjust
#   the `jq` commands if your file format or key names are different.
# - Ensure the local repository is clean (no uncommitted changes) before running this script
#   to avoid conflicts.
# ==========================================================================

# --- Configuration Variables (REPLACE with your actual values) ---
REPO_PATH="/path/to/your/local/git/repo" # Local path to the Git repository
FILE_TO_UPDATE="config/aws_credentials.json" # Path to the file within the repository to update
KEY_FILE_PATH="/path/to/secure/location/new_access_key.json" # Path to the JSON file with new IAM credentials
COMMIT_MESSAGE="Automated IAM key rotation update" # Git commit message
# ----------------------------------------------------------------

echo "Starting Git repository update for new IAM keys..."

# ==========================================================================
# STEP 1: Validate prerequisites and load new access keys.
# ==========================================================================
echo ">>> Step 1: Validating prerequisites and loading new access keys..."

# Check if the new key file exists
if [ ! -f "${KEY_FILE_PATH}" ]; then
    echo "Error: New key file not found at '${KEY_FILE_PATH}'. Exiting."
    exit 1
fi

# Load new access key ID and secret access key from the JSON file
NEW_ACCESS_KEY_ID=$(jq -r '.AccessKeyId' "${KEY_FILE_PATH}")
NEW_SECRET_ACCESS_KEY=$(jq -r '.SecretAccessKey' "${KEY_FILE_PATH}")

if [ -z "${NEW_ACCESS_KEY_ID}" ] || [ -z "${NEW_SECRET_ACCESS_KEY}" ]; then
    echo "Error: Could not extract AccessKeyId or SecretAccessKey from '${KEY_FILE_PATH}'. Exiting."
    exit 1
fi
echo "   Successfully loaded new Access Key ID: ${NEW_ACCESS_KEY_ID}"

# Check if the repository path exists
if [ ! -d "${REPO_PATH}" ]; then
    echo "Error: Repository path '${REPO_PATH}' does not exist. Exiting."
    exit 1
fi

# Check if the file to update exists within the repository
FULL_FILE_PATH="${REPO_PATH}/${FILE_TO_UPDATE}"
if [ ! -f "${FULL_FILE_PATH}" ]; then
    echo "Error: File to update '${FULL_FILE_PATH}' not found in repository. Exiting."
    exit 1
fi
echo "   File to update found: ${FULL_FILE_PATH}"

# ==========================================================================
# STEP 2: Update the specified file within the repository.
# This example assumes the file is a JSON file and updates specific keys.
# ==========================================================================
echo "
>>> Step 2: Updating file '${FILE_TO_UPDATE}' with new keys..."

# Use `jq` to update the JSON file. This is an in-place update.
# Adjust the key names (`.aws_access_key_id`, `.aws_secret_access_key`) if your JSON structure is different.
jq ".aws_access_key_id = \"${NEW_ACCESS_KEY_ID}\" | .aws_secret_access_key = \"${NEW_SECRET_ACCESS_KEY}\"" "${FULL_FILE_PATH}" > "${FULL_FILE_PATH}.tmp" && mv "${FULL_FILE_PATH}.tmp" "${FULL_FILE_PATH}"

if [ $? -eq 0 ]; then
    echo "   Successfully updated '${FILE_TO_UPDATE}'."
else
    echo "Error updating file '${FILE_TO_UPDATE}' using jq. Exiting."
    exit 1
fi

# ==========================================================================
# STEP 3: Commit and push changes to the remote repository.
# This requires Git to be configured with credentials to push.
# ==========================================================================
echo "
>>> Step 3: Committing and pushing changes..."

cd "${REPO_PATH}" || { echo "Error: Could not change directory to '${REPO_PATH}'. Exiting."; exit 1; }

# Add the updated file to the Git staging area
git add "${FILE_TO_UPDATE}" || { echo "Error adding file to Git. Exiting."; exit 1; }

# Commit the changes
git commit -m "${COMMIT_MESSAGE}" || { echo "Error committing changes. Exiting."; exit 1; }

# Push the changes to the remote repository
git push || { echo "Error pushing changes to remote. Ensure Git credentials are configured. Exiting."; exit 1; }

echo "   Successfully committed and pushed changes to remote repository."

echo "
=== Git repository update completed successfully. ===
"
