#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -uo pipefail

#############################################################################################################
# Start of the script
#############################################################################################################

# Source the common methods
source ./common_windows.sh
# Get the regional endpoint variable
image_endpoint=$(get_regional_image_endpoint "${AWS_REGION}")

# Declare constants
export DOCKER_CLI_EXPERIMENTAL=enabled
declare -A os_releases=( ["windows2019"]="ltsc2019" ["windows2022"]="ltsc2022")

#############################################################################################################
# Login into regional ECR of the region where we want to push the manifest.
# We also generate the Repository path here specific to regional ECR.
#############################################################################################################
if [[ $REGISTRY_TO_PUSH == "private-ecr" ]]; then
  # Create Repository path specific for private ECR.
  REGISTRY="${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.${image_endpoint}"
  REPOSITORY_PATH="${REGISTRY}/${REPOSITORY}"

  # Login into ECR of the region.
  aws ecr get-login-password --region ${AWS_REGION}| docker login --username AWS --password-stdin ${REGISTRY}

#############################################################################################################
# Login into public ECR of the account where we want to push the manifest.
# In order to do so, we assume a cross-account IAM role.
# We also generate the Repository path here specific to public ECR.
#############################################################################################################
elif [[ $REGISTRY_TO_PUSH == "public-ecr" ]]; then
  # Create Repository path specific for public ECR.
  REGISTRY="public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}"
  REPOSITORY_PATH="${REGISTRY}/${REPOSITORY}"

  # Assume the publish role for public ecr.
  CREDS=`aws sts assume-role --role-arn ${PUBLISH_ROLE_ARN_PUBLIC_ECR} --role-session-name publicECR`
  export AWS_ACCESS_KEY_ID=`echo $CREDS | jq -r .Credentials.AccessKeyId`
  export AWS_SECRET_ACCESS_KEY=`echo $CREDS | jq -r .Credentials.SecretAccessKey`
  export AWS_SESSION_TOKEN=`echo $CREDS | jq -r .Credentials.SessionToken`

  # Login into public ECR
  aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${REGISTRY}

#############################################################################################################
# Login into dockerhub account where we want to push the manifest.
# In order to do so, we get the credentials stored in Secrets Manager.
# We also generate the Repository path here specific to dockerhub.
#############################################################################################################
elif [[ $REGISTRY_TO_PUSH == "dockerhub" ]]; then
  # Create Repository path specific for Dockerhub.
  REPOSITORY_PATH="${REPOSITORY}"

  # Login into dockerhub account
  DOCKER_HUB_SECRET="com.amazonaws.dockerhub.aws-for-fluent-bit.credentials"
  docker login \
  -u "$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.username')" \
  --password "$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.password')"

#############################################################################################################
# Other registries are not supported.
#############################################################################################################
else
  echo "Unsupported registry: ${REGISTRY_TO_PUSH}"
  exit 1
fi

#############################################################################################################
# "create-manifest" action is used to create and push manifests for Windows in the target region and account.
#############################################################################################################
if [[ $ACTION == "create-manifest" ]]; then

  # Create and push the image manifests for all the versions.
  while read -r version; do
    # Create image manifest.
    docker manifest create ${REPOSITORY_PATH}:${version}-windowsservercore \
    ${REPOSITORY_PATH}:${version}-${os_releases[windows2019]} \
    ${REPOSITORY_PATH}:${version}-${os_releases[windows2022]}
    if [ $? = 1 ]; then
      echo "Failed to create manifest for ${REPOSITORY_PATH}:${version}-windowsservercore"
      exit 1
    fi

    # Sanity check the manifest.
    docker manifest inspect ${REPOSITORY_PATH}:${version}-windowsservercore

    # Push manifest to ECR.
    docker manifest push ${REPOSITORY_PATH}:${version}-windowsservercore
    if [ $? = 1 ]; then
      echo "Failed to push manifest ${REPOSITORY_PATH}:${version}-windowsservercore"
      exit 1
    fi
  done <<< "$(echo "${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}")"

  # Create manifest for latest image.
  docker manifest create ${REPOSITORY_PATH}:windowsservercore-latest \
  ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-${os_releases[windows2019]} \
  ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-${os_releases[windows2022]}
  if [ $? = 1 ]; then
    echo "Failed to create manifest for ${REPOSITORY_PATH}:windowsservercore-latest"
    exit 1
  fi

  # Push manifest for latest image.
  docker manifest push ${REPOSITORY_PATH}:windowsservercore-latest
  if [ $? = 1 ]; then
    echo "Failed to push manifest ${REPOSITORY_PATH}:windowsservercore-latest"
    exit 1
  fi

#############################################################################################################
# "sync-stable-image" action is used to sync stable image in target repository/region/account.
#############################################################################################################
elif [[ $ACTION == "sync-stable-image" ]]; then
  # Obtain the image URLs for expected and actual stable Windows image.
  EXPECTED_IMAGE_FOR_STABLE="${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-windowsservercore"
  ACTUAL_IMAGE_FOR_STABLE="${REPOSITORY_PATH}:windowsservercore-stable"

  # If the image manifests are not same then create and push the latest one.
  compare_image_manifests "${EXPECTED_IMAGE_FOR_STABLE}" "${ACTUAL_IMAGE_FOR_STABLE}"
  if [ $? = 1 ]; then
      # Create manifest for stable image.
      docker manifest create ${REPOSITORY_PATH}:windowsservercore-stable \
      ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-${os_releases[windows2019]} \
      ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-${os_releases[windows2022]}

      # Push manifest for stable image.
      docker manifest push ${REPOSITORY_PATH}:windowsservercore-stable
      if [ $? = 1 ]; then
        echo "Failed to push manifest ${REPOSITORY_PATH}:windowsservercore-stable"
        exit 1
      fi
      echo "Synced the latest version of stable image"
  else
    echo "Stable image is already in sync"
  fi
#############################################################################################################
# Any other action is not supported.
#############################################################################################################
else
  echo "Unsupported action: ${ACTION}"
  exit 1
fi


#!/bin/bash

VERSION=$1
if [ -z "$VERSION" ]; then
    echo "Usage $0 <version>"
    echo "Example: $0 2.31.11 "
    exit 1;
fi

image_shas=$(aws ecr describe-images --registry-id 906394416424 --repository-name aws-for-fluent-bit --region us-west-2 --image-ids imageTag=${VERSION} imageTag=arm64-${VERSION} imageTag=amd64-${VERSION} imageTag=init-arm64-${VERSION} imageTag=init-amd64-${VERSION} imageTag=${VERSION}-windowsservercore imageTag=${VERSION}-ltsc2019 imageTag=${VERSION}-ltsc2022 | jq -r '.imageDetails[] | objects | .imageDigest')

image_sha_array=($image_shas)

echo "Paste below query into Athena console and replace eventTime with desired data range"
echo "This can be used to obtain 'private' ECR download count"
echo "The query is for classic regions but can be used in other regions by changing the table name to 'cloudtrail_fluentbit'"
echo "-------"
echo ""
echo "
SELECT COUNT(*) as call_count
FROM cloudtrail_fluentbitimage
WHERE
    eventsource = 'ecr.amazonaws.com' AND
    eventname in ('GetDownloadUrlForLayer', 'BatchGetImage') AND
    eventTime > 'YYYY-MM-DDT00:00:00Z' AND
    eventTime < 'YYYY-MM-DDT00:00:00Z' AND (
      requestparameters like '%"imageTag":"${VERSION}"%' OR
      requestparameters like '%"imageTag":"amd64-${VERSION}"%' OR
      requestparameters like '%"imageTag":"arm64-${VERSION}"%' OR
      requestparameters like '%"imageTag":"init-${VERSION}"%' OR
      requestparameters like '%"imageTag":"init-amd64-${VERSION}"%' OR
      requestparameters like '%"imageTag":"init-arm64-${VERSION}"%' OR
      requestparameters like '%"imageTag":"${VERSION}-windowsservercore"%' OR
      requestparameters like '%"imageTag":"${VERSION}-ltsc2019"%' OR
      requestparameters like '%"imageTag":"${VERSION}-ltsc2022"%' OR
      requestparameters like '%${image_sha_array[0]}%' OR
      requestparameters like '%${image_sha_array[1]}%' OR
      requestparameters like '%${image_sha_array[2]}%' OR
      requestparameters like '%${image_sha_array[3]}%' OR
      requestparameters like '%${image_sha_array[4]}%' OR
      requestparameters like '%${image_sha_array[5]}%' OR
      requestparameters like '%${image_sha_array[6]}%' OR
      requestparameters like '%${image_sha_array[7]}%'
    )
"


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -xeuo pipefail

scripts=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
cd "${scripts}"

IMAGE_SHA_MATCHED="FALSE"
AWS_FOR_FLUENT_BIT_VERSION=$(cat ../AWS_FOR_FLUENT_BIT_VERSION)
AWS_FOR_FLUENT_BIT_STABLE_VERSION=$(cat ../AWS_FOR_FLUENT_BIT_STABLE_VERSION)

PUBLISH_LATEST=$(cat ../linux.version | jq -r '.linux.latest')
echo "Publish Latest? ${PUBLISH_LATEST}"

# Problem: when we push a new version bump the version number in AWS_FOR_FLUENT_BIT_VERSION file changes
# but that version is not published immediately. Thus, sync tasks normally
# sync latest version found in DockerHub. But what if we want to release a non-latest version?
# then sync tasks need to know this. So we use the script to check for an already published version
# that's not latest

