#!/bin/bash

# AWSがログインしているかどうかをチェックする関数
function check_aws_login() {
    if ! aws sts get-caller-identity &>/dev/null; then
        echo "❌ AWS credentials are not configured or are incorrect. Exiting."
        exit 1
    fi
}

# ログインチェックを実行
check_aws_login

# プロダクションECRとLambda名のペアの配列
resources=(
    "mbj-newdwh2021-product-sap-data-decrypt mbj-newdwh2021-product-lambda-sap-data-decrypt"
    "mbj-newdwh2021-product-check-view-security-option-ecr mbj-newdwh2021-product-lambda-check-view-security-option"
    "mbj-newdwh2021-product-transfer-medpass-data-ecr mbj-newdwh2021-product-lambda-transfer-medpass-data"
)

# 各リソースをループ
for resource_set in "${resources[@]}"; do
    # 本番環境のECRとLambda関数名を分割
    product_repo=$(echo $resource_set | awk '{print $1}')
    lambda_function=$(echo $resource_set | awk '{print $2}')

    # 本番環境のlatestタグのダイジェストを取得
    product_digest=$(aws ecr describe-images --repository-name "$product_repo" --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text 2>/dev/null)

    # Lambda関数のダイジェストを取得
    lambda_digest=$(aws lambda get-function --function-name "$lambda_function" --query 'Code.ImageUri' --output text 2>/dev/null | sed 's/.*@//')

    # 両方のダイジェストが正常に取得されたかチェック
    if [[ -z "$product_digest" || -z "$lambda_digest" ]]; then
        echo "Failed to retrieve digest for $product_repo or $lambda_function."
        continue
    fi

    # ダイジェストを比較
    if [[ "$product_digest" == "$lambda_digest" ]]; then
        echo "✅ Digests match for product ECR and Lambda in $product_repo."
        echo "    Product Digest: $product_digest"
        echo "    Lambda Digest: $lambda_digest"
    else
        echo "❌ Digests do not match for $product_repo and $lambda_function."
        echo "    Product Digest: $product_digest"
        echo "    Lambda Digest: $lambda_digest"
    fi
done
