#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

# compress static assets

set -o errexit
set -o nounset
set -o pipefail

cd prometheus/web/ui
cp embed.go.tmpl embed.go

# We run gzip with the following flags:
# -f overwrite of output file and compress links;
# -k keeps input files;
# -n drops the original name and timestamp so that the embeded assets
# generate deterministic checksums.
GZIP_OPTS="-fkn"
# gzip option '-k' may not always exist in the latest gzip available on different distros.
if ! gzip -k -h &>/dev/null; then GZIP_OPTS="-fn"; fi

find static -type f -name '*.gz' -delete
find static -type f -exec gzip $GZIP_OPTS '{}' \; -print0 | xargs -0 -I % echo %.gz | xargs echo //go:embed >> embed.go
echo var EmbedFS embed.FS >> embed.go


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

TAR=tar
if [ "$(uname -s)" = "Darwin" ]; then
    TAR=gtar
fi

rm -f "prometheus/npm_licenses.tar.bz2"
find prometheus/web/ui/node_modules -iname "license*" | $TAR cfj "prometheus/npm_licenses.tar.bz2" --transform 's/^/npm_licenses\//' --files-from=-


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o pipefail

REPO="$1"
OUTPUT_DIR="$2"
ARTIFACTS_PATH="$3"
TAG="$4"
IMAGE_REPO="$5"
IMAGE_TAG="$6"

MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${MAKE_ROOT}/../../../build/lib/common.sh"

cd $REPO

make release \
  RELEASE_DIR="out" \
  REGISTRY=${IMAGE_REPO} \
  TAG=${IMAGE_TAG}

mkdir -p $OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG
cp out/cluster-template.yaml "$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG"
cp out/infrastructure-components.yaml "$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG"

cp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o pipefail

REPO="$1"
OUTPUT_DIR="$2"
ARTIFACTS_PATH="$3"
TAG="$4"
GOLANG_VERSION="$5"

MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${MAKE_ROOT}/../../../build/lib/common.sh"

build::common::use_go_version ${GOLANG_VERSION}

cd $REPO

make release-manifests \
  RELEASE_DIR="out" \

mkdir -p $OUTPUT_DIR/manifests/infrastructure-rufio/$TAG
cp out/manifest.yaml "$OUTPUT_DIR/manifests/infrastructure-rufio/$TAG"

cp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o pipefail

REPO="$1"
ARTIFACTS_PATH="$2"
IMAGE_REPO="$3"
TINK_SERVER_IMAGE_COMPONENT="$4"
TINK_CONTROLLER_IMAGE_COMPONENT="$5"
IMAGE_TAG="$6"
GOLANG_VERSION="$7"

MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${MAKE_ROOT}/../../../build/lib/common.sh"

build::common::use_go_version ${GOLANG_VERSION}

cd $REPO

npm install prettier --global

make release-manifests \
  TINK_SERVER_IMAGE=${IMAGE_REPO}/${TINK_SERVER_IMAGE_COMPONENT} \
  TINK_CONTROLLER_IMAGE=${IMAGE_REPO}/${TINK_CONTROLLER_IMAGE_COMPONENT} \
  TINK_SERVER_TAG=${IMAGE_TAG} \
  TINK_CONTROLLER_TAG=${IMAGE_TAG}

cp out/release/tink.yaml $ARTIFACTS_PATH


#!/usr/bin/env bash
set -e

<<COMMENT
go mod init
go mod vendor -v
COMMENT

go mod init || true
go mod tidy -v


#!/usr/bin/env bash

# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

# Common functions used by various build scripts. To use these
# functions, source this file, e.g.:
#    . <path-to-this-file>/common.sh

# awsAuth echoes an AWS ECR password
function awsAuth () {
    local repo=${1?:no repo specified}
    local awsCmd="ecr"
    local region="--region=us-west-2"

    if [[ $repo =~ "public.ecr.aws" ]]; then
        awsCmd="ecr-public"
        region="--region=us-east-1"
    fi

    aws "$awsCmd" "$region" "--profile=${PROFILE:-}" get-login-password
}

function generate () {
    local version=$1
    local stage=$2
    local kms_key=signingPackagesKey

    cd "${BASE_DIRECTORY}/generatebundlefile"
    ./bin/generatebundlefile --input "./data/bundles_${stage}/${version}.yaml" \
                 --key alias/${kms_key} \
                 --output "output-${version}"
}

function regionCheck () {
    local version=$1
    cd "${BASE_DIRECTORY}/generatebundlefile"
    ./bin/generatebundlefile --bundle "output-${version}/bundle.yaml" \
                --region-check true || true
}

function push () {
    local version=${1?:no version specified}
    cd "${BASE_DIRECTORY}/generatebundlefile/output-${version}"
    awsAuth "$REPO" | "$ORAS_BIN" login "$REPO" --username AWS --password-stdin
    removeBundleMetadata bundle.yaml
    if "$ORAS_BIN" pull "${REPO}:v${version}-latest" -o ${version}; then
        removeBundleMetadata ${version}/bundle.yaml
    else
        mkdir -p ${version} && touch ${version}/bundle.yaml.stripped
    fi

    if (git diff --no-index --quiet -- ${version}/bundle.yaml.stripped bundle.yaml.stripped) then
        echo "bundle contents are identical skipping bundle push for ${version}"
    else
        "$ORAS_BIN" push "${REPO}:v${version}-${CODEBUILD_BUILD_NUMBER}" bundle.yaml
        "$ORAS_BIN" push "${REPO}:v${version}-latest" bundle.yaml
    fi
}

function removeBundleMetadata () {
    local bundle=${1?:no bundle specified}
    yq 'del(.metadata.name)' ${bundle} > ${bundle}.strippedname
    yq 'del(.metadata.annotations)' ${bundle}.strippedname > ${bundle}.stripped
}


#!/usr/bin/env bash

# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

# Generate bundle files for supported kubernetes versions.

set -euxo pipefail

export LANG=C.UTF-8

BASE_DIRECTORY=$(git rev-parse --show-toplevel)
. "${BASE_DIRECTORY}/generatebundlefile/hack/common.sh"
ECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries \
                 --query 'registries[*].registryUri' --output text)
REPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles
ORAS_BIN=${BASE_DIRECTORY}/bin/oras

if [ ! -x "${ORAS_BIN}" ]; then
    make oras-install
fi

make build
chmod +x ${BASE_DIRECTORY}/generatebundlefile/bin

for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    generate ${version} "dev"
    push ${version}
done


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -e
set -x
set -o pipefail

export LANG=C.UTF-8

BASE_DIRECTORY=$(git rev-parse --show-toplevel)
HELM_REPO=${HELM_REPO}
echo ${HELM_REPO}

make build
chmod +x ${BASE_DIRECTORY}/generatebundlefile/bin

AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
aws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com
aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

cd "${BASE_DIRECTORY}/generatebundlefile"

if [[ -n "${PROMOTE_FILE}" ]]; then
    if [[ "${HELM_REPO}" == "eks-anywhere-packages" ]]; then
        # We need to copy the images for the packages helm chart, but no other packages.
        ./bin/generatebundlefile  \
            --promote ${HELM_REPO} --input ${PROMOTE_FILE} --copy-images
    else
        ./bin/generatebundlefile  \
            --promote ${HELM_REPO} --input ${PROMOTE_FILE}
    fi
else
    ./bin/generatebundlefile  \
        --promote ${HELM_REPO}
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

#!/usr/bin/env bash

###################

# This file is NOT meant to be run as a script, or in CI. It's for useful commands when developing/testing generatebundle.

####################

set -e

export local_ecr_public="public.ecr.aws/f5b7k4z5"

function repoExists () {
    aws ecr-public describe-repositories \
        | jq -r ".repositories[].repositoryName" \
        | grep -q "^$1\$"
}

REPO_1=hello-eks-anywhere
REPO_2=eks-anywhere-packages
if ! repoExists ${REPO_1}; then
      aws ecr-public  create-repository --repository-name ${REPO_1}
fi

if ! repoExists ${REPO_2}; then
      aws ecr-public create-repository --repository-name ${REPO_2}
fi

#############
### ECR Logins
#############

export HELM_EXPERIMENTAL_OCI=1
aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws
aws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin 646717423341.dkr.ecr.us-west-2.amazonaws.com

################################################
# Populate Test cases for generateBundle
# TODO replace version this with an upstream version from the dev Account once it's published.
#################################################

helm pull oci://646717423341.dkr.ecr.us-west-2.amazonaws.com/hello-eks-anywhere --version 0.1.0+c4e25cb42e9bb88d2b8c2abfbde9f10ade39b214
helm push hello-eks-anywhere-0.1.0+c4e25cb42e9bb88d2b8c2abfbde9f10ade39b214.tgz "oci://$local_ecr_public"

########################
# Oras examples
#########################

# Manually push a local bundle
cd output/
oras push public.ecr.aws/f5b7k4z5/eks-anywhere-packages-bundles:v1.0.0-bundle bundle-1.20.yaml

# Pull latest bundle
oras pull public.ecr.aws/f5b7k4z5/eks-anywhere-packages-bundles:v1

########################
# Hack to Simulate Codebuild jobs locally, Run Builder-base test of promo/signing flags
########################

go mod vendor
docker run -d -v ${HOME}/.aws/credentials:/root/.aws/credentials:ro -v ${HOME}/go/src/github.com/modelrocket/eks-anywhere-packages:/go/src/github.com/aws/modelrocket/eks-anywhere-packages public.ecr.aws/eks-distro-build-tooling/builder-base:latest  tail -f /dev/null
docker ps
docker exec -it <CONTAINER_ID> /bin/bash
cd eks-anywhere-packages/
./generatebundlefile/hack/setup.sh

# Change the `make build` command to use vendor

build: ## Build release binary.
	mkdir -p $(REPO_ROOT)/generatebundlefile/bin
	$(GO) build -mod vendor -o $(REPO_ROOT)/generatebundlefile/bin/generatebundlefile *.go


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -e
set -x
set -o pipefail

export LANG=C.UTF-8