# this code currenly works because DockerHub returns the only last 100 tags and as of March 2023 we only have 64
# and it should keep working because dockerhub returns the latest tags first
docker_hub_image_tags=$(curl -s -S 'https://registry.hub.docker.com/v2/repositories/amazon/aws-for-fluent-bit/tags/?page=1&page_size=250' | jq -r '.results[].name')
tag_array=(`echo ${docker_hub_image_tags}`)
AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB=$(./get_latest_dockerhub_version.py linux latest ${tag_array[@]})

# If the AWS_FOR_FLUENT_BIT_VERSION is an older version which is already published to dockerhub
# and latest is set to false in linux.version, then we sync an older non-latest version.
# otherwise, normal behavior, sync latest version found in dockerhub
if [ "${PUBLISH_LATEST}" = "false" ]; then
	PUBLISH_NON_LATEST=$(./get_latest_dockerhub_version.py linux ${AWS_FOR_FLUENT_BIT_VERSION} ${tag_array[@]})
	if [ "${PUBLISH_NON_LATEST}" = "true" ]; then
		AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB=${AWS_FOR_FLUENT_BIT_VERSION}
	fi
fi

# Enforce STS regional endpoints
AWS_STS_REGIONAL_ENDPOINTS=regional

classic_regions="
us-east-1
eu-west-1
us-west-1
ap-southeast-1
ap-northeast-1
us-west-2
sa-east-1
ap-southeast-2
eu-central-1
ap-northeast-2
ap-south-1
us-east-2
ca-central-1
eu-west-2
eu-west-3
eu-north-1
ap-northeast-3
"

classic_regions_account_id="906394416424"

cn_regions="
cn-north-1
cn-northwest-1
"

cn_regions_account_id="128054284489"

gov_regions="
us-gov-east-1
us-gov-west-1
"

gov_regions_account_id="161423150738"

hongkong_region="ap-east-1"

hongkong_account_id="449074385750"

bahrain_region="me-south-1"

bahrain_account_id="741863432321"

cape_town_region="af-south-1"

cape_town_account_id="928143927712"

milan_region="eu-south-1"

milan_account_id="960320637246"

jakarta_region="ap-southeast-3"

jakarta_account_id="921575906885"

uae_region="me-central-1"

uae_account_id="358001906437"

spain_region="eu-south-2"

spain_account_id="146576467002"

zurich_region="eu-central-2"

zurich_account_id="269912160255"

hyderabad_region="ap-south-2"

hyderabad_account_id="378905956269"

gamma_region="us-west-2"

gamma_account_id="626332813196"

DOCKER_HUB_SECRET="com.amazonaws.dockerhub.aws-for-fluent-bit.credentials"

ARCHITECTURES=("amd64" "arm64")

# This variable is used in the image tag
init="init"

docker_hub_login() {
	username="$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.username')"
	password="$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.password')"

	# Logout when the script exits
	trap cleanup EXIT
	cleanup() {
		docker logout
	}

	# login to DockerHub
	docker login -u "${username}" --password "${password}"
}

publish_to_docker_hub() {
	export DOCKER_CLI_EXPERIMENTAL=enabled

	docker_hub_login

	if [ $# -eq 2 ]; then
		# Get the image SHA's
		docker pull ${1}:stable || echo "0"
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${1}:stable || echo "0")
		docker pull ${1}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${1}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})

		match_two_sha $sha1 $sha2

		if [ "$IMAGE_SHA_MATCHED" = "FALSE" ]; then
			create_manifest_list ${1} "stable" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		fi
	else
		for arch in "${ARCHITECTURES[@]}"
		do
			docker tag ${1}:"$arch" ${1}:"${arch}"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push ${1}:"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$arch"-"debug" ${1}:"${arch}"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push ${1}:"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$init"-"$arch" ${1}:"$init"-"${arch}"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push ${1}:"$init"-"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$init"-"$arch"-"debug" ${1}:"$init"-"${arch}"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push ${1}:"$init"-"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}

		done

		create_manifest_list ${1} ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
		create_manifest_list ${1} "debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}

		create_manifest_list_init ${1} "$init"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
		create_manifest_list_init ${1} "$init"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}

		if [ "${PUBLISH_LATEST}" = "true" ]; then
			create_manifest_list ${1} "latest" ${AWS_FOR_FLUENT_BIT_VERSION}
			create_manifest_list ${1} "debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}
			create_manifest_list_init ${1} "init-latest" ${AWS_FOR_FLUENT_BIT_VERSION}
			create_manifest_list_init ${1} "init-debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}
		fi
	fi
}

publish_to_public_ecr() {
	if [ $# -eq 2 ]; then
		aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:stable || echo "0"
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:stable || echo "0")
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})

		match_two_sha $sha1 $sha2

		if [ "$IMAGE_SHA_MATCHED" = "FALSE" ]; then
			aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
			create_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit "stable" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		fi
	else
		aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability

		for arch in "${ARCHITECTURES[@]}"
		do
			docker tag ${1}:"$arch" public.ecr.aws/aws-observability/aws-for-fluent-bit:"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push public.ecr.aws/aws-observability/aws-for-fluent-bit:"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$arch"-"debug" public.ecr.aws/aws-observability/aws-for-fluent-bit:"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push public.ecr.aws/aws-observability/aws-for-fluent-bit:"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$init"-"$arch" public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

			docker tag ${1}:"$init"-"$arch"-"debug" public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
			docker push public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
		done

		create_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
		aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
		create_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit "debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}

		create_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit "$init"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
		aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
		create_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit "$init"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}

		if [ "${PUBLISH_LATEST}" = "true" ]; then
			create_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit "latest" ${AWS_FOR_FLUENT_BIT_VERSION}
			aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
			create_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit "debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}

			create_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit "init-latest" ${AWS_FOR_FLUENT_BIT_VERSION}
			aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability
			create_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit "init-debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}
		fi
	fi
}

publish_ssm() {
	# This optional parameter indicates if we should publish stable (defaults to false)
	if [ ${4:-false} = true ]; then
		aws ssm put-parameter --name /aws/service/aws-for-fluent-bit/stable --overwrite \
			--description 'Regional Amazon ECR Image URI for the latest stable AWS for Fluent Bit Docker Image' \
			--type String --region ${1} --value ${2}:${3}
	else
		aws ssm put-parameter --name /aws/service/aws-for-fluent-bit/${3} --overwrite \
			--description 'Regional Amazon ECR Image URI for the latest AWS for Fluent Bit Docker Image' \
			--type String --region ${1} --value ${2}:${3}

		if [ "${PUBLISH_LATEST}" = "true" ]; then
			aws ssm put-parameter --name /aws/service/aws-for-fluent-bit/latest --overwrite \
				--description 'Regional Amazon ECR Image URI for the latest AWS for Fluent Bit Docker Image' \
				--type String --region ${1} --value ${2}:latest
		fi

		aws ssm put-parameter --name /aws/service/aws-for-fluent-bit/"$init"-${3} --overwrite \
			--description 'Regional Amazon ECR Image URI for the "$init"-latest AWS for Fluent Bit Docker Image' \
			--type String --region ${1} --value ${2}:"$init"-${3}

		if [ "${PUBLISH_LATEST}" = "true" ]; then
			aws ssm put-parameter --name /aws/service/aws-for-fluent-bit/"$init"-latest --overwrite \
				--description 'Regional Amazon ECR Image URI for the "$init"-latest AWS for Fluent Bit Docker Image' \
				--type String --region ${1} --value ${2}:"$init"-latest
		fi
	fi
}

rollback_ssm() {
	aws ssm delete-parameter --name /aws/service/aws-for-fluent-bit/${AWS_FOR_FLUENT_BIT_VERSION} --region ${1}

	aws ssm delete-parameter --name /aws/service/aws-for-fluent-bit/"$init"-${AWS_FOR_FLUENT_BIT_VERSION} --region ${1}
}

check_parameter() {
	repo_uri=$(aws ssm get-parameter --name /aws/service/aws-for-fluent-bit/${2} --region ${1} --query 'Parameter.Value')
	IFS='.' read -r -a array <<<"$repo_uri"
	region="${array[3]}"
	if [ "${1}" != "${region}" ]; then
		echo "${1}: Region found in repo URI does not match SSM Parameter region: ${repo_uri}"
		exit 1
	fi
	# remove leading and trailing quotes from repo_uri
	repo_uri=$(sed -e 's/^"//' -e 's/"$//' <<<"$repo_uri")
	docker pull $repo_uri

	if [ "${2}" != "stable" ]; then
		repo_uri_init=$(aws ssm get-parameter --name /aws/service/aws-for-fluent-bit/"$init"-${2} --region ${1} --query 'Parameter.Value')
		IFS='.' read -r -a array <<<"$repo_uri_init"
		region="${array[3]}"
		if [ "${1}" != "${region}" ]; then
			echo "${1}: Region found in repo URI does not match SSM Parameter region: ${repo_uri}"
			exit 1
		fi
		# remove leading and trailing quotes from repo_uri
		repo_uri_init=$(sed -e 's/^"//' -e 's/"$//' <<<"$repo_uri")
		docker pull $repo_uri_init
	fi
}

