#!/bin/bash
# ===============================================================================================================
# aws-oidc-setup.sh - Configura credenciales AWS via OIDC para Bitbucket Pipelines
# Descripcion:
#       Obtiene credenciales temporales de AWS explicitamente mediante
#       assume-role-with-web-identity y exporta las variables necesarias
#       para que Terraform (incluyendo su backend S3) y AWS CLI funcionen.
#
# Uso:
#       source scripts/aws-oidc-setup.sh <dev|prod>
#
# Requiere:
#       - El step de bitbucket-pipelines.yml debe tener "oidc: true"
#       - python3 disponible para parsear JSON
# ===============================================================================================================

set -euo pipefail

if ! command -v aws &> /dev/null; then
    echo "AWS CLI no encontrado. Instalando AWS CLI v2..."
    curl -s "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
    unzip -q awscliv2.zip
    ./aws/install --update
    rm -rf awscliv2.zip aws
    aws --version
fi

ENV="${1:-dev}"

if [[ -z "${BITBUCKET_STEP_OIDC_TOKEN:-}" ]]; then
  echo "ERROR: BITBUCKET_STEP_OIDC_TOKEN no esta definido."
  echo "Asegurate de agregar 'oidc: true' al step en bitbucket-pipelines.yml"
  exit 1
fi

# Escribir el token a un archivo temporal seguro para evitar que el decoder
# de Python trate el JWT crudo como un nombre de archivo (OSError 36).
TOKEN_FILE="$(mktemp)"
trap 'rm -f "${TOKEN_FILE}"' EXIT

printf '%s' "${BITBUCKET_STEP_OIDC_TOKEN}" > "${TOKEN_FILE}"
export AWS_WEB_IDENTITY_TOKEN_FILE="${TOKEN_FILE}"

if [[ "$ENV" == "prod" ]]; then
  export AWS_ROLE_ARN="arn:aws:iam::523761210517:role/BitbucketProyectosaccCICDRoleProd"
else
  export AWS_ROLE_ARN="arn:aws:iam::668889063715:role/BitbucketProyectosaccCICDRoleDev"
fi

SESSION_NAME="bitbucket-pipelines-proyectosacc-${ENV:-dev}-${BITBUCKET_BUILD_NUMBER:-unknown}"
export AWS_DEFAULT_REGION="mx-central-1"

echo "=== AWS OIDC Setup ==="
echo "Ambiente      : $ENV"
echo "Role ARN      : $AWS_ROLE_ARN"
echo "Region        : $AWS_DEFAULT_REGION"
echo "Session Name  : $SESSION_NAME"
echo "Token file    : $AWS_WEB_IDENTITY_TOKEN_FILE"
echo "Obteniendo credenciales temporales via STS..."

echo "=== Decoding OIDC Token ==="
# Leer el token desde stdin para nunca pasar el contenido como argumento o filename.
python3 -c "
import json, base64, sys
t = sys.stdin.read().strip()
payload = t.split('.')[1]
padding = 4 - len(payload) % 4
if padding != 4: payload += '=' * padding
decoded = json.loads(base64.b64decode(payload))
print(json.dumps(decoded, indent=2))
print('aud claim :', decoded.get('aud', 'N/A'))
" < "${TOKEN_FILE}"
echo "==========================="

CREDS=$(aws sts assume-role-with-web-identity \
  --role-arn "$AWS_ROLE_ARN" \
  --role-session-name "$SESSION_NAME" \
  --web-identity-token "file://${AWS_WEB_IDENTITY_TOKEN_FILE}" \
  --duration-seconds 3600 \
  --output json)

export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | python3 -c "import sys,json; print(json.load(sys.stdin)['Credentials']['AccessKeyId'])")
export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | python3 -c "import sys,json; print(json.load(sys.stdin)['Credentials']['SecretAccessKey'])")
export AWS_SESSION_TOKEN=$(echo "$CREDS" | python3 -c "import sys,json; print(json.load(sys.stdin)['Credentials']['SessionToken'])")

# Terraform S3 backend requiere estas variables explicitas
export AWS_REGION="${AWS_DEFAULT_REGION}"

echo "Credenciales obtenidas exitosamente."
echo "AWS_ACCESS_KEY_ID     : ${AWS_ACCESS_KEY_ID:0:8}..."
echo "AWS_SESSION_TOKEN     : ${AWS_SESSION_TOKEN:0:8}..."
echo "======================"