BASE_AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

cat << EOF > configfile
[default]
region=us-west-2
account=$BASE_AWS_ACCOUNT_ID
output=json

[profile packages]
role_arn=$PACKAGES_ARTIFACT_DEPLOYMENT_ROLE
region=us-west-2
credential_source=EcsContainer
EOF

# Release Package Images to Packages Artifact account
export CODEBUILD_BUILD_NUMBER=$(($CODEBUILD_BUILD_NUMBER+110))
BASE_DIRECTORY=$(git rev-parse --show-toplevel)
export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile
export PROFILE=packages
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
. "${BASE_DIRECTORY}/generatebundlefile/hack/common.sh"
ORAS_BIN=${BASE_DIRECTORY}/bin/oras

make build
chmod +x ${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile

aws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com
aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \
    --input ${BASE_DIRECTORY}/generatebundlefile/data/prod_artifact_move.yaml \
    --private-profile ${PROFILE}

# Release Helm Chart, and bundle to Production account
cat << EOF > prodconfigfile
[default]
region=us-west-2
account=$BASE_AWS_ACCOUNT_ID
output=json

[profile prod]
role_arn=$ARTIFACT_DEPLOYMENT_ROLE
region=us-east-1
credential_source=EcsContainer
EOF

export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/prodconfigfile
export PROFILE=prod
. "${BASE_DIRECTORY}/generatebundlefile/hack/common.sh"
ECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries --profile ${PROFILE} --query 'registries[*].registryUri' --output text)
REPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles

aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