sync_public_and_repo() {
	region=${1}
	account_id=${2}
	endpoint=${3}
	tag=${4}

	docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag}
	sha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag})
	aws ecr get-login-password --region ${region}| docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.${endpoint}
	repoList=$(aws ecr describe-repositories --region ${region})
	repoName=$(echo $repoList | jq .repositories[0].repositoryName)
	if [ "$repoName" = '"aws-for-fluent-bit"' ]; then
		tagCount=$(aws ecr list-images  --repository-name aws-for-fluent-bit --region ${region} | jq -r '.imageIds[].imageTag' | grep -c ${tag} || echo "0")
		if [ "$tagCount" = '1' ]; then
			docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag}
			sha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag})
		else
			sha2='repo_not_found'
		fi
	else
		sha2='repo_not_found'
	fi

	match_two_sha $sha1 $sha2

	if [ "$IMAGE_SHA_MATCHED" = "FALSE" ]; then
		aws ecr create-repository --repository-name aws-for-fluent-bit --image-scanning-configuration scanOnPush=true --region ${region}  || true
		push_image_ecr public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag} \
			${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag}
	fi
}

sync_ssm() {
	namespace_path=${1}
	region=${2}
	repo=${3}
	tag=${4}

	# Check the namespace_path looking for stable at the end, if the string were too short it would return an empty string
	is_stable=false
	if [ "${namespace_path:(-6)}" = "stable" ]; then
		is_stable=true
	fi

	invalid_parameter=
	should_prepare=false
	# Check to see if namespace is prepared, once a parameter is put into namespace requests should not fail
	if ! ssm_parameters=$(aws ssm get-parameters --names ${namespace_path} --region ${region}); then
		should_prepare=true
	else
		invalid_parameter=$(echo $ssm_parameters | jq .InvalidParameters[0])
	fi

	if [ $should_prepare = true ] || [ "$invalid_parameter" != 'null' ]; then
		publish_ssm ${region} ${repo} ${tag} ${is_stable}
	fi
}

sync_image_version() {
	region=${1}
	account_id=${2}

	endpoint='amazonaws.com'
	if [ "${1}" = "cn-north-1" ] || [ "${1}" = "cn-northwest-1" ]; then
		endpoint=${endpoint}.cn
	fi

	for arch in "${ARCHITECTURES[@]}"
	do
		aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability || echo "0"
		sync_public_and_repo ${region} ${account_id} ${endpoint} "${arch}-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}"

		sync_public_and_repo ${region} ${account_id} ${endpoint} "${arch}-debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}"

		sync_public_and_repo ${region} ${account_id} ${endpoint} "${init}-${arch}-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}"

		sync_public_and_repo ${region} ${account_id} ${endpoint} "${init}-${arch}-debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}"

		sync_public_and_repo ${region} ${account_id} ${endpoint} "${arch}-${AWS_FOR_FLUENT_BIT_STABLE_VERSION}"
	done

	if [ "${account_id}" != "${classic_regions_account_id}" ]; then
		create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "debug"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}

		create_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "$init"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		create_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "$init"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		if [ "${PUBLISH_LATEST}" = "true" ]; then
			create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "latest" ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
			create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}

			create_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "init-latest" ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
			create_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "init-debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		fi
	fi

	if [ "${AWS_FOR_FLUENT_BIT_STABLE_VERSION}" != "${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}" ]; then
		create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
	fi

	create_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit "stable" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo "0"

	make_repo_public ${region}

	sync_ssm "/aws/service/aws-for-fluent-bit/${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}" ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	sync_ssm "/aws/service/aws-for-fluent-bit/stable" ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}

	stable_uri=$(aws ssm get-parameters --names /aws/service/aws-for-fluent-bit/stable --region ${region} --query 'Parameters[0].Value')
	stable_uri=$(sed -e 's/^"//' -e 's/"$//' <<<"$stable_uri")

	if [ "$stable_uri" != "${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}" ]; then
		publish_ssm ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} true
	fi
}

verify_ssm() {
	is_sync_task=${2:-false}

	endpoint='amazonaws.com'

	if [ "${1}" = "cn-north-1" ] || [ "${1}" = "cn-northwest-1" ]; then
		endpoint=${endpoint}.cn
	fi
	aws ecr get-login-password --region ${1} | docker login --username AWS --password-stdin ${3}.dkr.ecr.${1}.${endpoint}

	if [ "${PUBLISH_LATEST}" = "true" ]; then
		check_parameter ${1} latest
	fi

	if [ "${is_sync_task}" = "true" ]; then
		check_parameter ${1} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		check_parameter ${1} stable
	else
		check_parameter ${1} ${AWS_FOR_FLUENT_BIT_VERSION}
	fi
}

create_manifest_list() {

	export DOCKER_CLI_EXPERIMENTAL=enabled
	tag=${2}
	version=${3}

	# TODO: Add a way to automatically generate arch images in manifest
	docker manifest create ${1}:${tag} ${1}:arm64-${version} ${1}:amd64-${version}

	for arch in "${ARCHITECTURES[@]}"
	do
		docker manifest annotate --arch "$arch" ${1}:${tag} ${1}:"$arch"-${version}
	done

	# sanity check on the debug log.
 	docker manifest inspect ${1}:${tag}
	docker manifest push ${1}:${tag}
}

create_manifest_list_init() {

	export DOCKER_CLI_EXPERIMENTAL=enabled
	tag=${2}
	version=${3}

	# TODO: Add a way to automatically generate arch images in manifest
	docker manifest create ${1}:${tag} ${1}:"$init"-arm64-${version} ${1}:"$init"-amd64-${version}

	for arch in "${ARCHITECTURES[@]}"
	do
		docker manifest annotate --arch "$arch" ${1}:${tag} ${1}:"$init"-"$arch"-${version}
	done

	# sanity check on the debug log.
 	docker manifest inspect ${1}:${tag}
	docker manifest push ${1}:${tag}
}

push_image_ecr() {
	docker tag ${1} ${2}
    	docker push ${2}
}

make_repo_public() {
	aws ecr set-repository-policy --repository-name aws-for-fluent-bit --policy-text file://public_repo_policy.json --region ${1}
}

publish_ecr() {
	region=${1}
	account_id=${2}

	aws ecr get-login-password --region ${region}| docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.amazonaws.com
	aws ecr create-repository --repository-name aws-for-fluent-bit --image-scanning-configuration scanOnPush=true --region ${region}  || true

	for arch in "${ARCHITECTURES[@]}"
	do
		push_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:"$arch" \
			${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

		push_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:"$arch"-"debug" \
			${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}

		push_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:"$init"-"$arch" \
			${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:"$init"-"$arch"-${AWS_FOR_FLUENT_BIT_VERSION}

		push_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:"$init"-"$arch"-"debug" \
			${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:"$init"-"$arch"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION}
	done

	create_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
	create_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}
	create_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "$init"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}
	create_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "$init"-"debug"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}

	if [ "${PUBLISH_LATEST}" = "true" ]; then
		create_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "latest" ${AWS_FOR_FLUENT_BIT_VERSION}
		create_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}
		create_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "init-latest" ${AWS_FOR_FLUENT_BIT_VERSION}
		create_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit "init-debug-latest" debug-${AWS_FOR_FLUENT_BIT_VERSION}
	fi

	make_repo_public ${region}
}

verify_ecr() {
	region=${1}
	account_id=${2}
	is_sync_task=${3:-false}

	endpoint='amazonaws.com'
	if [ "${1}" = "cn-north-1" ] || [ "${1}" = "cn-northwest-1" ]; then
		endpoint=${endpoint}.cn
	fi
	aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.${endpoint}

	if [ "${is_sync_task}" = "true" ]; then
		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:stable || echo "0"
		stableSha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:stable || echo "0")
		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo "0"
		stableSha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo "0")

		verify_sha $stableSha1 $stableSha2

		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})

		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		sha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})

		# verify version number tag against public ECR
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})

		verify_sha $sha1 $sha2

		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:init-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		sha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:init-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})

		verify_sha $sha1_init $sha2_init
	else
		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})

		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION}
		sha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION})
	fi

	# in main pipeline when publishing a non-latest release
	# we can't verify the SHA against any other tag
	# only verification is the above steps to pull the image
	if [ "${PUBLISH_LATEST}" = "true" ]; then
	    # Also validate version number tag against latest tag
		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:latest
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:latest)

		verify_sha $sha1 $sha2

		docker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-latest
		sha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:"$init"-latest)

		verify_sha $sha1_init $sha2_init
	fi
}

check_image_version() {
	export DOCKER_CLI_EXPERIMENTAL=enabled
	EXIT_CODE=0

	docker_hub_login

	# check if we can get the image information in dockerhub; if yes, the exit status should be 0
	docker manifest inspect public.ecr.aws/aws-observability/aws-for-fluent-bit:${1} > /dev/null || EXIT_CODE=$?
	if [ "${EXIT_CODE}" = "0" ]; then
		echo "Accidental release: current image version from github source file match a previous version from dockerhub."
		exit 1
	fi

	echo "Approved release: release the image with a new version."
}

