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

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

# 各ステージングリポジトリをループ
for staging_repo in "${staging_repositories[@]}"; do

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

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

    # 両方のダイジェストが正常に取得されたかチェック
    if [[ -z "$latest_digest" || -z "$scan_point_digest" ]]; then
        echo "Failed to retrieve digest for 'latest' or 'scan-point' tag in $staging_repo."
        continue
    fi

    # ダイジェストを比較
    if [[ "$latest_digest" == "$scan_point_digest" ]]; then
        echo "✅ Digests match for 'latest' and 'scan-point' tags in $staging_repo."
        echo "    Latest Tag Digest: $latest_digest"
        echo "    Scan-Point Tag Digest: $scan_point_digest"
    else
        echo "❌ Digests do not match for 'latest' and 'scan-point' tags in $staging_repo."
        echo "    Latest Tag Digest: $latest_digest"
        echo "    Scan-Point Tag Digest: $scan_point_digest"
    fi
done
