#!/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

# リポジトリ名のペアの配列（ステージングと本番）
repositories=(
    "mbj-newdwh2021-staging-ecr mbj-newdwh2021-product-ecr"
    "mbj-newdwh2021-staging-sap-data-decrypt mbj-newdwh2021-product-sap-data-decrypt"
    "mbj-newdwh2021-staging-check-view-security-option-ecr mbj-newdwh2021-product-check-view-security-option-ecr"
    "mbj-newdwh2021-staging-crm-datafetch-ecr mbj-newdwh2021-product-crm-datafetch-ecr"
    "mbj-newdwh2021-staging-jskult-dbdump-ecr mbj-newdwh2021-product-jskult-dbdump-ecr"
    "mbj-newdwh2021-staging-jskult-batch-daily-ecr mbj-newdwh2021-product-jskult-batch-daily-ecr"
    "mbj-newdwh2021-staging-jskult-batch-laundering-ecr mbj-newdwh2021-product-jskult-batch-laundering-ecr"
    "mbj-newdwh2021-staging-jskult-webapp-ecr mbj-newdwh2021-product-jskult-webapp-ecr"
    "mbj-newdwh2021-staging-export-dbdump-ecr mbj-newdwh2021-product-export-dbdump-ecr"
    "mbj-newdwh2021-staging-transfer-medpass-data-ecr mbj-newdwh2021-product-transfer-medpass-data-ecr"
    "mbj-newdwh2021-staging-jskult-transfer-receive-file-ecr mbj-newdwh2021-product-jskult-transfer-receive-file-ecr"
)

# 各ペアのリポジトリをループ
for repo_pair in "${repositories[@]}"; do
    # ステージングと本番のリポジトリ名を分割
    staging_repo=$(echo $repo_pair | awk '{print $1}')
    product_repo=$(echo $repo_pair | awk '{print $2}')

    # ステージングのダイジェストを取得
    staging_digest=$(aws ecr describe-images --repository-name "$staging_repo" --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text 2>/dev/null)

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

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

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