# Move Helm charts within the bundle to another account
${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \
    --input ${BASE_DIRECTORY}/generatebundlefile/data/prod_artifact_move.yaml \
    --public-profile ${PROFILE}

if [ ! -x "${ORAS_BIN}" ]; then
    make oras-install
fi

export AWS_PROFILE=prod
export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/prodconfigfile
for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    generate ${version} "prod"
done

aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    push ${version}
done


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -e
set -x
set -o pipefail

export LANG=C.UTF-8

BASE_AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

cat << EOF > configfile
[default]
region=us-west-2
account=$BASE_AWS_ACCOUNT_ID
output=json

[profile packages]
role_arn=$PACKAGES_ARTIFACT_DEPLOYMENT_ROLE
region=us-west-2
credential_source=EcsContainer
EOF

# Release Package Images to Packages Artifact account
BASE_DIRECTORY=$(git rev-parse --show-toplevel)
export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile
export PROFILE=packages
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
. "${BASE_DIRECTORY}/generatebundlefile/hack/common.sh"
ORAS_BIN=${BASE_DIRECTORY}/bin/oras

make build
chmod +x ${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile

aws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com
aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

# Move Helm Images within the bundle to Private ECR
${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \
    --input ${BASE_DIRECTORY}/generatebundlefile/data/staging_artifact_move.yaml \
    --private-profile ${PROFILE}

# Release Helm Chart, and bundle to Staging account
cat << EOF > stagingconfigfile
[default]
region=us-west-2
account=$BASE_AWS_ACCOUNT_ID
output=json

[profile staging]
role_arn=$ARTIFACT_DEPLOYMENT_ROLE
region=us-east-1
credential_source=EcsContainer
EOF

export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/stagingconfigfile
export PROFILE=staging
. "${BASE_DIRECTORY}/generatebundlefile/hack/common.sh"
ECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries --profile ${PROFILE} --query 'registries[*].registryUri' --output text)
REPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles

aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws

# Move Helm charts within the bundle to Public ECR
${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \
    --input ${BASE_DIRECTORY}/generatebundlefile/data/staging_artifact_move.yaml \
    --public-profile ${PROFILE}

if [ ! -x "${ORAS_BIN}" ]; then
    make oras-install
fi

# Generate Bundles from Public ECR
export AWS_PROFILE=staging
export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/stagingconfigfile
for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    generate ${version} "staging"
done

# Push Bundles to Public ECR
aws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws
for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    push ${version}
done

# Check images from Bundle in Private ECR
export AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile
export AWS_PROFILE=packages
for version in 1-22 1-23 1-24 1-25 1-26 1-27; do
    regionCheck ${version}
done


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -e
set -o pipefail

# More Information about the Docker Cred Helper https://github.com/docker/docker-credential-helpers
# ECR credential helper automatically uses the same credentials as the AWS CLI and the AWS SDKs
# to first retrieve an ECR authentication token for each account for secure access to repositories,
# then lets the Docker daemon use this token when familiar Docker commands such as docker push or docker pull
if [ ! -d "/root/.docker" ]; then
    mkdir -p /root/.docker
fi

if [ ! -d "/root/.config/containers" ]; then
    mkdir -p /root/.config/containers
fi

mv generatebundlefile/hack/policy.json /root/.config/containers/policy.json
mv generatebundlefile/hack/docker-ecr-config.json /root/.docker/config.json
git config --global credential.helper '!aws codecommit credential-helper $@'
git config --global credential.UseHttpPath true


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o nounset
set -o pipefail

ROOT_DIR="$(git rev-parse --show-toplevel)"

cd ${ROOT_DIR}
./bin/kustomize build config/crd > charts/eks-anywhere-packages/crds/crd.yaml
./bin/kustomize build config/crd > charts/eks-anywhere-packages-crds/templates/crd.yaml

cd charts
helm lint eks-anywhere-packages
OUTDIR=_output
rm -rf $OUTDIR
mkdir $OUTDIR
cp -r eks-anywhere-packages $OUTDIR
EKS_ANYWHERE_PACKAGES_TAG=$(cat image-tags/eks-anywhere-packages)
sed \
        -e "s,{{eks-anywhere-packages}},${EKS_ANYWHERE_PACKAGES_TAG}," \
        eks-anywhere-packages/values.yaml >${OUTDIR}/eks-anywhere-packages/values.yaml
cd $OUTDIR
RESULT=$(helm package eks-anywhere-packages| sed -e 's/Successfully packaged chart and saved it to: //g')
echo "helm install eks-anywhere-packages ${RESULT}"


#!/usr/bin/env bash
yq () {
  local file=$1
  local query=$2
  local params=$3
  docker run --rm -i --entrypoint yq linuxserver/yq ${params} -rc "${query}" <${file}
}
file=$1
tmpfile=$(mktemp ${file}.digest.XXXXXX)
alwaysexcludes='.metadata.annotations."eksa.aws.com/signature"'
has_excludes=$(yq "${file}" '.metadata.annotations."eksa.aws.com/excludes"')

excludes=""
if [ "${has_excludes}" != "null" ]; then
    excludes=$(yq "${file}" '.metadata.annotations."eksa.aws.com/excludes"' | base64 -d | cat <(echo ${alwaysexcludes}) - | paste -sd "," -)
fi
yq ${file} "del(${alwaysexcludes}$([ ! -z ${excludes} ] && echo , ${excludes})) | walk( if type == \"object\" then with_entries(select(.value != \"\" and .value != null and .value != [])) else . end)" "--indentless-lists -Y -S" | openssl dgst -sha256 -binary >${tmpfile}
signature=$(openssl pkeyutl -inkey pkg/signature/testdata/private.ec.key -sign -in ${tmpfile} | base64 | tr -d '\n')
yq "${file}" ".metadata.annotations.\"eksa.aws.com/signature\" = \"${signature}\"" -Y > "${file}.signed"
cat ${tmpfile} | base64 | tr -d '\n' > ${file}.digest
rm -f ${tmpfile}


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

function build::common::ensure_tar() {
  if [[ -n "${TAR:-}" ]]; then
    return
  fi

  # Find gnu tar if it is available, bomb out if not.
  TAR=tar
  if which gtar &>/dev/null; then
      TAR=gtar
  elif which gnutar &>/dev/null; then
      TAR=gnutar
  fi
  if ! "${TAR}" --version | grep -q GNU; then
    echo "  !!! Cannot find GNU tar. Build on Linux or install GNU tar"
    echo "      on Mac OS X (brew install gnu-tar)."
    return 1
  fi
}

# Build a release tarball.  $1 is the output tar name.  $2 is the base directory
# of the files to be packaged.  This assumes that ${2}/kubernetes is what is
# being packaged.
function build::common::create_tarball() {
  build::common::ensure_tar

  local -r tarfile=$1
  local -r stagingdir=$2
  local -r repository=$3

  "${TAR}" czf "${tarfile}" -C "${stagingdir}" $repository --owner=0 --group=0
}

# Generate shasum of tarballs. $1 is the directory of the tarballs.
function build::common::generate_shasum() {

  local -r tarpath=$1

  echo "Writing artifact hashes to shasum files..."

  if [ ! -d "$tarpath" ]; then
    echo "  Unable to find tar directory $tarpath"
    exit 1
  fi

  cd $tarpath
  for file in $(find . -name '*.tar.gz'); do
    filepath=$(basename $file)
    sha256sum "$filepath" > "$file.sha256"
    sha512sum "$filepath" > "$file.sha512"
  done
  cd -
}

function build::common::upload_artifacts() {
  local -r artifactspath=$1
  local -r artifactsbucket=$2
  local -r projectpath=$3
  local -r buildidentifier=$4
  local -r githash=$5
  local -r latestpath=$6

  echo "$githash" >> "$artifactspath"/githash

  # Upload artifacts to s3
  # 1. To proper path on s3 with buildId-githash
  # 2. Latest path to indicate the latest build, with --delete option to delete stale files in the dest path
  aws s3 sync "$artifactspath" "$artifactsbucket"/"$projectpath"/"$buildidentifier"-"$githash"/artifacts --acl public-read
  aws s3 sync "$artifactspath" "$artifactsbucket"/"$projectpath"/"$latestpath" --delete --acl public-read
}

function build::gather_licenses() {
  # force 1.18 since thats the version used to install go-licenses in builder-base
  build::common::use_go_version 1.18
  if ! command -v go-licenses &> /dev/null
  then
    echo " go-licenses not found.  If you need license or attribtuion file handling"
    echo " please refer to the doc in docs/development/attribution-files.md"
    exit
  fi

  local -r outputdir=$1
  local -r patterns=$2

  # Force deps to only be pulled form vendor directories
  # this is important in a couple cases where license files
  # have to be manually created
  export GOFLAGS=-mod=vendor
  # force platform to be linux to ensure all deps are picked up
  export GOOS=linux
  export GOARCH=amd64

  mkdir -p "${outputdir}/attribution"
  # attribution file generated uses the output go-deps and go-license to gather the neccessary
  # data about each dependency to generate the amazon approved attribution.txt files
  # go-deps is needed for module versions
  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns
  go list -deps=true -json ./... | jq -s ''  > "${outputdir}/attribution/go-deps.json"

  go-licenses save --force $patterns --save_path="${outputdir}/LICENSES"

  # go-licenses can be a bit noisy with its output and lot of it can be confusing
  # the following messags are safe to ignore since we do not need the license url for our process
  NOISY_MESSAGES="cannot determine URL for|Error discovering URL|unsupported package host"
  go-licenses csv $patterns > "${outputdir}/attribution/go-license.csv" 2>  >(grep -vE "$NOISY_MESSAGES" >&2)

  if cat "${outputdir}/attribution/go-license.csv" | grep -q "^vendor\/golang.org\/x"; then
      echo " go-licenses created a file with a std golang package (golang.org/x/*)"
      echo " prefixed with vendor/.  This most likely will result in an error"
      echo " when generating the attribution file and is probably due to"
      echo " to a version mismatch between the current version of go "
      echo " and the version of go that was used to build go-licenses"
      exit 1
  fi

  if cat "${outputdir}/attribution/go-license.csv" | grep -e ",LGPL-" -e ",GPL-"; then
    echo " one of the dependencies is licensed as LGPL or GPL"
    echo " which is prohibited at Amazon"
    echo " please look into removing the dependency"
  fi

  # go-license is pretty eager to copy src for certain license types
  # when it does, it applies strange permissions to the copied files
  # which makes deleting them later awkward
  # this behavior may change in the future with the following PR
  # https://github.com/google/go-licenses/pull/28
  chmod -R 777 "${outputdir}/LICENSES"

  # most of the packages show up the go-license.csv file as the module name
  # from the go.mod file, storing that away since the source dirs usually get deleted
  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')
  echo $MODULE_NAME > ${outputdir}/attribution/root-module.txt
}

function build::generate_attribution(){
  local -r golang_verson=$1
  local -r output_directory=${2:-"_output"}
  local -r attribution_file=${3:-"ATTRIBUTION.txt"}

  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)
  local -r go_path=$(build::common::get_go_path $golang_verson)
  local -r golang_version_tag=$($go_path/go version | grep -o "go[0-9].* ")

  if cat "${output_directory}/attribution/go-license.csv" | grep -e ",LGPL-" -e ",GPL-"; then
    echo " one of the dependencies is licensed as LGPL or GPL"
    echo " which is prohibited at Amazon"
    echo " please look into removing the dependency"
    exit 1
  fi

  generate-attribution $root_module_name "./" $golang_version_tag $output_directory
  cp -f "${output_directory}/attribution/ATTRIBUTION.txt" $attribution_file
}

function build::common::remove_go_path() {
  # This is the path where the specific go binary versions reside in our builder-base image
  export PATH=$(echo "$PATH" | sed -e "s/^\/go\/go[0-9\.]*\/bin://")

  # This is the path that will most likely be correct if running locally
  local -r quoted_go_path=$(build::common::re_quote $GOPATH)
  export PATH=$(echo "$PATH" | sed -e "s/^$quoted_go_path\/go[0-9\.]*\/bin://")
}

function build::common::get_go_path() {
  local -r version=$1

  # This is the path where the specific go binary versions reside in our builder-base image
  local -r gorootbinarypath="/go/go${version}/bin"
  # This is the path that will most likely be correct if running locally
  local -r gopathbinarypath="$GOPATH/go${version}/bin"
  if [ -d "$gorootbinarypath" ]; then
    echo $gorootbinarypath
  elif [ -d "$gopathbinarypath" ]; then
    echo $gopathbinarypath
  else
    # not in builder-base, probably running in dev environment
    # return default go installation
    local -r which_go=$(which go)
    echo "$(dirname $which_go)"
  fi
}

function build::common::use_go_version() {
  local -r version=$1

  local -r gobinarypath=$(build::common::get_go_path $version)
  echo "Adding $gobinarypath to PATH"
  # Adding to the beginning of PATH to allow for builds on specific version if it exists
  export PATH=${gobinarypath}:$PATH
}

function build::common::re_quote() {
    local -r to_escape=$1
    sed 's/[][()\.^$\/?*+]/\\&/g' <<< "$to_escape"
}


#!/usr/bin/env bash
set -euo pipefail

GIT_REPO_ROOT=$(git rev-parse --show-toplevel)
BUILD_DIR="${GIT_REPO_ROOT}/build"
TOOLS_DIR="${BUILD_DIR}/tools"
STABLE="${GIT_REPO_ROOT}/stable"
export PATH="${TOOLS_DIR}:${PATH}"

RELEASE_NOTES="${BUILD_DIR}/release-notes.md"
touch "${RELEASE_NOTES}"

function get_chart_version() {
    chart="$(basename ${1})"
    grep 'version: [0-9]\+\.[0-9]\+\.[0-9]\+' "${GIT_REPO_ROOT}/stable/${chart}/Chart.yaml" | cut -d':' -f2 | tr -d '[:space:]'
}

function get_app_version() {
    chart="$(basename ${1})"
    grep 'appVersion:[ ]*v\?[0-9]\+\.[0-9]\+\.[0-9]\+' "${GIT_REPO_ROOT}/stable/${chart}/Chart.yaml" | cut -d':' -f2 | tr -d '[:space:]'
}

>&2 git fetch --all --tags

if $(git describe HEAD --tags | grep -Eq "^v[0-9]+(\.[0-9]+)*(-[a-z0-9]+)?$"); then
    LAST_RELEASE_HASH=$(git rev-list --tags --max-count=1 --skip=1 --no-walk)
else
    TAG=$(git describe HEAD --tags | grep -Eo "^v[0-9]+(\.[0-9]+)*")
    LAST_RELEASE_HASH=$(git rev-list -1 $TAG)
fi
LAST_RELEASE_TAG=$(git describe $LAST_RELEASE_HASH --tags)

CHANGED_CHARTS=()

cd ${STABLE}
echo "## Charts" | tee "${RELEASE_NOTES}"
for chart in */; do
    chart="$(basename $chart)"
    LAST_COMMIT_HASH=$(git --no-pager log --pretty=tformat:"%H" -- "${chart}" | awk 'FNR <= 1')
    ## If LAST_RELEASE_HASH does not include the chart, then it's a new chart so we'll add it to the notes
    if [[ -z $(git ls-tree -d $LAST_RELEASE_HASH "${chart}") ]]; then
        echo "- ${chart} (chart $(get_chart_version ${chart}), image $(get_app_version ${chart}))"  | tee -a "${RELEASE_NOTES}"
        CHANGED_CHARTS+=("${chart}")
        continue
    fi
    ## If LAST_RELEASE_HASH is NOT an ancestor of LAST_COMMIT_HASH then it has not been modified
    if [[ ! -z $LAST_COMMIT_HASH && -z $(git rev-list $LAST_COMMIT_HASH | grep $LAST_RELEASE_HASH) || $LAST_COMMIT_HASH == $LAST_RELEASE_HASH ]]; then
        continue
    fi
    ## The chart was modified since the last release
    echo "- ${chart} (chart $(get_chart_version ${chart}), image $(get_app_version ${chart}))"  | tee -a "${RELEASE_NOTES}"
    CHANGED_CHARTS+=("${chart}")
done

echo "## Changes"  | tee -a "${RELEASE_NOTES}"
for chart in "${CHANGED_CHARTS[@]}"; do
    echo "- [${chart}]" | tee -a "${RELEASE_NOTES}"
    for change in $(git rev-list $LAST_RELEASE_HASH..HEAD ${chart}); do
        one_line_msg=$(git --no-pager log --pretty='%s (thanks to %an)'  "${change}" -n1 |  sed 's/^\[.*\]//' | xargs)
        echo "  - ${one_line_msg}" | tee -a "${RELEASE_NOTES}"
    done
done

>&2 echo -e "\n\nRelease notes file: ${RELEASE_NOTES}"


#!/usr/bin/env bash
set -euo pipefail

PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$([[ $(uname -m) = "x86_64" ]] && echo 'amd64' || echo 'arm64')
GIT_REPO_ROOT=$(git rev-parse --show-toplevel)
BUILD_DIR="${GIT_REPO_ROOT}/build"
TMP_DIR="${BUILD_DIR}/tmp"
TOOLS_DIR="${BUILD_DIR}/tools"
mkdir -p "${TOOLS_DIR}"
export PATH="${TOOLS_DIR}:${PATH}"

HELMV2_VERSION="v2.17.0"
HELMV3_VERSION="v3.6.3"
KUBECTL_VERSION=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)
KIND_VERSION=v0.11.1
BATS_VERSION=1.1.0

## Install kubectl
curl -sSL "https://storage.googleapis.com/kubernetes-release/release/${KUBECTL_VERSION}/bin/${PLATFORM}/${ARCH}/kubectl" -o "${TOOLS_DIR}/kubectl"
chmod +x "${TOOLS_DIR}/kubectl"

## Install kubeval
mkdir -p "${TMP_DIR}/kubeval"
curl -sSL https://github.com/instrumenta/kubeval/releases/latest/download/kubeval-${PLATFORM}-${ARCH}.tar.gz | tar xz -C "${TMP_DIR}/kubeval"
mv "${TMP_DIR}/kubeval/kubeval" "${TOOLS_DIR}/kubeval"

## Install helm v2
mkdir -p "${TMP_DIR}/helmv2"
curl -sSL  https://get.helm.sh/helm-${HELMV2_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C "${TMP_DIR}/helmv2"
mv "${TMP_DIR}/helmv2/${PLATFORM}-${ARCH}/helm" "${TOOLS_DIR}/helmv2"
rm -rf "${PLATFORM}-${ARCH}"

## Install helm v3
mkdir -p "${TMP_DIR}/helmv3"
curl -sSL https://get.helm.sh/helm-${HELMV3_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C "${TMP_DIR}/helmv3"
mv "${TMP_DIR}/helmv3/${PLATFORM}-${ARCH}/helm" "${TOOLS_DIR}/helmv3"
rm -rf "${PLATFORM}-${ARCH}"

## Install Bats
curl -sSL https://github.com/bats-core/bats-core/archive/v${BATS_VERSION}.tar.gz | tar xz -C "${TOOLS_DIR}"
ln -s ${TOOLS_DIR}/bats-core-${BATS_VERSION}/bin/bats ${TOOLS_DIR}/bats

## Initialize helm

helmv2 init --stable-repo-url https://charts.helm.sh/stable --client-only --kubeconfig="${BUILD_DIR}/.kube/kubeconfig"

## Install kind
curl -sSL "https://github.com/kubernetes-sigs/kind/releases/download/${KIND_VERSION}/kind-${PLATFORM}-${ARCH}" -o "${TOOLS_DIR}/kind"
chmod +x "${TOOLS_DIR}/kind"

rm -rf ${TMP_DIR}


#!/usr/bin/env bash
set -euo pipefail

GIT_REPO_ROOT=$(git rev-parse --show-toplevel)
BUILD_DIR="${GIT_REPO_ROOT}/build"
TOOLS_DIR="${BUILD_DIR}/tools"
STABLE="${GIT_REPO_ROOT}/stable"
export PATH="${TOOLS_DIR}:${PATH}"

PACKAGE_DIR="${GIT_REPO_ROOT}/build"
mkdir -p "${PACKAGE_DIR}"

helmv3 package "${STABLE}/"* --destination "${PACKAGE_DIR}/stable" --dependency-update


#!/usr/bin/env bash
set -euo pipefail

GIT_REPO_ROOT=$(git rev-parse --show-toplevel)
BUILD_DIR="${GIT_REPO_ROOT}/build"
TOOLS_DIR="${BUILD_DIR}/tools"
STABLE="${GIT_REPO_ROOT}/stable"
PACKAGE_DIR="${GIT_REPO_ROOT}/build"
export PATH="${TOOLS_DIR}:${PATH}"
VERSION="$(git describe --tags --always)"

if echo "${VERSION}" | grep -Eq "^v[0-9]+(\.[0-9]+){2}$"; then
    git fetch --all
    git config user.email eks-bot@users.noreply.github.com
    git config user.name eks-bot
    git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPO}
    git config pull.rebase false
    git checkout gh-pages
    mv -n $PACKAGE_DIR/stable/*.tgz .
    helmv3 repo index . --url https://aws.github.io/eks-charts
    git add .
    git commit -m "Publish stable charts ${VERSION}"
    git push origin gh-pages
    echo "âœ… Published charts"
else
    echo "Not a valid semver release tag! Skip charts publish"
    exit 1
fi


#!/bin/bash

check_kube_connection() {

	kube_err=$(kubectl cluster-info 2>&1 >/dev/null)
    if [[ -z $kube_err ]]; then
        echo "kubectl context check: PASSED!"
        return 0
    else
        echo "kubectl context check: FAILED -- context or permissions issue for kubectl"
        echo $kube_err
        return 1
    fi

}

check_kube_installation() {

    kube_err=$(kubectl version --client 2>&1 >/dev/null)
    if [[ -z $kube_err ]]; then
        echo "kubectl installation check: PASSED!"
        return 0
    else
        echo "kubectl installation check: FAILED -- kubectl not installed"
        return 1
    fi

}

check_jq_installation() {

    jq_err=$(jq --version 2>&1 >/dev/null)
    if [[ -z $jq_err ]]; then
        echo "jq installation check: PASSED!"
        return 0
    else
        echo "jq installation check: FAILED -- jq not installed"
        return 1
    fi

}

check_old_crds() {

    vs=$(kubectl get crd virtualservices.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == "v1beta1")')
    vn=$(kubectl get crd virtualnodes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == "v1beta1")')
    ms=$(kubectl get crd meshes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == "v1beta1")')

    if [[ -z $vs && -z $vn && -z $ms  ]]; then
        echo "App Mesh CRD check: PASSED!"
        return 0
    else
       echo "App Mesh CRD check: FAILED -- v1beta1 CRDs are still installed"
       return 1
    fi

}

check_controller_version() {
    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller --ignore-not-found -o json | jq -r ".spec.template.spec.containers[].image" | cut -f2 -d ':')
    requiredver="v1.0.0"

    if [[ "$(printf '%s\n' "$requiredver" "$currentver" | sort -V | head -n1)" = "$requiredver" || -z "$currentver" ]]; then
        echo "Controller version check: PASSED!"
        return 0
    else
        echo "Controller version check: FAILED -- old appmesh-controller ($currentver) is still running"
        return 1

    fi
}

check_injector() {
    status=0
    for ns in "appmesh-inject" "appmesh-system"; do

        injector=$(kubectl get deployment -n ${ns} appmesh-inject --ignore-not-found -o json | jq -r .kind)

        if [ -z $injector ]; then
            echo "Injector check for namespace ${ns}: PASSED!"
        else
           echo "Injector check: FAILED -- appmesh-inject is still running in namespace ${ns}"
           return 1
        fi

    done
    return 0
}

main() {

    exitcode=0
    check_kube_installation || exitcode=1
    check_jq_installation || exitcode=1
    check_kube_connection || exitcode=1
    if [ ${exitcode} = 0 ]; then
        check_old_crds || exitcode=1
        check_controller_version || exitcode=1
        check_injector || exitcode=1
    fi

    if [ ${exitcode} = 0 ]; then
        echo -e "\nYour cluster is ready for upgrade. Please proceed to the installation instructions"
    else
        echo -e "\nYour cluster is NOT ready for upgrade to v1.0.0. Please install/uninstall all the identified items before proceeding"
    fi

}

main


#!/usr/bin/env bash

# Run e2e tests

set -o errexit

export REPO_ROOT=$(git rev-parse --show-toplevel)
export PATH="$REPO_ROOT/build/tools:$PATH"

cd "${REPO_ROOT}/test/e2e/"
bats -t .


#!/usr/bin/env bash

# Helm charts testing helpers

set -o errexit

export REPO_ROOT=$(git rev-parse --show-toplevel)

function infof() {
    echo -e "\e[32m${1}\e[0m" >&3
}

function errorf() {
    echo -e "\e[31m${1}\e[0m" >&3
    exit 1
}

function installChart() {
  chartName=$(basename $1)
  testValues="$1/ci/values.yaml"

  infof "Installing chart $chartName"
  if test -f "$testValues"; then
    helm upgrade -i $chartName $1 --namespace $2 -f $testValues
  else
    helm upgrade -i $chartName $1 --namespace $2
  fi
  infof "âœ” $chartName chart install test passed"
}

function waitForDeployment() {
  chartName=$(basename $1)
  infof "Waiting for deployment $chartName"
  retries=10
  count=0
  ok=false
  until $ok; do
    kubectl -n $2 get deployment/$chartName && ok=true || ok=false
    sleep 6
    count=$(($count + 1))
    if [[ $count -eq $retries ]]; then
      errorf "No more retries left"
    fi
  done

  kubectl -n $2 rollout status deployment/$chartName --timeout=1m >&3
  infof "âœ” deployment/$chartName test passed"
}

function waitForService() {
  chartName=$(basename $1)
  infof "Waiting for service $chartName"
  retries=10
  count=0
  ok=false
  until $ok; do
    kubectl -n $2 get svc/$chartName && ok=true || ok=false
    sleep 6
    count=$(($count + 1))
    if [[ $count -eq $retries ]]; then
      errorf "No more retries left"
    fi
  done
    infof "âœ” service/$chartName test passed"
}


#!/usr/bin/env bash

# Create Kubernetes cluster with Kind

set -o errexit

REPO_ROOT=$(git rev-parse --show-toplevel)
TOOLS_DIR="$REPO_ROOT/build/tools"
export PATH="$TOOLS_DIR:$PATH"
HELM_MODE="${HELM_MODE:-v2}"

kind create cluster --wait 5m

function installHelm() {

  if [[ "${1}" == "v2" ]]; then
    kubectl --namespace kube-system create sa tiller

    kubectl create clusterrolebinding tiller-cluster-rule \
      --clusterrole=cluster-admin --serviceaccount=kube-system:tiller

    cp -f $TOOLS_DIR/helmv2 $TOOLS_DIR/helm

    helm init --stable-repo-url https://charts.helm.sh/stable --service-account tiller --upgrade --wait
  else
    cp -f $TOOLS_DIR/helmv3 $TOOLS_DIR/helm
  fi
}

export KUBECONFIG="$(kind get kubeconfig > $REPO_ROOT/build/kind-kubeconfig)"

installHelm $HELM_MODE

kubectl get pods --all-namespaces


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

BASE_DIRECTORY="${1?Specify first argument - Base directory of build-tooling repo}"
MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"

cd $MAKE_ROOT

# Iterating over orgs under projects folder
for org_path in projects/*; do
    org=$(basename "$org_path")
    for repo_path in projects/$org/*; do
        repo=$(basename "$repo_path")
        # couple odd ball non-builds in this repo
        if [[ -f $repo_path/DO_NOT_BUILD ]]; then
            continue
        fi
        echo -n "${org}_${repo} "
    done
done

echo


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

BUILD_LIB_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/" && pwd -P)"

CMD="buildctl"
if [ -f "/buildkit.sh" ] && ! buildctl debug workers >/dev/null 2>&1; then
    # on the builder base this helper file exists to run buildkitd
    # in prow buildkitd is run as a seperate container so it will be running already
    # in codebuild its run directly on the instance so we want to use this helper
    CMD="/buildkit.sh"

fi
# From time to time we see random failures when creating/pushing images that fix on reruning the job
# this is an attempt to avoid failing key jobs, like the release job, with a flaky failure
# If running in builder base, most likely we are running in prow/codebuild, us retry logic
# if not in builder base, probably running locally so skip the retry
if [ -f "/buildkit.sh" ]; then
    for i in $(seq 1 5); do
        [ $i -gt 1 ] && sleep 15
        $CMD "$@" && s=0 && break || s=$?
    done

    # space is limited on presubmit nodes, after each image build clear the build cache
    if [ "${JOB_TYPE:-}" == "presubmit" ] && [ "${PRUNE_BUILDCTL:-false}" == "true" ]; then
        $CMD prune --all
    fi

    (exit $s)
else
    # skip retry when running locally
    log_file=$(mktemp)
    trap "rm -f $log_file" EXIT
    if ! $CMD "$@" 2>&1 | tee $log_file; then
        if grep -q "blobs/uploads/\": EOF" $log_file ; then
            echo "******************************************************"
            echo "Ensure container registry and repository exists!!"
            echo "Try running make create-ecr-repos to create ecr repositories in your aws account."
            echo "******************************************************"
        fi
        exit 1
    fi
fi


# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

function buildkit_ready() {
  for i in {1..24}
  do
    if [ ! -S "/run/buildkit/buildkitd.sock" ]
    then
      echo "Buildkit daemon is not running. Retrying."
      sleep 5s
    else
      exit 0
    fi
  done
  echo "Buildkit daemon is not available"
  exit 1
}

buildkit_ready


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

if [ -n "${OUTPUT_DEBUG_LOG:-}" ]; then
    set -x
fi

function build::common::ensure_tar() {
  if [[ -n "${TAR:-}" ]]; then
    return
  fi

  # Find gnu tar if it is available, bomb out if not.
  TAR=tar
  if which gtar &>/dev/null; then
      TAR=gtar
  elif which gnutar &>/dev/null; then
      TAR=gnutar
  fi
  if ! "${TAR}" --version | grep -q GNU; then
    echo "  !!! Cannot find GNU tar. Build on Linux or install GNU tar"
    echo "      on Mac OS X (brew install gnu-tar)."
    return 1
  fi
}

# Build a release tarball.  $1 is the output tar name.  $2 is the base directory
# of the files to be packaged.  This assumes that ${2}/kubernetes is what is
# being packaged.
function build::common::create_tarball() {
  build::common::ensure_tar

  local -r tarfile=$1
  local -r stagingdir=$2
  local -r repository=$3

  build::common::echo_and_run "${TAR}" czf "${tarfile}" -C "${stagingdir}" $repository --owner=0 --group=0
}

# Generate shasum of tarballs. $1 is the directory of the tarballs.
function build::common::generate_shasum() {

  local -r tarpath=$1

  echo "Writing artifact hashes to shasum files..."

  if [ ! -d "$tarpath" ]; then
    echo "  Unable to find tar directory $tarpath"
    exit 1
  fi

  cd $tarpath
  for file in $(find . -name '*.tar.gz'); do
    filepath=$(basename $file)
    sha256sum "$filepath" > "$file.sha256"
    sha512sum "$filepath" > "$file.sha512"
  done
  cd -
}

function build::gather_licenses() {
  local -r outputdir=$1
  local -r patterns=$2
  local -r golang_version=$3

  # Force deps to only be pulled form vendor directories
  # this is important in a couple cases where license files
  # have to be manually created
  export GOFLAGS=-mod=vendor
  # force platform to be linux to ensure all deps are picked up
  export GOOS=linux
  export GOARCH=amd64

  # the version of go used here must be the version go-licenses was installed with corresponding go versions
  build::common::use_go_version $golang_version

  if ! command -v go-licenses &> /dev/null
  then
    echo " go-licenses not found.  If you need license or attribution file handling"
    echo " please refer to the doc in docs/development/attribution-files.md"
    exit
  fi

  mkdir -p "${outputdir}/attribution"
  # attribution file generated uses the output go-deps and go-license to gather the necessary
  # data about each dependency to generate the amazon approved attribution.txt files
  # go-deps is needed for module versions
  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns
  build::common::echo_and_run go list -deps=true -json ./... | jq -s ''  > "${outputdir}/attribution/go-deps.json"

  # go-licenses can be a bit noisy with its output and lot of it can be confusing
  # the following messages are safe to ignore since we do not need the license url for our process
  NOISY_MESSAGES="cannot determine URL for|Error discovering license URL|unsupported package host|contains non-Go code|has empty version|vendor.*\.s$"

  build::common::echo_and_run go-licenses save --force $patterns --save_path "${outputdir}/LICENSES" 2> >(grep -vE "$NOISY_MESSAGES")

  build::common::echo_and_run go-licenses csv $patterns 2> >(grep -vE "$NOISY_MESSAGES") > "${outputdir}/attribution/go-license.csv"

  if cat "${outputdir}/attribution/go-license.csv" | grep -q "^vendor\/golang.org\/x"; then
      echo " go-licenses created a file with a std golang package (golang.org/x/*)"
      echo " prefixed with vendor/.  This most likely will result in an error"
      echo " when generating the attribution file and is probably due to"
      echo " to a version mismatch between the current version of go "
      echo " and the version of go that was used to build go-licenses"
      exit 1
  fi

  if cat "${outputdir}/attribution/go-license.csv" | grep -e ",LGPL-" -e ",GPL-"; then
    echo " one of the dependencies is licensed as LGPL or GPL"
    echo " which is prohibited at Amazon"
    echo " please look into removing the dependency"
    exit 1
  fi

  # go-license is pretty eager to copy src for certain license types
  # when it does, it applies strange permissions to the copied files
  # which makes deleting them later awkward
  # this behavior may change in the future with the following PR
  # https://github.com/google/go-licenses/pull/28
  # We can delete these additional files because we are running go mod vendor
  # prior to this call so we know the source is the same as upstream
  # go-licenses is copying this code because it doesnt know if its be modified or not
  chmod -R 777 "${outputdir}/LICENSES"
  find "${outputdir}/LICENSES" -type f \( -name '*.yml' -o -name '*.go' -o -name '*.mod' -o -name '*.sum' -o -name '*gitignore' \) -delete

  # most of the packages show up the go-license.csv file as the module name
  # from the go.mod file, storing that away since the source dirs usually get deleted
  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')
  if [ ! -f ${outputdir}/attribution/root-module.txt ]; then
  	echo $MODULE_NAME > ${outputdir}/attribution/root-module.txt
  fi
}

function build::non-golang::gather_licenses(){
  local -r project="$1"
  local -r git_tag="$2"
  local -r output_dir="$3"
  project_org="$(cut -d '/' -f1 <<< ${project})"
  project_name="$(cut -d '/' -f2 <<< ${project})"
  git clone https://github.com/${project_org}/${project_name}
  cd $project_name
  git checkout $git_tag
  cd ..
  build::non-golang::copy_licenses $project_name $output_dir/LICENSES/github.com/${project_org}/${project_name}
  rm -rf $project_name
}

function build::non-golang::copy_licenses(){
  local -r source_dir="$1"
  local -r destination_dir="$2"
  (cd $source_dir; find . \( -name "*COPYING*" -o -name "*COPYRIGHT*" -o -name "*LICEN[C|S]E*" -o -name "*NOTICE*" \)) |
  while read file
  do
    license_dest=$destination_dir/$(dirname $file)
    mkdir -p $license_dest
    cp -r "${source_dir}/${file}" $license_dest/$(basename $file)
  done
}

function build::generate_attribution(){
  local -r project_root=$1
  local -r golang_version=$2
  local -r output_directory=${3:-"${project_root}/_output"}
  local -r attribution_file=${4:-"${project_root}/ATTRIBUTION.txt"}

  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)
  local -r go_path=$(build::common::get_go_path $golang_version)
  local -r golang_version_tag=$($go_path/go version | grep -o "go[0-9].* ")

  if cat "${output_directory}/attribution/go-license.csv" | grep -e ",LGPL-" -e ",GPL-"; then
    echo " one of the dependencies is licensed as LGPL or GPL"
    echo " which is prohibited at Amazon"
    echo " please look into removing the dependency"
    exit 1
  fi

  build::common::echo_and_run generate-attribution $root_module_name $project_root $golang_version_tag $output_directory
  cp -f "${output_directory}/attribution/ATTRIBUTION.txt" $attribution_file
}

function build::common::get_go_path() {
  local -r version=$1

  # This is the path where the specific go binary versions reside in our builder-base image
  local -r gorootbinarypath="/go/go${version}/bin"
  # This is the path that will most likely be correct if running locally
  local -r gopathbinarypath="$GOPATH/go${version}/bin"
  if [ -d "$gorootbinarypath" ]; then
    echo $gorootbinarypath
  elif [ -d "$gopathbinarypath" ]; then
    echo $gopathbinarypath
  else
    # not in builder-base, probably running in dev environment
    # return default go installation
    local -r which_go=$(which go)
    echo "$(dirname $which_go)"
  fi
}

function build::common::use_go_version() {
  local -r version=$1

  if (( "${version#*.}" < 16 )); then
    echo "Building with GO version $version is no longer supported!  Please update the build to use a newer version."
    exit 1
  fi

  local -r gobinarypath=$(build::common::get_go_path $version)
  echo "Adding $gobinarypath to PATH"
  # Adding to the beginning of PATH to allow for builds on specific version if it exists
  export PATH=${gobinarypath}:$PATH
  export GOCACHE=$(go env GOCACHE)/$version
}

# Use a seperate build cache for each project/version to ensure there are no
# shared bits which can mess up the final checksum calculation
# this is mostly needed for create checksums locally since in the builds
# different versions of the same project are not built in the same container
function build::common::set_go_cache() {
  local -r project=$1
  local -r git_tag=$2
  export GOCACHE=$(go env GOCACHE)/$project/$git_tag
}

function build::common::re_quote() {
    local -r to_escape=$1
    sed 's/[][()\.^$\/?*+]/\\&/g' <<< "$to_escape"
}
function build::common::wait_for_tag() {
  local -r tag=$1
  sleep_interval=20
  for i in {1..60}; do
    echo "Checking for tag ${tag}..."
    git rev-parse --verify --quiet "${tag}" && echo "Tag ${tag} exists!" && break
    git fetch --tags > /dev/null 2>&1
    echo "Tag ${tag} does not exist!"
    echo "Waiting for tag ${tag}..."
    sleep $sleep_interval
    if [ "$i" = "60" ]; then
      exit 1
    fi
  done
}

function build::common::wait_for_tarball() {
  local -r tarball_url=$1
  sleep_interval=20
  for i in {1..60}; do
    echo "Checking for URL ${tarball_url}..."
    local -r http_code=$(curl -I -L -s -o /dev/null -w "%{http_code}" $tarball_url)
    if [[ "$http_code" == "200" ]]; then
      echo "Tarball exists!" && break
    fi
    echo "Tarball does not exist!"
    echo "Waiting for tarball to be uploaded to ${tarball_url}"
    sleep $sleep_interval
    if [ "$i" = "60" ]; then
      exit 1
    fi
  done
}

function build::common::get_clone_url() {
  local -r org=$1
  local -r repo=$2
  local -r aws_region=$3

  echo "https://github.com/${org}/${repo}.git"
}

function retry() {
  local n=1
  local max=120
  local delay=5
  while true; do
    "$@" && break || {
      if [[ $n -lt $max ]]; then
        ((n++))
        >&2 echo "Command failed. Attempt $n/$max:"
        sleep $delay;
      else
        fail "The command has failed after $n attempts."
      fi
    }
  done
}

function build::docker::retry_pull() {
  retry docker pull "$@"
}

function build::common::echo_and_run() {
  >&2 echo "($(pwd)) \$ $*"
  "$@"
}


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

PROJECT_ROOT="$1"
GOLANG_VERSION="$2"
OUTPUT_DIR="$3"
OUTPUT_FILENAME="$4"
RELEASE_BRANCH="${5:-}"

if [[ -n "$RELEASE_BRANCH" ]] && [ -d "$PROJECT_ROOT/$RELEASE_BRANCH" ]; then
	PROJECT_ROOT=$PROJECT_ROOT/$RELEASE_BRANCH
fi

build::generate_attribution $PROJECT_ROOT $GOLANG_VERSION $OUTPUT_DIR $PROJECT_ROOT/$OUTPUT_FILENAME


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

IMAGE_NAME="$1"
IMAGE="$2"
LATEST_IMAGE="$3"
WINDOWS_IMAGE_VERSIONS="$4"

echo "Creating windows manifest for $IMAGE_NAME"

# this metadate file contains the linux/amd+arm images
if [ ! -f /tmp/$IMAGE_NAME-metadata.json ]; then
    echo "No metadata file for image: /tmp/$IMAGE_NAME-metadata.json!"
    exit 1
fi

# need to remove mediaType from descri since buildx segfaults when it is set
jq -r '."containerimage.descriptor"  | {size, digest}' /tmp/$IMAGE_NAME-metadata.json > /tmp/$IMAGE_NAME-descr-final.json

CREATE_ARGS="-f /tmp/$IMAGE_NAME-descr-final.json "
VERSIONS=(${WINDOWS_IMAGE_VERSIONS// / })
for version in "${VERSIONS[@]}"; do
    if [ ! -f /tmp/$IMAGE_NAME-$version-metadata.json ]; then
        echo "No metadata file for image: /tmp/$IMAGE_NAME-$version-metadata.json!"
        exit 1
    fi

    BASE_IMAGE=$(jq -r '."containerimage.buildinfo".attrs."build-arg:BASE_IMAGE"' /tmp/$IMAGE_NAME-$version-metadata.json)

    # need to remove mediaType from descri since buildx segfaults when it is set
    jq -r '."containerimage.descriptor"  | {size, digest}' /tmp/$IMAGE_NAME-$version-metadata.json > /tmp/$IMAGE_NAME-$version-descr.json
    build::common::echo_and_run retry docker buildx imagetools inspect --raw $BASE_IMAGE | jq '.manifests[0] | {platform}' | jq add -s - /tmp/$IMAGE_NAME-$version-descr.json > /tmp/$IMAGE_NAME-$version-descr-final.json
    cat /tmp/$IMAGE_NAME-$version-descr-final.json
    CREATE_ARGS+="-f /tmp/$IMAGE_NAME-$version-descr-final.json "
done

build::common::echo_and_run retry docker buildx imagetools create --dry-run $CREATE_ARGS -t $IMAGE -t $LATEST_IMAGE > /tmp/$IMAGE_NAME-manfiest-final.json

cat  /tmp/$IMAGE_NAME-manfiest-final.json

if [ "$(jq '.manifests[].platform.os' /tmp/$IMAGE_NAME-manfiest-final.json |  grep -w -c windows)" != "${#VERSIONS[@]}" ]; then
    echo "image manifest does not contain correct number of windows images!"
    exit 1
fi

if [ "$(jq '.manifests[].platform.os' /tmp/$IMAGE_NAME-manfiest-final.json |  grep -w -c linux)" != "2" ]; then
    echo "image manifest does not contain correct number of linux images!"
    exit 1
fi

if [ "$(jq '.manifests[].platform | select( has("os.version") == true ) | ."os.version"' /tmp/$IMAGE_NAME-manfiest-final.json | wc -l | xargs)" != "${#VERSIONS[@]}" ]; then
    echo "windows images do not have os.version set!"
    exit 1
fi

build::common::echo_and_run retry docker buildx imagetools create $CREATE_ARGS -t $IMAGE -t $LATEST_IMAGE

build::common::echo_and_run retry docker buildx imagetools inspect $IMAGE

# Public ecr's tagging appears to have some delay when retagging existing tags, like latest
# retry the diff to give it time to make sure the latest manifest has been updated to new verion
function validate_latest() {
    if ! diff <(retry docker buildx imagetools inspect $IMAGE --raw) <(retry docker buildx imagetools inspect $LATEST_IMAGE --raw); then
        echo "image manifest and latest manifest do not match!"
        return 1
    fi
}

retry validate_latest

rm -rf /tmp/$IMAGE_NAME-*.json


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

REPO="$1"
OUTPUT_DIR="$2"
PACKAGE_FILTER="$3"
REPO_SUBPATH="${4:-}"
GOLANG_VERSION="${5:-}"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

cd $REPO/$REPO_SUBPATH
build::gather_licenses $OUTPUT_DIR "$PACKAGE_FILTER" "$GOLANG_VERSION"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

PROJECT_ROOT="$1"
BINARY_TARGET_FILES="$2"
BINARY_PLATFORMS="$3"
BINARY_TARGETS="$4"
REPO="$5"
HAS_PATCHES="$6"
LOCAL_IMAGE_TARGETS="$7"
IMAGE_TARGETS="$8"
BUILD_TARGETS="$9"
RELEASE_TARGETS="${10}"
HAS_S3_ARTIFACTS="${11}"
HAS_LICENSES="${12}"
REPO_NO_CLONE="${13}"
FETCH_BINARIES_TARGETS="${14}"
HAS_HELM_CHART="${15}"
IN_DOCKER_TARGETS="${16}"

NL=$'\n'
HEADER="########### DO NOT EDIT #############################"
FOOTER="########### END GENERATED ###########################"

MAKEFILE=$PROJECT_ROOT/Makefile
HELPFILE=$PROJECT_ROOT/Help.mk

SED=sed
if [ "$(uname -s)" = "Darwin" ]; then
    SED=gsed
fi

$SED -i "/$HEADER/,/$FOOTER/d" $MAKEFILE
# remove trailing newlines
printf %s "$(< $MAKEFILE)" > $MAKEFILE

touch $HELPFILE

$SED -i "/$HEADER/,/$FOOTER/d" $HELPFILE
# remove trailing newlines
printf %s "$(< $HELPFILE)" > $HELPFILE

# Generate help items from Common.mk
EXTRA_HELP="$(make help-list --no-print-directory)"
BINARY_TARGETS_HELP=""
CHECKSUMS_TARGETS_HELP=""
if [ ! -z "$(echo "$BINARY_TARGETS" | xargs)" ]; then
    BINARY_TARGETS_HELP+="${NL}${NL}##@ Binary Targets"
    BINARY_TARGETS_HELP+="${NL}binaries: ## Build all binaries: \`${BINARY_TARGET_FILES}\` for \`${BINARY_PLATFORMS}\`"
    TARGETS=(${BINARY_TARGETS// / })
    for target in "${TARGETS[@]}"; do
        BINARY_TARGETS_HELP+="${NL}${target}: ## Build \`${target}\`"
    done

    CHECKSUMS_TARGETS_HELP+="${NL}${NL}##@ Checksum Targets"
    CHECKSUMS_TARGETS_HELP+="${NL}checksums: ## Update checksums file based on currently built binaries."
    CHECKSUMS_TARGETS_HELP+="${NL}validate-checksums: # Validate checksums of currently built binaries against checksums file."
    CHECKSUMS_TARGETS_HELP+="${NL}all-checksums: ## Update checksums files for all RELEASE_BRANCHes."
fi

GIT_TARGETS_HELP=""
if [[ "$REPO_NO_CLONE" != "true" ]]; then
    GIT_TARGETS_HELP+="${NL}${NL}##@ GIT/Repo Targets"
    GIT_TARGETS_HELP+="${NL}clone-repo:  ## Clone upstream \`${REPO}\`"
    GIT_TARGETS_HELP+="${NL}checkout-repo: ## Checkout upstream tag based on value in GIT_TAG file"
fi

PATCHES_TARGET=""
if [[ "$HAS_PATCHES" == "true" ]]; then
    PATCHES_TARGET+="${NL}patch-repo: ## Patch upstream repo with patches in patches directory"
fi

IMAGE_TARGETS_HELP=""
if [ ! -z "$(echo "$LOCAL_IMAGE_TARGETS" | xargs)" ]; then
    IMAGE_TARGETS_HELP+="${NL}${NL}##@ Image Targets"
    IMAGE_TARGETS_HELP+="${NL}local-images: ## Builds \`$(echo ${LOCAL_IMAGE_TARGETS} | xargs)\` as oci tars for presumbit validation"
    IMAGE_TARGETS_HELP+="${NL}images: ## Pushes \`$(echo ${IMAGE_TARGETS} | xargs)\` to IMAGE_REPO"

    ALL_IMAGES=()
    TARGETS=(${LOCAL_IMAGE_TARGETS// / })
    for target in "${TARGETS[@]}"; do
        ALL_IMAGES+=("$target")
    done
    TARGETS=(${IMAGE_TARGETS// / })
    for target in "${TARGETS[@]}"; do
        if [[ ! " ${ALL_IMAGES[*]} " =~ " ${target} " ]]; then
            ALL_IMAGES+=("$target")
        fi
    done
    for image in "${ALL_IMAGES[@]}"; do
        IMAGE_TARGETS_HELP+="${NL}$image: ## Builds/pushes \`${image}\`"
    done

fi

ARTIFACTS_TARGETS=""
if [[ "$HAS_S3_ARTIFACTS" == "true" ]]; then
    ARTIFACTS_TARGETS+="${NL}${NL}##@ Artifact Targets"
    ARTIFACTS_TARGETS+="${NL}tarballs: ## Create tarballs by calling build/lib/simple_create_tarballs.sh unless SIMPLE_CREATE_TARBALLS=false, then tarballs must be defined in project Makefile"
    ARTIFACTS_TARGETS+="${NL}s3-artifacts: # Prepare ARTIFACTS_PATH folder structure with tarballs/manifests/other items to be uploaded to s3"
    ARTIFACTS_TARGETS+="${NL}upload-artifacts: # Upload tarballs and other artifacts from ARTIFACTS_PATH to S3"
fi

LICENSES_TARGETS=""
if [[ "$HAS_LICENSES" == "true" ]]; then
    LICENSES_TARGETS+="${NL}${NL}##@ License Targets"
    LICENSES_TARGETS+="${NL}gather-licenses: ## Helper to call \$(GATHER_LICENSES_TARGETS) which gathers all licenses"
    LICENSES_TARGETS+="${NL}attribution: ## Generates attribution from licenses gathered during \`gather-licenses\`."
    LICENSES_TARGETS+="${NL}attribution-pr: ## Generates PR to update attribution files for projects"
    LICENSES_TARGETS+="${NL}attribution-checksums: ## Update attribution and checksums files."
    LICENSES_TARGETS+="${NL}all-attributions: ## Update attribution files for all RELEASE_BRANCHes."
    LICENSES_TARGETS+="${NL}all-attributions-checksums: ## Update attribution and checksums files for all RELEASE_BRANCHes."
fi

CLEAN_TARGETS="${NL}${NL}##@ Clean Targets"
CLEAN_TARGETS+="${NL}clean: ## Removes source and _output directory"
if [[ "$REPO_NO_CLONE" != "true" ]]; then
    CLEAN_TARGETS+="${NL}clean-repo: ## Removes source directory"
fi

FETCH_BINARY_TARGETS_HELP=""
if [ ! -z "$(echo "$FETCH_BINARIES_TARGETS" | xargs)" ]; then
    FETCH_BINARY_TARGETS_HELP+="${NL}${NL}##@ Fetch Binary Targets"
    TARGETS=(${FETCH_BINARIES_TARGETS// / })
    for target in "${TARGETS[@]}"; do
        FETCH_BINARY_TARGETS_HELP+="${NL}${target}: ## Fetch \`${target}\`"
    done
fi

HELM_TARGETS=""
if [[ "$HAS_HELM_CHART" == "true" ]]; then
    HELM_TARGETS+="${NL}${NL}##@ Helm Targets"
    HELM_TARGETS+="${NL}helm/build: ## Build helm chart"
    HELM_TARGETS+="${NL}helm/push: ## Build helm chart and push to registry defined in IMAGE_REPO."
fi

TARGETS=(${IN_DOCKER_TARGETS// / })
DOCKER_TARGETS="${NL}${NL}##@ Run in Docker Targets"
for target in "${TARGETS[@]}"; do
    DOCKER_TARGETS+="${NL}run-${target}-in-docker: ## Run \`${target}\` in docker builder container"
done

cat >> $HELPFILE << EOF
${NL}${NL}${NL}${HEADER}
# To update call: make add-generated-help-block
# This is added to help document dynamic targets and support shell autocompletion
${GIT_TARGETS_HELP}${PATCHES_TARGET}${BINARY_TARGETS_HELP}${IMAGE_TARGETS_HELP}${HELM_TARGETS}${FETCH_BINARY_TARGETS_HELP}${CHECKSUMS_TARGETS_HELP}${DOCKER_TARGETS}${ARTIFACTS_TARGETS}${LICENSES_TARGETS}${CLEAN_TARGETS}
${EXTRA_HELP}

##@ Build Targets
build: ## Called via prow presubmit, calls \`${BUILD_TARGETS//$PROJECT_ROOT\//""}\`
release: ## Called via prow postsubmit + release jobs, calls \`${RELEASE_TARGETS}\`
${FOOTER}
EOF

cat >> $MAKEFILE << EOF
${NL}${NL}${NL}${HEADER}
# To update call: make add-generated-help-block
# This is added to help document dynamic targets and support shell autocompletion
# Run make help for a formatted help block with all targets
include Help.mk
${FOOTER}
EOF


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

PROJECT_ROOT="$1"
REPO="$2"
TAG="$3"
GOLANG_VERSION="$4"
REPO_SUBPATH="${5:-}"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

cd $REPO/$REPO_SUBPATH

CACHE_KEY=$(echo $PROJECT_ROOT | sed 's/\(.*\)\//\1-/' | xargs basename)
build::common::use_go_version $GOLANG_VERSION
build::common::set_go_cache $CACHE_KEY $TAG
build::common::echo_and_run go mod vendor


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

# Taken from https://github.com/aws/eks-distro-build-tooling/blob/main/builder-base/install.sh
# TODO: introduce a shared scripts repo to better share things like this

set -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

setupgo() {
    local -r version=$1
    go install golang.org/dl/go${version}@latest
    go${version} download
    # Removing the patch number as we only care about the minor version of golang
    local -r majorversion=$(cut -d. -f"1,2" <<< $version)
    mkdir -p ${GOPATH}/go${majorversion}/bin
    ln -sf ${GOPATH}/bin/go${version} ${GOPATH}/go${majorversion}/bin/go
    ln -sf ${HOME}/sdk/go${version}/bin/gofmt ${GOPATH}/go${majorversion}/bin/gofmt
}

setupgo "${GOLANG117_VERSION:-1.17.13}"
setupgo "${GOLANG118_VERSION:-1.18.10}"
setupgo "${GOLANG119_VERSION:-1.19.10}"
setupgo "${GOLANG120_VERSION:-1.20.5}"

# use 1.17 when installing and running go-licenses
# go-licenses needs to be installed by the same version of go that is being used
# to generate the deps list during the attribution generation process
build::common::use_go_version "1.17"
GOBIN=${GOPATH}/go1.17/bin go install github.com/google/go-licenses@v1.2.1

build::common::use_go_version "1.18"
GOBIN=${GOPATH}/go1.18/bin go install github.com/google/go-licenses@v1.2.1

build::common::use_go_version "1.19"
GOBIN=${GOPATH}/go1.19/bin go install github.com/google/go-licenses@v1.2.1

build::common::use_go_version "1.20"
GOBIN=${GOPATH}/go1.20/bin go install github.com/google/go-licenses@v1.2.1

# 1.17 is the default so symlink it to /go/bin
ln -sf ${GOPATH}/go1.17/bin/go-licenses ${GOPATH}/bin


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -e
set -o pipefail
set -x

function registry_ready() {
  for i in {1..24}
  do
    if ! curl http://$IMAGE_REPO/ > /dev/null 2>&1;
    then
      echo "Local registry at ${IMAGE_REPO} is not running. Retrying."
      sleep 5
    else
      exit 0
    fi
  done
  echo "Local registry at ${IMAGE_REPO} is not available"
  exit 1
}

registry_ready


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o nounset
set -o pipefail

REPO="$1"
GIT_TAG="$2"
PATCHES_DIR="${3:-../patches}"

mkdir -p $PATCHES_DIR

cd $REPO

COMMIT=$(git rev-parse HEAD)
LATEST_PATCH_NUMBER=$(ls -f $PATCHES_DIR | cut -d- -f1 | sort | tail -1)

if [[ ! $LATEST_PATCH_NUMBER =~ ^[0-9] ]]; then
    LATEST_PATCH_NUMBER=1
fi

git add go.mod go.sum

# if the upstream project vends their deps, lets update them in the patch
if [ $(git cat-file -t $GIT_TAG:vendor 2>/dev/null) ]; then
    git add ./vendor
fi

git commit
git format-patch --signoff --start-number $((LATEST_PATCH_NUMBER + 1)) -o $PATCHES_DIR $COMMIT --

# Copy into project folder to check in for dependabot
cp -f go.{mod,sum} $(dirname $PATCHES_DIR)


#!/usr/bin/env bash
# Copyright 2020 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

PROJECT="$1"
TARGET="$2"
IMAGE_REPO="${3:-}"
RELEASE_BRANCH="${4:-}"
ARTIFACTS_BUCKET="${5:-$ARTIFACTS_BUCKET}"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"

source "${SCRIPT_ROOT}/common.sh"

echo "****************************************************************"
echo "A docker container with the name eks-d-builder will be launched."
echo "It will be left running to support running consecutive runs."
echo "Run 'make stop-docker-builder' when you are done to stop it."
echo "****************************************************************"

if ! docker ps -f name=eks-d-builder | grep -w eks-d-builder; then
	build::docker::retry_pull public.ecr.aws/eks-distro-build-tooling/builder-base:latest

	NETRC=""
	if [ -f $HOME/.netrc ]; then
		NETRC="--mount type=bind,source=$HOME/.netrc,target=/root/.netrc"
	fi

	# on a linux host, the uid needs to match the host user otherwise
	# git will complain about user permissions on the repo, when go
	# goes to figure out the vcs information
	USER_ID=""
	if [ "$(uname -s)" = "Linux" ] && [ -n "${USER:-}" ]; then
		USER_ID="-u $(id -u ${USER}):$(id -g ${USER})"
	fi

	docker run -d --name eks-d-builder --privileged $NETRC $USER_ID \
		--mount type=bind,source=$MAKE_ROOT,target=/eks-distro \
		-e GOPROXY=${GOPROXY:-} --entrypoint sleep \
		public.ecr.aws/eks-distro-build-tooling/builder-base:latest infinity
fi

docker exec -e RELEASE_BRANCH=$RELEASE_BRANCH -it eks-d-builder make $TARGET -C /eks-distro/projects/$PROJECT IMAGE_REPO=$IMAGE_REPO ARTIFACTS_BUCKET=$ARTIFACTS_BUCKET


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

PROJECT_ROOT="$1"
TARGET_FILE="$2"
REPO="$3"
GOLANG_VERSION="$4"
BINARY_PLATFORMS="$5"
SOURCE_PATTERN="$6"
GOBUILD_COMMAND="$7"
EXTRA_GOBUILD_FLAGS="$8"
GO_LDFLAGS="$9"
CGO_ENABLED="${10}"
CGO_LDFLAGS="${11}"
REPO_SUBPATH="${12:-}"
ALL_TARGET_FILES="${13:-}"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

function build::simple::print_go_env(){
  for var in "GOOS" "GOARCH" "CGO_ENABLED" "GOCACHE" "GOFLAGS"; do
    if [ -n "${!var:-}" ]; then
      echo "$var: ${!var:-}"
    fi
    if [ "$var" = "CGO_ENABLED" ] && [ "${!var:-}" = "1" ]; then
      for other in "CGO_LDFLAGS" "CGO_CFLAGS" "LD_LIBRARY_PATH" "PKG_CONFIG_PATH"; do echo "$other: ${!other:-}"; done
    fi
  done
}

function build::simple::binaries(){
  mkdir -p $(dirname $TARGET_FILE)
  cd "$PROJECT_ROOT/$REPO/$REPO_SUBPATH"
  build::common::use_go_version $GOLANG_VERSION
  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })
  for platform in "${SUPPORTED_PLATFORMS[@]}"; do
    OS="$(cut -d '/' -f1 <<< ${platform})"
    ARCH="$(cut -d '/' -f2 <<< ${platform})"
    if [ $CGO_ENABLED = 1 ]; then
      export CGO_LDFLAGS="$CGO_LDFLAGS,-L$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64"
      export CGO_CFLAGS="-I$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/include"
      export LD_LIBRARY_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64:${LD_LIBRARY_PATH-}
      export PKG_CONFIG_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64/pkgconfig:${PKG_CONFIG_PATH-}
    fi

    # target file is meant to be treated as a folder since multiple binaries will written out
    if [[ "$TARGET_FILE" == */ ]]; then
      mkdir -p $TARGET_FILE
    fi

    echo "Building binary(s): $ALL_TARGET_FILES"
    export CGO_ENABLED=$CGO_ENABLED GOOS=$OS GOARCH=$ARCH

    build::simple::print_go_env

    build::common::echo_and_run go $GOBUILD_COMMAND -trimpath -a -ldflags "$GO_LDFLAGS" $EXTRA_GOBUILD_FLAGS -o $TARGET_FILE $SOURCE_PATTERN

    if [[ "$TARGET_FILE" == */ ]]; then
      # in the case of outputing to a directory, the files will be named by the basename of the source pattern
      # these need to be renamed to match the configured name from ALL_TARGET_FILES
      TARGET_FILES=(${ALL_TARGET_FILES// / })
      index=0
      for source in $SOURCE_PATTERN; do
        if [ "$(basename $source)" != "${TARGET_FILES[$index]}" ] && [ -f $TARGET_FILE$(basename $source) ]; then
          # in the case of multiple target files but the first is a ., we cant move . but it should already be named correctly
          build::common::echo_and_run mv $TARGET_FILE$(basename $source) $TARGET_FILE${TARGET_FILES[$index]}
        fi
        ((index=index+1))
      done
    fi
  done
}

build::simple::binaries


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

TAR_FILE_PREFIX="$1"
OUTPUT_DIR="$2"
OUTPUT_BIN_DIR="$3"
TAG="$4"
BINARY_PLATFORMS="$5"
TAR_PATH="$6"

LICENSES_PATH=$(find $OUTPUT_DIR -maxdepth 3 -name LICENSES)
ATTRIBUTION_PATH=$(find $OUTPUT_DIR -maxdepth 1 -name "*ATTRIBUTION.txt")

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

function build::simple::tarball() {
  build::common::ensure_tar
  mkdir -p "$TAR_PATH"
  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })
  for platform in "${SUPPORTED_PLATFORMS[@]}"; do
    OS="$(cut -d '/' -f1 <<< ${platform})"
    ARCH="$(cut -d '/' -f2 <<< ${platform})"
    TAR_FILE="${TAR_FILE_PREFIX}-${OS}-${ARCH}-${TAG}.tar.gz"

    build::common::echo_and_run cp -rf $LICENSES_PATH ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/
    build::common::echo_and_run cp $ATTRIBUTION_PATH ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/
    build::common::create_tarball ${TAR_PATH}/${TAR_FILE} ${OUTPUT_BIN_DIR}/${OS}-${ARCH} .
  done
}