verify_ecr_image_scan() {
	region=${1}
	repo_uri=${2}
	tag=${3}

	tagCount=$(aws ecr list-images  --repository-name ${repo_uri} --region ${region} | jq -r '.imageIds[].imageTag' | grep -c ${tag} || echo "0")
	if [ "$tagCount" = '1' ]; then
		aws ecr start-image-scan --repository-name ${repo_uri} --image-id imageTag=${tag} --region ${region}
		aws ecr wait image-scan-complete --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag}
		highVulnerabilityCount=$(aws ecr describe-image-scan-findings --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag} | jq '.imageScanFindings.findingSeverityCounts.HIGH')
		criticalVulnerabilityCount=$(aws ecr describe-image-scan-findings --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag} | jq '.imageScanFindings.findingSeverityCounts.CRITICAL')
		if [ "$highVulnerabilityCount" != null ] || [ "$criticalVulnerabilityCount" != null ]; then
			echo "Uploaded image ${tag} has ${vulnerabilityCount} vulnerabilities."
			exit 1
		fi
	fi
}

verify_dockerhub() {
	docker_hub_login

	# Verify the image with stable tag
	if [ $# -eq 1 ] || [ "${PUBLISH_LATEST}" = "false" ]; then
		# Get the image SHA's
		docker pull amazon/aws-for-fluent-bit:stable
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:stable)
		docker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})

		verify_sha $sha1 $sha2
	else
		# Get the image SHA's
		docker pull amazon/aws-for-fluent-bit:latest
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:latest)
		docker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})

		verify_sha $sha1 $sha2

		docker pull amazon/aws-for-fluent-bit:"$init"-latest
		sha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:"$init"-latest)
		docker pull amazon/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION}
		sha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION})
		verify_sha $sha1_init $sha2_init
	fi
}

verify_public_ecr() {
	aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability || echo "0"

	# Verify the image with stable tag
	if [ $# -eq 1 ] || [ "${PUBLISH_LATEST}" = "false" ]; then
		# Get the image SHA's
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:stable
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:stable)
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})

		verify_sha $sha1 $sha2
	else
		# Get the image SHA's
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:latest
		sha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:latest)
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}
		sha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})

		verify_sha $sha1 $sha2

		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-latest
		sha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-latest)
		docker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION}
		sha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:"$init"-${AWS_FOR_FLUENT_BIT_VERSION})

		verify_sha $sha1_init $sha2_init
	fi
}

verify_sha() {
	sha1=${1}
	sha2=${2}

	match_two_sha $sha1 $sha2

	if [ "$IMAGE_SHA_MATCHED" = "TRUE" ]; then
		echo '[Publish Verification] Successfull'
		IMAGE_SHA_MATCHED="FALSE"
	else
		echo '[Publish Verification] Failed'
		exit 1
	fi
}

match_two_sha() {
	sha1=${1}
	sha2=${2}

	# Get the last 64 chars of the SHA string
	last64_1=$(echo $sha1 | egrep -o '.{1,64}$')
	last64_2=$(echo $sha2 | egrep -o '.{1,64}$')

	if [ "$last64_1" = "$last64_2" ]; then
		IMAGE_SHA_MATCHED="TRUE"
	else
		IMAGE_SHA_MATCHED="FALSE"
	fi
}