build::simple::tarball


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

MAKE_ROOT="$1"
PROJECT_ROOT="$2"
OUTPUT_BIN_DIR="$3"

if [ ! -d ${OUTPUT_BIN_DIR} ] ;  then
    echo "${OUTPUT_BIN_DIR} not present! Run 'make binaries'"
    exit 1
fi

CHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS

rm -f $CHECKSUMS_FILE
for file in $(find ${OUTPUT_BIN_DIR} -type f | sort); do
    filepath=$(realpath --relative-base=$MAKE_ROOT $file)
    sha256sum $filepath >> $CHECKSUMS_FILE
done

echo "*************** CHECKSUMS ***************"
cat $CHECKSUMS_FILE
echo "*****************************************"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

if [[ -z "$JOB_TYPE" ]]; then
    exit 0
fi

GOPATH=$GOPATH
if [ -d "/go" ]; then
    GOPATH="/go"
fi

for go in $GOPATH/go*/bin/go; do
    VERSION=$($go version | grep -o "go[0-9].* " | grep -o "[0-9\.]*")
    NOPATCH=$(cut -d. -f"1,2" <<< $VERSION)
    sed -i "s,\${GOLANG${NOPATCH//./}_VERSION:-.*},\${GOLANG${NOPATCH//./}_VERSION:-$VERSION}," ./build/lib/install_go_versions.sh
done


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -x
set -o errexit
set -o nounset
set -o pipefail

PROJECT_ROOT="$1"
REPO="$2"
TAG="$3"
GOLANG_VERSION="$4"
CUSTOM_VENDOR_UPDATE_SCRIPT="${5:-}"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

cd $REPO

CACHE_KEY=$(echo $PROJECT_ROOT | sed 's/\(.*\)\//\1-/' | xargs basename)
build::common::use_go_version $GOLANG_VERSION
build::common::set_go_cache $CACHE_KEY $TAG

# force a full download of deps to properly clean up the go.sum
rm -rf go.sum vendor

if [ ! -f "$CUSTOM_VENDOR_UPDATE_SCRIPT" ]; then
    go mod vendor
    go mod tidy
else
    exec $CUSTOM_VENDOR_UPDATE_SCRIPT
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

PROJECT_ROOT="$1"
ARTIFACTS_FOLDER="$2"
GIT_TAG="$3"
FAKE_ARM_ARTIFACTS_FOR_VALIDATION="$4"

EXPECTED_FILES_PATH=$PROJECT_ROOT/expected_artifacts
if [[ $ARTIFACTS_FOLDER == *images ]]; then
	EXPECTED_FILES_PATH=$PROJECT_ROOT/expected_images
fi