if [ "${1}" = "publish" ]; then
	if [ "${2}" = "dockerhub" ]; then
		publish_to_docker_hub amazon/aws-for-fluent-bit
	fi

	if [ "${2}" = "aws" ]; then
		for region in ${classic_regions}; do
			publish_ecr ${region} ${classic_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-cn" ]; then
		for region in ${cn_regions}; do
			publish_ecr ${region} ${cn_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-us-gov" ]; then
		for region in ${gov_regions}; do
			publish_ecr ${region} ${gov_regions_account_id}
		done
	fi

	if [ "${2}" = "${hongkong_region}" ]; then
		publish_ecr ${hongkong_region} ${hongkong_account_id}
	fi

	if [ "${2}" = "${bahrain_region}" ]; then
		publish_ecr ${bahrain_region} ${bahrain_account_id}
	fi

	if [ "${2}" = "${cape_town_region}" ]; then
		publish_ecr ${cape_town_region} ${cape_town_account_id}
	fi

	if [ "${2}" = "${milan_region}" ]; then
		publish_ecr ${milan_region} ${milan_account_id}
	fi

	if [ "${2}" = "${jakarta_region}" ]; then
		publish_ecr ${jakarta_region} ${jakarta_account_id}
	fi

	if [ "${2}" = "${uae_region}" ]; then
		publish_ecr ${uae_region} ${uae_account_id}
	fi

	if [ "${2}" = "${spain_region}" ]; then
		publish_ecr ${spain_region} ${spain_account_id}
	fi

	if [ "${2}" = "${zurich_region}" ]; then
		publish_ecr ${zurich_region} ${zurich_account_id}
	fi

	if [ "${2}" = "${hyderabad_region}" ]; then
		publish_ecr ${hyderabad_region} ${hyderabad_account_id}
	fi

	if [ "${2}" = "gamma" ]; then
		publish_ecr ${gamma_region} ${gamma_account_id}
	fi
fi

if [ "${1}" = "verify" ]; then
	if [ "${2}" = "dockerhub" ]; then
		docker pull amazon/aws-for-fluent-bit:latest
		docker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}
	fi
	if [ "${2}" = "aws" ]; then
		for region in ${classic_regions}; do
			verify_ecr ${region} ${classic_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-cn" ]; then
		for region in ${cn_regions}; do
			verify_ecr ${region} ${cn_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-us-gov" ]; then
		for region in ${gov_regions}; do
			verify_ecr ${region} ${gov_regions_account_id}
		done
	fi

	if [ "${2}" = "${hongkong_region}" ]; then
		verify_ecr ${hongkong_region} ${hongkong_account_id}
	fi

	if [ "${2}" = "${bahrain_region}" ]; then
		verify_ecr ${bahrain_region} ${bahrain_account_id}
	fi

	if [ "${2}" = "${cape_town_region}" ]; then
		verify_ecr ${cape_town_region} ${cape_town_account_id}
	fi

	if [ "${2}" = "${milan_region}" ]; then
		verify_ecr ${milan_region} ${milan_account_id}
	fi

	if [ "${2}" = "${jakarta_region}" ]; then
		verify_ecr ${jakarta_region} ${jakarta_account_id}
	fi

	if [ "${2}" = "${uae_region}" ]; then
		verify_ecr ${uae_region} ${uae_account_id}
	fi

	if [ "${2}" = "${spain_region}" ]; then
		verify_ecr ${spain_region} ${spain_account_id}
	fi

	if [ "${2}" = "${zurich_region}" ]; then
		verify_ecr ${zurich_region} ${zurich_account_id}
	fi

	if [ "${2}" = "${hyderabad_region}" ]; then
		verify_ecr ${hyderabad_region} ${hyderabad_account_id}
	fi

	if [ "${2}" = "gamma" ]; then
		verify_ecr ${gamma_region} ${gamma_account_id}
	fi
fi

if [ "${1}" = "publish-ssm" ]; then
	if [ "${2}" = "aws" ]; then
		for region in ${classic_regions}; do
			publish_ssm ${region} ${classic_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION}
		done
	fi

	if [ "${2}" = "aws-cn" ]; then
		for region in ${cn_regions}; do
			publish_ssm ${region} ${cn_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		done
	fi

	if [ "${2}" = "aws-us-gov" ]; then
		for region in ${gov_regions}; do
			publish_ssm ${region} ${gov_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		done
	fi

	if [ "${2}" = "${hongkong_region}" ]; then
		publish_ssm ${hongkong_region} ${hongkong_account_id}.dkr.ecr.${hongkong_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${bahrain_region}" ]; then
		publish_ssm ${bahrain_region} ${bahrain_account_id}.dkr.ecr.${bahrain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${cape_town_region}" ]; then
		publish_ssm ${cape_town_region} ${cape_town_account_id}.dkr.ecr.${cape_town_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${milan_region}" ]; then
		publish_ssm ${milan_region} ${milan_account_id}.dkr.ecr.${milan_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${jakarta_region}" ]; then
		publish_ssm ${jakarta_region} ${jakarta_account_id}.dkr.ecr.${jakarta_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${uae_region}" ]; then
		publish_ssm ${uae_region} ${uae_account_id}.dkr.ecr.${uae_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${spain_region}" ]; then
		publish_ssm ${spain_region} ${spain_account_id}.dkr.ecr.${spain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${zurich_region}" ]; then
		publish_ssm ${zurich_region} ${zurich_account_id}.dkr.ecr.${zurich_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi

	if [ "${2}" = "${hyderabad_region}" ]; then
		publish_ssm ${hyderabad_region} ${hyderabad_account_id}.dkr.ecr.${hyderabad_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	fi
fi

if [ "${1}" = "verify-ssm" ]; then
	if [ "${2}" = "aws" ]; then
		for region in ${classic_regions}; do
			verify_ssm ${region} false ${classic_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-cn" ]; then
		for region in ${cn_regions}; do
			verify_ssm ${region} false ${cn_regions_account_id}
		done
	fi

	if [ "${2}" = "aws-us-gov" ]; then
		for region in ${gov_regions}; do
			verify_ssm ${region} false ${gov_regions_account_id}
		done
	fi

	if [ "${2}" = "${hongkong_region}" ]; then
		verify_ssm ${hongkong_region} false ${hongkong_account_id}
	fi

	if [ "${2}" = "${bahrain_region}" ]; then
		verify_ssm ${bahrain_region} false ${bahrain_account_id}
	fi

	if [ "${2}" = "${cape_town_region}" ]; then
		verify_ssm ${cape_town_region} false ${cape_town_account_id}
	fi

	if [ "${2}" = "${milan_region}" ]; then
		verify_ssm ${milan_region} false ${milan_account_id}
	fi

	if [ "${2}" = "${jakarta_region}" ]; then
		verify_ssm ${jakarta_region} false ${jakarta_account_id}
	fi

	if [ "${2}" = "${uae_region}" ]; then
		verify_ssm ${uae_region} false ${uae_account_id}
	fi

	if [ "${2}" = "${spain_region}" ]; then
		verify_ssm ${spain_region} false ${spain_account_id}
	fi

	if [ "${2}" = "${zurich_region}" ]; then
		verify_ssm ${zurich_region} false ${zurich_account_id}
	fi

	if [ "${2}" = "${hyderabad_region}" ]; then
		verify_ssm ${hyderabad_region} false ${hyderabad_account_id}
	fi
fi

if [ "${1}" = "rollback-ssm" ]; then
	if [ "${2}" = "aws" ]; then
		for region in ${classic_regions}; do
			rollback_ssm ${region}
		done
	fi

	if [ "${2}" = "aws-cn" ]; then
		for region in ${cn_regions}; do
			rollback_ssm ${region}
		done
	fi

	if [ "${2}" = "aws-us-gov" ]; then
		for region in ${gov_regions}; do
			rollback_ssm ${region}
		done
	fi

	if [ "${2}" = "${hongkong_region}" ]; then
		rollback_ssm ${hongkong_region}
	fi

	if [ "${2}" = "${bahrain_region}" ]; then
		rollback_ssm ${bahrain_region}
	fi

	if [ "${2}" = "${cape_town_region}" ]; then
		rollback_ssm ${cape_town_region}
	fi

	if [ "${2}" = "${milan_region}" ]; then
		rollback_ssm ${milan_region}
	fi

	if [ "${2}" = "${jakarta_region}" ]; then
		rollback_ssm ${jakarta_region}
	fi

	if [ "${2}" = "${uae_region}" ]; then
		rollback_ssm ${uae_region}
	fi

	if [ "${2}" = "${spain_region}" ]; then
		rollback_ssm ${spain_region}
	fi

	if [ "${2}" = "${zurich_region}" ]; then
		rollback_ssm ${zurich_region}
	fi

	if [ "${2}" = "${hyderabad_region}" ]; then
		rollback_ssm ${hyderabad_region}
	fi
fi

# Publish using CI/CD pipeline
# Following scripts will be called only from the CI/CD pipeline
if [ "${1}" = "cicd-publish" ]; then
	if [ "${2}" = "dockerhub" ]; then
		publish_to_docker_hub amazon/aws-for-fluent-bit
	elif [ "${2}" = "public-ecr" ]; then
		publish_to_public_ecr amazon/aws-for-fluent-bit
	elif [ "${2}" = "us-gov-east-1" ] || [ "${2}" = "us-gov-west-1" ]; then
		for region in ${gov_regions}; do
			sync_image_version ${region} ${gov_regions_account_id}
		done
	elif [ "${2}" = "cn-north-1" ] || [ "${2}" = "cn-northwest-1" ]; then
		for region in ${cn_regions}; do
			sync_image_version ${region} ${cn_regions_account_id}
		done
	elif [ "${2}" = "${bahrain_region}" ]; then
		sync_image_version ${bahrain_region} ${bahrain_account_id}
	elif [ "${2}" = "${hongkong_region}" ]; then
		sync_image_version ${hongkong_region} ${hongkong_account_id}
	elif [ "${2}" = "${cape_town_region}" ]; then
		sync_image_version ${cape_town_region} ${cape_town_account_id}
	elif [ "${2}" = "${milan_region}" ]; then
		sync_image_version ${milan_region} ${milan_account_id}
	elif [ "${2}" = "${jakarta_region}" ]; then
		sync_image_version ${jakarta_region} ${jakarta_account_id}
	elif [ "${2}" = "${uae_region}" ]; then
		sync_image_version ${uae_region} ${uae_account_id}
	elif [ "${2}" = "${spain_region}" ]; then
		sync_image_version ${spain_region} ${spain_account_id}
	elif [ "${2}" = "${zurich_region}" ]; then
		sync_image_version ${zurich_region} ${zurich_account_id}
	elif [ "${2}" = "${hyderabad_region}" ]; then
		sync_image_version ${hyderabad_region} ${hyderabad_account_id}
	elif [ $# -eq 3 ] && [ "${3}" = "stable" ]; then
		for region in ${classic_regions}; do
			sync_image_version ${region} ${classic_regions_account_id}
		done
	elif [ $# -eq 3 ] && [ "${2}" = "public-dockerhub-stable" ]; then
		if [ "${3}" = "us-west-2" ]; then
			publish_to_docker_hub amazon/aws-for-fluent-bit stable
		fi
	elif [ $# -eq 3 ] && [ "${2}" = "public-ecr-stable" ]; then
		if [ "${3}" = "us-west-2" ]; then
			publish_to_public_ecr amazon/aws-for-fluent-bit stable
		fi
	else
		publish_ecr "${2}" ${classic_regions_account_id}
	fi
fi

# Verify using CI/CD pipeline
if [ "${1}" = "cicd-verify" ]; then
	if [ "${2}" = "dockerhub" ]; then
		verify_dockerhub
	elif [ "${2}" = "public-ecr" ]; then
		verify_public_ecr
	elif [ "${2}" = "us-gov-east-1" ] || [ "${2}" = "us-gov-west-1" ]; then
		for region in ${gov_regions}; do
			verify_ecr ${region} ${gov_regions_account_id} true
		done
	elif [ "${2}" = "cn-north-1" ] || [ "${2}" = "cn-northwest-1" ]; then
		for region in ${cn_regions}; do
			verify_ecr ${region} ${cn_regions_account_id} true
		done
	elif [ "${2}" = "${bahrain_region}" ]; then
		verify_ecr ${bahrain_region} ${bahrain_account_id} true
	elif [ "${2}" = "${hongkong_region}" ]; then
		verify_ecr ${hongkong_region} ${hongkong_account_id} true
	elif [ "${2}" = "${cape_town_region}" ]; then
		verify_ecr ${cape_town_region} ${cape_town_account_id} true
	elif [ "${2}" = "${milan_region}" ]; then
		verify_ecr ${milan_region} ${milan_account_id} true
	elif [ "${2}" = "${jakarta_region}" ]; then
		verify_ecr ${jakarta_region} ${jakarta_account_id} true
	elif [ "${2}" = "${uae_region}" ]; then
		verify_ecr ${uae_region} ${uae_account_id} true
	elif [ "${2}" = "${spain_region}" ]; then
		verify_ecr ${spain_region} ${spain_account_id} true
	elif [ "${2}" = "${zurich_region}" ]; then
		verify_ecr ${zurich_region} ${zurich_account_id} true
	elif [ "${2}" = "${hyderabad_region}" ]; then
		verify_ecr ${hyderabad_region} ${hyderabad_account_id} true
	elif [ $# -eq 3 ] && [ "${3}" = "stable" ]; then
		for region in ${classic_regions}; do
			verify_ecr ${region} ${classic_regions_account_id} true
		done
	elif [ "${2}" = "stable" ]; then
		if [ "${3}" = "us-west-2" ]; then
			verify_dockerhub stable
			verify_public_ecr stable
		fi
	else
		verify_ecr "${2}" ${classic_regions_account_id}
	fi
fi

# Publish SSM parameters
if [ "${1}" = "cicd-publish-ssm" ]; then
	if [ "${2}" = "us-gov-east-1" ] || [ "${2}" = "us-gov-west-1" ]; then
		for region in ${gov_regions}; do
			publish_ssm ${region} ${gov_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		done
	elif [ "${2}" = "cn-north-1" ] || [ "${2}" = "cn-northwest-1" ]; then
		for region in ${cn_regions}; do
			publish_ssm ${region} ${cn_regions_account_id}.dkr.ecr.${region}.amazonaws.com.cn/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
		done
	elif [ "${2}" = "${bahrain_region}" ]; then
		publish_ssm ${bahrain_region} ${bahrain_account_id}.dkr.ecr.${bahrain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${hongkong_region}" ]; then
		publish_ssm ${hongkong_region} ${hongkong_account_id}.dkr.ecr.${hongkong_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${cape_town_region}" ]; then
		publish_ssm ${cape_town_region} ${cape_town_account_id}.dkr.ecr.${cape_town_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${milan_region}" ]; then
		publish_ssm ${milan_region} ${milan_account_id}.dkr.ecr.${milan_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${jakarta_region}" ]; then
		publish_ssm ${jakarta_region} ${jakarta_account_id}.dkr.ecr.${jakarta_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${uae_region}" ]; then
		publish_ssm ${uae_region} ${uae_account_id}.dkr.ecr.${uae_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${spain_region}" ]; then
		publish_ssm ${spain_region} ${spain_account_id}.dkr.ecr.${spain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${zurich_region}" ]; then
		publish_ssm ${zurich_region} ${zurich_account_id}.dkr.ecr.${zurich_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	elif [ "${2}" = "${hyderabad_region}" ]; then
		publish_ssm ${hyderabad_region} ${hyderabad_account_id}.dkr.ecr.${hyderabad_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}
	else
		for region in ${classic_regions}; do
			publish_ssm ${region} ${classic_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION}
		done
	fi
fi

# Verify SSM parameters
if [ "${1}" = "cicd-verify-ssm" ]; then
	if [ "${2}" = "us-gov-east-1" ] || [ "${2}" = "us-gov-west-1" ]; then
		for region in ${gov_regions}; do
			verify_ssm ${region} true ${gov_regions_account_id}
		done
	elif [ "${2}" = "cn-north-1" ] || [ "${2}" = "cn-northwest-1" ]; then
		for region in ${cn_regions}; do
			verify_ssm ${region} true ${cn_regions_account_id}
		done
	elif [ "${2}" = "${bahrain_region}" ]; then
		verify_ssm ${bahrain_region} true ${bahrain_account_id}
	elif [ "${2}" = "${hongkong_region}" ]; then
		verify_ssm ${hongkong_region} true ${hongkong_account_id}
	elif [ "${2}" = "${cape_town_region}" ]; then
		verify_ssm ${cape_town_region} true ${cape_town_account_id}
	elif [ "${2}" = "${milan_region}" ]; then
		verify_ssm ${milan_region} true ${milan_account_id}
	elif [ "${2}" = "${jakarta_region}" ]; then
		verify_ssm ${jakarta_region} true ${jakarta_account_id}
	elif [ "${2}" = "${uae_region}" ]; then
		verify_ssm ${uae_region} true ${uae_account_id}
	elif [ "${2}" = "${spain_region}" ]; then
		verify_ssm ${spain_region} true ${spain_account_id}
	elif [ "${2}" = "${zurich_region}" ]; then
		verify_ssm ${zurich_region} true ${zurich_account_id}
	elif [ "${2}" = "${hyderabad_region}" ]; then
		verify_ssm ${hyderabad_region} true ${hyderabad_account_id}
	elif [ $# -eq 3 ]; then
		for region in ${classic_regions}; do
			verify_ssm ${region} true ${classic_regions_account_id}
		done
	else
		for region in ${classic_regions}; do
			verify_ssm ${region} false ${classic_regions_account_id}
		done
	fi
fi

if [ "${1}" = "cicd-verify-ecr-image-scan" ]; then
	verify_ecr_image_scan ${2} ${3} ${4}
fi

if [ "${1}" = "cicd-check-image-version" ]; then
	check_image_version ${AWS_FOR_FLUENT_BIT_VERSION}
fi


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -uo pipefail

#############################################################################################################
# This script would be executed from a codebuild project which would set the following environment variables-
# ACTION -> Action to perform. Can be amongst "publish-ssm-parameters", or "sync-ssm-parameter"
# SSM_PARAM_NAMESPACE -> The SSM Parameter namespace to be used.
# ACCOUNT_ID -> Account ID where the images are present.
# REGIONS_TO_PUBLISH -> A comma separated list of regions where we need to publish SSM parameter.
# PUBLIC_REGISTRY_ALIAS -> Used when syncing the SSM params.
# PUBLIC_REPOSITORY -> Public repository which is used for the image sync.
#############################################################################################################

#############################################################################################################
# Helper methods to publish the SSM Parameter.
#############################################################################################################

# This method publishes the SSM parameter for a given tag if the same is not present or has old data.
publish_ssm_param() {
  local region param_name expected_param_value ssm_parameter old_param_value
  region=${1}
  param_name=${2}
  expected_param_value=${3}

  echo "Publishing ${param_name} in ${region} region."
  ssm_parameter=$(aws ssm get-parameter --name "${param_name}" --region "${region}" || echo "1")
  # If SSM Parameter is present then find the old value.
  if [ "$ssm_parameter" != 1 ]; then
    old_param_value=$(echo "$ssm_parameter" | jq -r '.Parameter.Value')
  fi

  # If the expected parameter is not present, or has old data, then put the same in SSM store.
  if [[ "$ssm_parameter" = 1 || "$old_param_value" != "$expected_param_value" ]]; then
    # Verify that the image manifest actually exists and then publish the parameter.
    check_image_manifest_exists "${expected_param_value}"

    aws ssm put-parameter \
    --region "${region}" \
    --name "${param_name}" \
    --overwrite \
    --description 'Regional Amazon ECR Image URI for the AWS for Fluent Bit Windows Docker Image' \
    --type String \
    --value "${expected_param_value}"

    echo "Published SSM parameter ${param_name} = ${expected_param_value} in ${region} region"
  else
    echo "SSM Parameter ${param_name} is already latest. Skipping."
  fi
}

# Publishes SSM Parameter for a given version.
publish_ssm_param_for_version(){
  local region version param_name param_value
  region=${1}
  version=${2}
  # Get the regional endpoint variable
  image_endpoint=$(get_regional_image_endpoint "${region}")

  param_name="${SSM_PARAM_NAMESPACE}/${version}-windowsservercore"
  param_value="${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${version}-windowsservercore"

  publish_ssm_param "${region}" "${param_name}" "${param_value}"
}

# Publishes SSM Parameter for the latest version.
publish_ssm_param_for_latest(){
  local region param_name expected_param_value
  region=${1}
  # Get the regional endpoint variable
  image_endpoint=$(get_regional_image_endpoint "${region}")

  param_name="${SSM_PARAM_NAMESPACE}/windowsservercore-latest"
  expected_param_value="${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-windowsservercore"

  publish_ssm_param "${region}" "${param_name}" "${expected_param_value}"
}

# Publishes SSM Parameter for the stable version.
publish_ssm_param_for_stable(){
  local region param_name expected_param_value
  region=${1}
  # Get the regional endpoint variable
  image_endpoint=$(get_regional_image_endpoint "${region}")

  param_name="${SSM_PARAM_NAMESPACE}/windowsservercore-stable"
  expected_param_value="${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-windowsservercore"

  publish_ssm_param "${region}" "${param_name}" "${expected_param_value}"
}

# Publishes the SSM Parameter for all the supported versions in a given region.
publish_to_region() {
  local region
  region=${1}

  # For a given region, iterate over all supported versions and publish them if required.
  while read -r version; do
    publish_ssm_param_for_version "${region}" "${version}"
  done <<< "$(echo "${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}")"

  # Finally, publish the SSM param for latest as well as Dockerhub version.
  publish_ssm_param_for_latest $region
  publish_ssm_param_for_version "${region}" "${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}"
}

#############################################################################################################
# Helper methods for sync task
#############################################################################################################

# Compares if the image referenced by local SSM store and that in upstream repository are same.
compare_latest_ssm_param_image_with_public_ecr() {
  local region repository param_name ssm_parameter regional_ecr_image upstream_image
  region=${1}
  repository=${2}
  param_name="${SSM_PARAM_NAMESPACE}/windowsservercore-latest"
  upstream_image="${repository}:windowsservercore-latest"

  ssm_parameter=$(aws ssm get-parameter --name "${param_name}" --region "${region}" || echo "1")
  if [ "$ssm_parameter" = 1 ]; then
    return 1
  else
    regional_ecr_image=$(echo "$ssm_parameter" | jq -r '.Parameter.Value')
  fi

  compare_image_manifests "${regional_ecr_image}" "${upstream_image}"
  return $?
}

#############################################################################################################
# Start of the script
#############################################################################################################

# Source the common methods
source ./common_windows.sh

#############################################################################################################
# This action would be called in classic regions where we push the SSM parameters.
# "publish-ssm-parameters" action would publish a new SSM Parameter if same is not present.
#############################################################################################################
if [[ $ACTION == "publish-ssm-parameters" ]]; then
  echo "Publishing the SSM parameter for Windows images in regions: ${REGIONS_TO_PUBLISH}"

  # Split the comma separated list of regions into an array
  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\n/g'`)
  for region in "${REGIONS[@]}"
  do
    # Get the regional endpoint variable
    image_endpoint=$(get_regional_image_endpoint "${region}")
    # Authenticate to ECR so that regional image manifest can be inspected.
    aws ecr get-login-password --region "${region}" | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}"
    publish_to_region "${region}"
  done

#############################################################################################################
# This action would be invoked in opt-in regions as well as other partitions.
# We will check if the images referenced in SSM param are same as those in public ECR.
# If not, we will update the SSM parameters with latest.
#############################################################################################################
elif [[ $ACTION == "sync-ssm-parameter" ]]; then
  # Split the comma separated list of regions into an array
  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\n/g'`)
  for region in "${REGIONS[@]}"
  do
    # Get the regional endpoint
    image_endpoint=$(get_regional_image_endpoint "${region}")
    # Authenticate to ECR so that regional image manifest can be inspected.
    aws ecr get-login-password --region "${region}" | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}"

    # Publish stable parameter if it has old data.
    publish_ssm_param_for_stable "${region}"

    # For a given region, find if the sync is need for all other parameters.
    repository="public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}/${PUBLIC_REPOSITORY}"
    compare_latest_ssm_param_image_with_public_ecr "${region}" "${repository}"

    # If return value is 1, then publish the SSM params in this region.
    if [ $? = 1 ]; then
      publish_to_region "${region}"
    fi
  done

#############################################################################################################
# Any action not matching above is unsupported.
#############################################################################################################
else
  echo "Unsupported action: ${ACTION}"
  exit 1
fi


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -uo pipefail

#############################################################################################################
# Start of the script
#############################################################################################################

# Source the common methods
source ./common_windows.sh
# Get the regional endpoint variable
image_endpoint=$(get_regional_image_endpoint "${TARGET_AWS_REGION}")

# Declare the constants
SOURCE_REPOSITORY_URL="public.ecr.aws/${SOURCE_REGISTRY_ALIAS}/${SOURCE_REPOSITORY}"
TARGET_REPOSITORY_URL="${TARGET_AWS_ACCOUNT}.dkr.ecr.${TARGET_AWS_REGION}.${image_endpoint}/${TARGET_REPOSITORY}"

# Authenticate to ECR of target repository.
# Since out sync-task workflows would only target regional ECR, we are explicitly logging into the same.
aws ecr get-login-password --region "${TARGET_AWS_REGION}" | docker login --username AWS --password-stdin "${TARGET_REPOSITORY_URL}"

echo "Verifying if the images need to be synced in: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}"

# Obtain the source image and expected image url.
LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_SOURCE="${SOURCE_REPOSITORY_URL}:windowsservercore-latest"
LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_TARGET="${TARGET_REPOSITORY_URL}:windowsservercore-latest"

# Compare manifests for both and determine if sync is required.
compare_image_manifests "${LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_SOURCE}" "${LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_TARGET}"
if [ $? = 1 ]; then
  echo "true" > SYNC_IMAGES
  echo "Images need to be synced in: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}"
else
  echo "false" > SYNC_IMAGES
  echo "Images are already in sync: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}"
fi


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -euo pipefail

#############################################################################################################
# Start of the script
#############################################################################################################

# Source the common methods
source ./common_windows.sh
# Get the regional endpoint variable
image_endpoint=$(get_regional_image_endpoint "${AWS_REGION}")

#############################################################################################################
# For regional ECR, we create the specific image URL here. Additionally, we also authenticate to regional ECR.
#############################################################################################################
if [[ $TARGET_REGISTRY == "private-ecr" ]]; then
  # Create Repository url specific for regional ECR.
  REGISTRY="${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.${image_endpoint}"
  REPOSITORY_PATH="${REGISTRY}/${REPOSITORY}"

  # Authenticate to ECR.
  aws ecr get-login-password --region "${AWS_REGION}" | docker login --username AWS --password-stdin "${REGISTRY}"

#############################################################################################################
# For public ECR, we create the specific image URL here.
#############################################################################################################
elif [[ $TARGET_REGISTRY == "public-ecr" ]]; then
  REGISTRY="public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}"
  REPOSITORY_PATH="${REGISTRY}/${REPOSITORY}"

#############################################################################################################
# For dockerhub, we create the specific image URL here.
#############################################################################################################
elif [[ $TARGET_REGISTRY == "dockerhub" ]]; then
  REPOSITORY_PATH="${REPOSITORY}"
fi

#############################################################################################################
# For "verify-images" action, we will verify that the image manifest exists for all the supported versions
# in the target registry. We will also verify the latest image and compare the image digests for the same.
#############################################################################################################
if [[ $ACTION == "verify-images" ]]; then
  # Validate that manifest exists for all the versions.
  while read -r version; do
    check_image_manifest_exists "${REPOSITORY_PATH}:${version}-windowsservercore"
  done <<< "$(echo "${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}")"

  # Validate that latest manifest is same as the required version.
  LATEST_IMAGE_URI_WITH_VERSION_TAG="${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-windowsservercore"
  LATEST_IMAGE_URI_WITH_LATEST_TAG="${REPOSITORY_PATH}:windowsservercore-latest"
  compare_image_manifests "${LATEST_IMAGE_URI_WITH_LATEST_TAG}" "${LATEST_IMAGE_URI_WITH_VERSION_TAG}"

#############################################################################################################
# Any action not matching above is unsupported.
#############################################################################################################
else
  echo "Unsupported action: ${ACTION}"
  exit 1
fi


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

set -euo pipefail

#############################################################################################################
# This script would be executed from a codebuild project which would set the following environment variables-
# ACTION -> Action to perform. Can be amongst "verify-ssm-parameter"
# SSM_PARAM_NAMESPACE -> The SSM Parameter namespace to be used.
# ACCOUNT_ID -> Account ID where the images are present.
# REGIONS_TO_PUBLISH -> A comma separated list of regions where we need to publish SSM parameter.
#############################################################################################################

#############################################################################################################
# Helper methods to verify the SSM Parameter.
#############################################################################################################

# Verifies that the given param tag has the expected image in the given region and account.
verify_ssm_param(){
  local ssm_parameter region version param_name
  region=${1}
  version=${2}
  param_tag=${3}

  # Get the regional endpoint variable
  image_endpoint=$(get_regional_image_endpoint "${region}")

  # Get the parameter name and the expected parameter value.
  param_name="${SSM_PARAM_NAMESPACE}/${param_tag}"
  expected_param_value="${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${version}-windowsservercore"

  echo "Verifying ${param_name} in ${region} region. Expected value: ${expected_param_value}"
  ssm_parameter=$(aws ssm get-parameter --name "${param_name}" --region "${region}" || echo "1")
  # If SSM Parameter is present then find the old value.
  if [ "$ssm_parameter" != 1 ]; then
    current_param_value=$(echo $ssm_parameter | jq -r '.Parameter.Value')
  fi

  # If the latest parameter is not present, or is different then we exit with failure code.
  if [[ "$current_param_value" == "$expected_param_value" ]]; then
    echo "SSM parameter ${param_name} in ${region} region matches the expected value"
  else
    echo "SSM parameter verification of ${param_name} in ${region} region failed. Actual: ${current_param_value} : Expected: ${expected_param_value}"
    exit 1
  fi
}

#############################################################################################################
# Start of the script
#############################################################################################################

# Source the common methods
source ./common_windows.sh

#############################################################################################################
# If action is "verify-ssm-parameter" then verify that SSM parameter for each supported version is present.
#############################################################################################################
if [[ $ACTION == "verify-ssm-parameter" ]]; then
  echo "Verifying the SSM parameter for Windows images in region: ${REGIONS_TO_PUBLISH}"

  # Split the comma separated list of regions into an array
  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\n/g'`)
  for region in "${REGIONS[@]}"
  do
    # For a given region, iterate over all supported versions and verify the SSM parameters.
    while read -r version; do
        verify_ssm_param "${region}" "${version}" "${version}-windowsservercore"
    done <<< "$(echo "${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}")"

    # Finally, verify the SSM param for latest as well as Dockerhub version.
    verify_ssm_param "${region}" "${AWS_FOR_FLUENT_BIT_LATEST_VERSION}" "windowsservercore-latest"
    verify_ssm_param "${region}" "${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}" "${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}-windowsservercore"
    verify_ssm_param "${region}" "${AWS_FOR_FLUENT_BIT_LATEST_VERSION}" "windowsservercore-latest"
  done

#############################################################################################################
# Any action not matching above is unsupported.
#############################################################################################################
else
  echo "Unsupported action: ${ACTION}"
  exit 1
fi


#!/bin/bash

# Arguments:
# $1 = number log lines to write at a time
# $2 = sleep time between writes

while [ true ]
do
    /go/bin/flog -t stdout -f apache_common -n ${1}
    sleep ${2}
done


for i in `seq 1 100`;
do
  echo "2.1.0.1 - TheDoctor 000 [$(date)] \"POST /cestlavie\" 000 $i"
  sleep 1
done


args=""

for plugin in ./.vscode/external-plugins/*; do
    for entry in "$plugin"/bin/*; do
        [[ $entry == *.so ]] && args="${args} -e ${entry}"
    done
done

echo "$args"


#!/bin/bash

# Rebuild External Plugins (on Change)
# For VSCode Fluent-Bit
# The following detects changes to the following
# watched directories and files, and will initiate a
# rebuild on modification.
watch='*' # Watch all changes in the external plugin folder

cd "./.vscode/external-plugins"

for plugin in */; do
    # Step into plugin folder
    cd $plugin;

    # Keep a record of the latest update
    # prior to the last build
    mkdir -p bin/
    memoryFile="./bin/.latestchange"
    [ -f $memoryFile ] || touch $memoryFile
    lts1=`cat $memoryFile`
    if uname | grep -q "Darwin"; then
        lts2=`find $watch -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f 1 -d " "`
    else
        lts2=`find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1`
    fi
    if [[ $lts1 != $lts2 ]] ; then
        # Rebuild
        make
        # Make could modify files, so save a fresh timestamp
        if uname | grep -q "Darwin"; then
            echo `find $watch -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f 1 -d " "` > $memoryFile
        else
            echo `find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1 | cut -f 1 -d " "` > $memoryFile
        fi
    fi

    # Step out of plugin folder
    cd ..
done

cd "../../"


#!/bin/bash

# Rebuild (on Change)
# For VSCode Fluent-Bit
# The following detects changes to the following
# watched directories and files, and will initiate a
# rebuild on modification.
watch='src/ plugins/'

# Kill old fluent-bit processes (might not be the best place for this)
kill -9 $(pgrep fluent-bit)

# OpenSSL Key Export
# export SSLKEYLOGFILE=/Users/falamatt/fluentbit-premaster
# export LD_PRELOAD=.vscode/Scripts/libsslkeylog.so
LD_PRELOAD=""

# Keep a record of the latest update
# prior to the last build
memoryFile="./.vscode/Scripts/.latestchange"
[ -f $memoryFile ] || touch $memoryFile
lts1=`cat $memoryFile`
if uname | grep -q "Darwin"; then
    lts2=`find $watch -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f 1 -d " "`
else
    lts2=`find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1`
fi

if [[ $lts1 != $lts2 ]] ; then
    # Rebuild
    cd build
    cmake -DFLB_DEV=On ../
    make
    cd ..
    # Make could modify files, so save a fresh timestamp
    if uname | grep -q "Darwin"; then
        echo `find $watch -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f 1 -d " "` > $memoryFile
    else
        echo `find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1 | cut -f 1 -d " "` > $memoryFile
    fi
fi


#!/bin/bash

# Writes 500 log lines per second

while :
do
    for i in {0..${LOGGER_RATE}}
    do
        openssl rand -base64 ${LOG_SIZE}
    done
    sleep 1
done


# Usage: Set the following env vars:
#
# STDOUT_LOGGER_RATE => logs per second to send to stdout
# FILE1_LOGGER_RATE => logs per second to send to /tail/file1.log$(date "+%Y-%m-%d-%H-%M-%S")
# TCP_LOGGER_RATE => logs per second to send to TCP_LOGGER_PORT
# TCP_LOGGER_PORT => TCP port of TCP input in Fluent Bit, if used
#
# If you do not need one of these loggers, simply remove its entry from the loop
#
# you can easily configure additional loggers as needed
# just add another entry in the while loop
# and import the new file in the Dockerfile

while true
do
    for i in {1..$TCP_LOGGER_RATE}
    do
        cat /tcp.log | nc 127.0.0.1 $TCP_LOGGER_PORT
    done
    for i in {1..$STDOUT_LOGGER_RATE}
    do
        cat /stdout.log
    done
    for i in {1..$FILE1_LOGGER_RATE}
    do
        # this sets up automatic rotation of the active file based on the date
        # automatic log file clean up is not currently in this image
        cat /file1.log >>  /tail/file1.log$(date "+%Y-%m-%d-%H")
    done
    sleep 1
done


while true
do
   cat example.log >> app.log
   sleep 1
done


read_line_by_line() {
    while IFS= read -r line; do
        echo "$line" | nc 127.0.0.1 $2
        sleep 1
    done < "$1"
}

while true
do
    read_line_by_line $1 $2
    sleep 1
done


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

debug=0

function usage {
  echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]"
}

function help {
  info_msg "$script_name"
  info_msg " "
  info_msg "Sets up the environment for AWS FPGA HDK tools."
  info_msg " "
  info_msg "hdk_setup.sh script will:"
  info_msg "  (1) Check if Xilinx Vivado is installed,"
  info_msg "  (2) Set up key environment variables HDK_*, and"
  info_msg "  (3) Download/update the HDK shell's checkpoint"
  info_msg "  (4) Prepare DRAM controller and PCIe IP modules if they are not already available in your directory."
  echo " "
  usage
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
  arg=${args[$i]}
  case $arg in
    -d|-debug)
      debug=1
    ;;
    -h|-help)
      help
      return 0
    ;;
    *)
      err_msg "Invalid option: $arg\n"
      usage
      return 1
  esac
done

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh

hdk_shell_version=$(readlink $HDK_COMMON_DIR/shell_stable)

debug_msg "Checking for Vivado install:"

# before going too far make sure Vivado is available
if ! exists vivado; then
    err_msg "Please install/enable Vivado."
    err_msg "  If you are using the FPGA Developer AMI then please request support."
    return 1
fi

# Install any patches as required
info_msg "Setting up Vivado patches if required."
setup_patches

#Searching for Vivado version and comparing it with the list of supported versions

export VIVADO_VER=`vivado -version | grep Vivado | head -1`

info_msg "Using $VIVADO_VER"

if grep -Fxq "$VIVADO_VER" $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt
then
    debug_msg "$VIVADO_VER is supported by this HDK release."
else
    err_msg "$VIVADO_VER is not supported by this HDK release."
    err_msg "Supported versions are:"
    cat $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt
    return 1
fi

VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::'`
export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:7}
echo "VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION"

debug_msg "Vivado check succeeded"

# The CL_DIR is where the actual Custom Logic design resides. The developer is expected to override this.
# export CL_DIR=$HDK_DIR/cl/developer_designs

debug_msg "Done setting environment variables.";

# Download correct shell DCP
info_msg "Using HDK shell version $hdk_shell_version"
debug_msg "Checking HDK shell's checkpoint version"
hdk_resources_s3_bucket=aws-fpga-hdk-resources

# Shell files to be downloaded
declare -a s3_hdk_files=("SH_CL_BB_routed.dcp"
                         "cl_hello_world.debug_probes.ltx"
                         "cl_dram_dma.debug_probes.ltx"
                        )
# Downloading the shell files
for shell_file in "${s3_hdk_files[@]}"
do
  # Determine if shell or debug probe
  if [ $shell_file == "SH_CL_BB_routed.dcp" ]; then
    sub_dir="checkpoints"
  else
    sub_dir="debug_probes"
  fi
  hdk_shell_dir=$HDK_SHELL_DIR/build/$sub_dir/from_aws
  hdk_file=$hdk_shell_dir/$shell_file
  s3_shell_dir=hdk/$hdk_shell_version/build/$sub_dir/from_aws
  # Download the sha256
  if [ ! -e $hdk_shell_dir ]; then
      mkdir -p $hdk_shell_dir || { err_msg "Failed to create $hdk_shell_dir"; return 2; }
  fi
  # Use curl instead of AWS CLI so that credentials aren't required.
  debug_msg "curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256"
  curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256 || { err_msg "Failed to download HDK shell's $shell_file version from $s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256"; return 2; }
  if grep -q '<?xml version' $hdk_file.sha256; then
    err_msg "Failed to download HDK shell's $shell_file version from $s3_shell_dir/$shell_file.sha256"
    cat $hdk_file.sha256
    return 2
  fi
  exp_sha256=$(cat $hdk_file.sha256)
  debug_msg "  $shell_file latest   version=$exp_sha256"
  # If shell file already downloaded check its sha256
  if [ -e $hdk_file ]; then
    act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )
    debug_msg "  $shell_file existing version=$act_sha256"
    if [[ $act_sha256 != $exp_sha256 ]]; then
      info_msg "HDK shell's $shell_file version is incorrect"
      info_msg "  Saving old file to $hdk_file.back"
      mv $hdk_file $hdk_file.back
    fi
  else
    info_msg "HDK shell's $shell_file hasn't been downloaded yet."
  fi
  if [ ! -e $hdk_file ]; then
    info_msg "Downloading latest HDK shell $shell_file from $s3_shell_dir/$shell_file"
    # Use curl instead of AWS CLI so that credentials aren't required.
    curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file -o $hdk_file || { err_msg "HDK shell checkpoint download failed"; return 2; }
  fi

  # Check sha256
  act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )
  if [[ $act_sha256 != $exp_sha256 ]]; then
    err_msg "Incorrect HDK shell checkpoint version:"
    err_msg "  expected version=$exp_sha256"
    err_msg "  actual   version=$act_sha256"
    err_msg "  There may be an issue with the uploaded checkpoint or the download failed."
    return 2
  fi
  info_msg "HDK shell is up-to-date"
done

# Create DDR and PCIe IP models and patch PCIe
models_dir=$HDK_COMMON_DIR/verif/models
ddr4_model_dir=$models_dir/ddr4_model
if [ -f $ddr4_model_dir/arch_defines.v ]; then
  # Models already built
  # Check to make sure they were built with this version of vivado
  if [[ -f $models_dir/.vivado_version ]]; then
    models_vivado_version=$(cat $models_dir/.vivado_version)
    info_msg "DDR4 model files in $ddr4_model_dir/ were built with $models_vivado_version"
    if [[ $models_vivado_version != $VIVADO_VER ]]; then
      info_msg "  Wrong vivado version so rebuilding with $VIVADO_VER"
    fi
  else
    models_vivado_version=UNKNOWN
    info_msg "DDR4 model files in $ddr4_model_dir/ were built with UNKNOWN Vivado version so rebuilding."
  fi
else
  # Models haven't been built
  models_vivado_version=NOT_BUILT
  info_msg "DDR4 model files in "$ddr4_model_dir/" do NOT exist. Running model creation step.";
fi
if [[ $models_vivado_version != $VIVADO_VER ]] && [ ! -e $models_dir/build.lock ]; then
  rm -rf $HDK_COMMON_DIR/verif/scripts/.done 2>&1 >/dev/null
fi
ddr4_build_dir=$HDK_COMMON_DIR/verif/scripts/tmp
if [ -d $ddr4_build_dir ] && [ ! -e $models_dir/build.lock ]; then rm -rf $ddr4_build_dir; fi
if ! make -s -C $HDK_DIR/common/verif/scripts MODEL_DIR=$models_dir; then
  err_msg "  build dir=$ddr4_build_dir"
  return 2
fi

if [[ ":$CL_DIR" == ':' ]]; then
  info_msg "attention: don't forget to set the CL_DIR variable for the directory of your custom logic.";
else
  info_msg "CL_DIR is $CL_DIR"
  if [ ! -d $CL_DIR ]; then
    err_msg "CL_DIR doesn't exist. set CL_DIR to a valid directory."
    unset CL_DIR
  fi
fi

cd $current_dir

info_msg "AWS HDK setup PASSED.";


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.