ACTUAL_FILES=$(mktemp)

for file in $(find ${ARTIFACTS_FOLDER} -type f | sort); do
    filepath=$(realpath --relative-base=$ARTIFACTS_FOLDER $file)
	echo $filepath >> $ACTUAL_FILES
done

EXPECTED_FILES=$(mktemp)
export GIT_TAG=$GIT_TAG
envsubst '$GIT_TAG' \
	< $EXPECTED_FILES_PATH \
	> $EXPECTED_FILES

if $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then
	sed -i '/arm64/d' $EXPECTED_FILES
fi

if ! diff $EXPECTED_FILES $ACTUAL_FILES; then
	echo "Artifacts directory does not matched expected!"
	echo "******************* Actual ******************"
	cat $ACTUAL_FILES
	echo "*********************************************"
	exit 1
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

MAKE_ROOT="$1"
PROJECT_ROOT="$2"
OUTPUT_BIN_DIR="$3"
FAKE_ARM_ARTIFACTS_FOR_VALIDATION="$4"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

cd $MAKE_ROOT

CHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS

if $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then
	TEMP_FILE=$(mktemp)
	grep -v 'arm64' $CHECKSUMS_FILE > $TEMP_FILE
	CHECKSUMS_FILE=$TEMP_FILE
fi

if ! sha256sum -c $CHECKSUMS_FILE; then
	echo "Checksums do not match!"
	echo "The correct checksums are printed below"
	echo "Please only update if changing GIT_TAG or build flags."
	$SCRIPT_ROOT/update_checksums.sh $MAKE_ROOT $PROJECT_ROOT $OUTPUT_BIN_DIR
	exit 1
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 -o errexit
set -o nounset
set -o pipefail

TAG="$1"

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
source "${SCRIPT_ROOT}/common.sh"

build::common::wait_for_tag $TAG