#!/bin/bash

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

EKSA_MANIFESTS_PATH="${EKSA_MANIFESTS_PATH:-/usr/lib/eks-a/manifests}" # The full path where eks-a manifests will be downloaded
EKSA_ARTIFACTS_TAR_PATH="${EKSA_ARTIFACTS_TAR_PATH:-/usr/lib/eks-a/artifacts/artifacts.tar.gz}" # The path where the tar containing all eks-a container artifacts will be stored

sudo mkdir -p $EKSA_MANIFESTS_PATH
sudo -E env "PATH=$PATH" eksctl anywhere download artifacts --retain-dir --download-dir $EKSA_MANIFESTS_PATH -v4
sudo chmod -R a+r $EKSA_MANIFESTS_PATH

ARTIFACTS_NAME_DIR=$(dirname $EKSA_ARTIFACTS_TAR_PATH)
sudo mkdir -p $ARTIFACTS_NAME_DIR
sudo -E env "PATH=$PATH" eksctl anywhere download images -o $EKSA_ARTIFACTS_TAR_PATH -v4
sudo chmod -R a+r $ARTIFACTS_NAME_DIR

# The download images command pulls down all the images in the bundle
# but after the images get saved to a tar archive, the images are still
# in the local Docker runtime, that bloats the final admin image. This can
# cause downstream resource heavy operations to fail due to lack of disk
# space. To mitigate this, we prune all the dangling and unused images and
# volumes to increase the free disk space on the admin image.
sudo docker system prune --all --volumes --force


#!/bin/bash

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

# Install packages
sudo apt-get update -y
sudo apt-get install -y python python3 python3-pip
sudo apt-get install -y awscli
sudo snap install jq


#!/bin/bash

echo $EKSA_VERSION

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

EKSCTL_VERSION="${EKSCTL_VERSION:-latest}" # The eksctl version to install (example v0.0.0)
EKSA_RELEASE_MANIFEST_URL="${EKSA_RELEASE_MANIFEST_URL:-https://anywhere-assets.eks.amazonaws.com/releases/eks-a/manifest.yaml}" # The url pointing to the eks-a releases manifest
EKSA_VERSION="${EKSA_VERSION:-latest}" # The eks-a version to install (example v0.0.0)

# Install eksctl
mkdir eksctl_tmp
if [[ "$EKSCTL_VERSION" == "latest" ]]; then
	EKSCTL_URL="https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_linux_amd64.tar.gz"
else
	EKSCTL_URL="https://github.com/weaveworks/eksctl/releases/download/${EKSCTL_VERSION}/eksctl_linux_amd64.tar.gz"
fi
curl -L --silent $EKSCTL_URL | tar xz -C ./eksctl_tmp

sudo mv eksctl_tmp/eksctl /usr/local/bin/
rm -rf eksctl_tmp

# Install eksctl-anywhere
mkdir eksa_tmp
if [[ "$EKSA_VERSION" == "latest" || "$EKSA_VERSION" == "v0.0.0" ]]; then
	EKSA_VERSION=$(curl -L --silent $EKSA_RELEASE_MANIFEST_URL |  yq e '.spec.latestVersion' -)
fi
EKSA_TAR_URL=$(curl -L --silent $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.releases[] | select(.version == "'$EKSA_VERSION'") | .eksABinary.linux.uri')
curl -L --silent $EKSA_TAR_URL | tar xz -C ./eksa_tmp

sudo mv eksa_tmp/eksctl-anywhere /usr/local/bin/
rm -rf eksa_tmp


#!/bin/bash

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

if [[ "$GO_VERSION" == "latest" ]]; then
    GO_VERSION="$(curl --silent https://go.dev/VERSION?m=text)";
    GO_URL="https://go.dev/dl/${GO_VERSION}.linux-amd64.tar.gz"
else
    GO_URL="https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
fi

sudo apt-get install -y tar
sudo apt-get install -y git

curl -L --silent $GO_URL | sudo tar xz -C /usr/local

export GOROOT=/usr/local/go
export GOPATH=/usr/local/go/packages
export GOPROXY=direct

sudo sh -c "echo 'PATH=\$PATH:$GOROOT/bin:$GOPATH/bin' >> /etc/profile.d/golang.sh"

source /etc/profile.d/golang.sh

GO=/usr/local/go/bin/go

$GO version

# required for e2e tests
sudo GOPROXY=direct GOPATH=/usr/local/go/packages $GO install gotest.tools/gotestsum@latest
sudo cp $GOPATH/bin/gotestsum /usr/local/bin/gotestsum

sudo env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $GO build -o test2json -ldflags="-s -w" cmd/test2json
sudo mv test2json /usr/local/bin/test2json


#!/bin/bash

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

# Install packages
sudo apt-get update -y
sudo apt-get install -y ipmitool


#!/bin/bash

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

# KIND_URL needs to be provided to the script as envvar

sudo apt-get install -y tar

mkdir kind_tmp

curl --silent -L $KIND_URL  | tar xz -C ./kind_tmp
chmod +x kind_tmp/kind
sudo mv kind_tmp/kind /usr/local/bin/kind
rm -rf kind_tmp


#!/bin/bash

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

# KUBECTL_URL needs to be provided to the script

curl --silent -L $KUBECTL_URL --output kubectl
chmod +x kubectl
sudo mv kubectl /usr/local/bin/kubectl


#!/bin/bash

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

sudo apt-get install -y python python3 python3-pip
sudo snap install amazon-ssm-agent --classic
sudo systemctl stop snap.amazon-ssm-agent.amazon-ssm-agent.service

SSM_ACTIVATION_DIR=/etc/amazon/ssm

sudo mkdir -p $SSM_ACTIVATION_DIR
chmod +x /home/$USER/activate_ssm.sh
sudo mv /home/$USER/activate_ssm.sh $SSM_ACTIVATION_DIR

sudo sh -c "echo '@reboot root /etc/amazon/ssm/activate_ssm.sh' >> /etc/crontab"


#!/bin/bash

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

# Enabling docker
sudo systemctl start docker
sudo systemctl enable docker

USER="${USER:-ubuntu}"
# Setting permisions to avoid sudo
sudo usermod -a -G docker $USER

# Rebooting to get permissions
sudo reboot


#!/bin/bash

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

# Package cleanup and reset cloud-init
sudo yum clean all
sudo cloud-init clean

# Remove ssh keys and hosts
sudo rm -rf /home/ec2-user/.ssh
sudo rm -rf /root/.ssh
sudo rm -f /etc/ssh/ssh_host_*

# Clean tmp
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*

# Clean cache
sudo rm -rf /var/cache/*

# Truncate audit logs
sudo touch /var/log/wtmp
sudo touch /var/log/lastlog

# Truncate other logs
sudo journalctl --flush
sudo journalctl -m --vacuum-time=1s
sudo find /var/log -type f -iname '*.log' | sudo xargs truncate -s 0
sudo find /var/log -type f -name '*.gz' -exec rm {} +

# Remove bash history
cat /dev/null > ~/.bash_history && sudo rm -f /root/.bash_history && history -c


#!/bin/bash

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

# Install prerequisites
sudo yum update -y
sudo amazon-linux-extras enable docker
sudo yum install -y docker tar

# Install yq
wget \
    --progress dot:giga \
    $YQ_URL
sudo mv yq_linux_amd64 /usr/local/bin/yq
chmod +x /usr/local/bin/yq


#!/bin/bash

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

sudo amazon-linux-extras install kernel-5.15 -y
sudo yum clean all
sudo yum update -y
sudo yum upgrade -y

sudo reboot


#!/bin/bash

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

getprops_from_ovfxml() {
/usr/bin/python - <<EOS
from xml.dom.minidom import parseString
ovfEnv = open("$1", "r").read()
dom = parseString(ovfEnv)
section = dom.getElementsByTagName("PropertySection")[0]
for property in section.getElementsByTagName("Property"):
  key = property.getAttribute("oe:key").replace('.','_')
  value = property.getAttribute("oe:value")
  print "{0}='{1}'".format(key,value)
dom.unlink()
EOS
}

[ -x /usr/bin/vmtoolsd ] || {
  echo "ERROR: VMware Tools are not installed. Exiting ..."
  exit 1
}

/usr/bin/vmtoolsd --cmd='info-get guestinfo.ovfEnv' >/tmp/ovf.xml 2>/dev/null

[ -s /tmp/ovf.xml ] || {
  echo "ERROR: Cannot get OVF parameters through VMware Tools. Exiting ..."
  exit 1
}

eval `getprops_from_ovfxml /tmp/ovf.xml`

SSM_ACTIVATION_DIR=/etc/amazon/ssm

mkdir -p $SSM_ACTIVATION_DIR

SSM_ACTIVATION_FILE=$SSM_ACTIVATION_DIR/.activated

if test -f "$SSM_ACTIVATION_FILE"; then
	echo "SSM is already activated."
else
	echo "Activating SSM Agent..."
    /snap/amazon-ssm-agent/current/amazon-ssm-agent -register -code "$ssm_activation_code" -id "$ssm_activation_id" -region "$ssm_activation_region"
    systemctl enable snap.amazon-ssm-agent.amazon-ssm-agent.service
    systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service
    touch $SSM_ACTIVATION_FILE
fi


#!/bin/bash

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

EKSA_MANIFESTS_PATH="${EKSA_MANIFESTS_PATH:-/usr/lib/eks-a/manifests}"
EKSA_ARTIFACTS_TAR_PATH="${EKSA_ARTIFACTS_TAR_PATH:-/usr/lib/eks-a/artifacts/artifacts.tar.gz}"

if test -d $EKSA_MANIFESTS_PATH; then
	echo "Manifests dir exists. Pass."
else
	echo "Manifests dir does not exist. Failing."
	exit 1
fi

if test -f $EKSA_ARTIFACTS_TAR_PATH; then
	echo "Artifacts tarball exists. Pass"
else
	echo "Artifacts tarball does not exist. Failing."
	exit 1
fi


#!/bin/bash

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

if type -p jq &>/dev/null; then
	echo "jq command exists. Pass."
else
	echo "jq command does not exist. Failing."
	exit 1
fi

if type -p python3 &>/dev/null; then
	echo "python3 command exists. Pass."
else
	echo "python3 command does not exist. Failing."
	exit 1
fi

if type -p aws &>/dev/null; then
	echo "aws command exists. Pass."
else
	echo "aws command does not exist. Failing."
	exit 1
fi


#!/bin/bash

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

CUR_STATE=$(systemctl is-active docker)
if [[ $CUR_STATE == "active" ]]; then
	echo "Docker service is active. Pass"
else
	echo "Docker service is not active. State '$CUR_STATE'. Failing."
	exit 1
fi

if type -P docker &>/dev/null; then
	echo "Docker command exists. Pass."
else
	echo "Docker command does not exist. Failing."
	exit 1
fi

GROUP='docker'
if groups $USER | grep &>/dev/null "$GROUP"; then
	echo "The '$USER' is a member of the '$GROUP' group. Pass."
else
	echo "The '$USER' is not a member of the '$GROUP' group. Failing."
	exit 1
fi


#!/bin/bash

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

 if type -p eksctl &>/dev/null; then
	echo "eksctl command exists. Pass."
else
	echo "eksctl command does not exist. Failing."
	exit 1
fi

if type -p eksctl-anywhere &>/dev/null; then
	echo "eksctl-anywhere binary exists. Pass."
else
	echo "eksctl-anywhere binary does not exist. Failing."
	exit 1
fi

if eksctl anywhere version &>/dev/null; then
	echo "eksctl anywhere command works. Pass."
else
	echo "eksctl anywhere command does not work. Failing."
	exit 1
fi


#!/bin/bash

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

source /etc/profile.d/golang.sh

if type -p go &>/dev/null; then
	echo "go command exists. Pass."
else
	echo "go command does not exist. Failing."
	exit 1
fi

if type -p git &>/dev/null; then
	echo "git command exists. Pass."
else
	echo "git command does not exist. Failing."
	exit 1
fi


#!/bin/bash

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

if type -p kind &>/dev/null; then
	echo "kind command exists. Pass."
else
	echo "kind command does not exist. Failing."
	exit 1
fi


#!/bin/bash

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

if type -p kubectl &>/dev/null; then
	echo "kubectl command exists. Pass."
else
	echo "kubectl command does not exist. Failing."
	exit 1
fi


#!/bin/bash

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

SSM_SERVICE_FILE=/etc/systemd/system/snap.amazon-ssm-agent.amazon-ssm-agent.service
if test -f "$SSM_SERVICE_FILE"; then
	echo "Amazon SSM Agent service is installed. Pass"
else
	echo "Amazon SSM Agent service is not installed."
	exit 1
fi


#!/bin/bash

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

# Package cleanup and reset cloud-init
sudo apt-get -y autoremove
sudo apt-get -y clean
sudo cloud-init clean

# Remove ssh keys and hosts
sudo rm -rf /home/ubuntu/.ssh
sudo rm -rf /root/.ssh
sudo rm -f /etc/ssh/ssh_host_*

# Clean tmp
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*

# Truncate audit logs
sudo touch /var/log/wtmp
sudo touch /var/log/lastlog

# Truncate other logs
sudo find /var/log -type f -iname '*.log' | sudo xargs truncate -s 0
sudo find /var/log -type f -name '*.gz' -exec rm {} +
sudo journalctl --rotate
sudo journalctl -m --vacuum-time=1s

# Remove bash history
cat /dev/null > ~/.bash_history && sudo rm -f /root/.bash_history && history -c


#!/bin/bash

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

# Install prerequisites
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common tar

# Install docker gpg key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

# Adding docker repo
LSB_RELEASE=$(lsb_release -cs)
ARCH=$(dpkg --print-architecture)
SOURCE="deb [arch=$ARCH] https://download.docker.com/linux/ubuntu $LSB_RELEASE stable"
sudo add-apt-repository "$SOURCE"

# Install docker and containerd
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io

# Install yq
sudo snap install yq


#!/bin/bash

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

sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade -y

sudo reboot


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

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

ARCH="$1"

OUTPUT_DIR="${MAKE_ROOT}/_output/dependencies/linux-$ARCH"
EKS_A_TOOL_BINARY_DIR="${OUTPUT_DIR}/eks-a-tools/binary"
EKS_A_TOOL_LICENSE_DIR="${OUTPUT_DIR}/eks-a-tools/licenses"

mkdir -p $EKS_A_TOOL_BINARY_DIR
mkdir -p $EKS_A_TOOL_LICENSE_DIR

declare -A project_bin_licenses=(["eksa/fluxcd/flux2"]="flux FLUX2"
                                 ["eksa/kubernetes-sigs/cluster-api"]="clusterctl CAPI"
                                 ["eksa/kubernetes-sigs/kind"]="kind KIND"
                                 ["eksd/kubernetes"]="client/bin/kubectl KUBERNETES"
                                 ["eksa/replicatedhq/troubleshoot"]="support-bundle TROUBLESHOOT"
                                 ["eksa/vmware/govmomi"]="govc GOVMOMI"
                                 ['eksa/helm/helm']="helm HELM"
                                 ['eksa/apache/cloudstack-cloudmonkey']="cmk CLOUDMONKEY")

for project in "${!project_bin_licenses[@]}"
do
  bin_license_map=(${project_bin_licenses[$project]})
  binary=${bin_license_map[0]}
  license_prefix=${bin_license_map[1]}
  cp $OUTPUT_DIR/$project/$binary $EKS_A_TOOL_BINARY_DIR/$(basename $binary)
  cp $OUTPUT_DIR/$project/ATTRIBUTION.txt $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_ATTRIBUTION.txt
  cp -r $OUTPUT_DIR/$project/LICENSES $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_LICENSES
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 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

MANIFEST_IMAGE_OVERRIDE="${IMAGE_REPO}/aws/etcdadm-bootstrap-provider:${IMAGE_TAG}"

sed -i "s,\${ETCDADM_BOOTSTRAP_IMAGE},${MANIFEST_IMAGE_OVERRIDE}," ./config/manager/manager.yaml
yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" config/manager/manager.yaml

mkdir -p $OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${TAG}
kustomize build config/default > bootstrap-components.yaml
cp bootstrap-components.yaml "$OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${TAG}"
cp ../manifests/metadata.yaml "$OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${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"
IMAGE_REPO="$5"
IMAGE_TAG="$6"

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

cd $REPO

MANIFEST_IMAGE_OVERRIDE="${IMAGE_REPO}/aws/etcdadm-controller:${IMAGE_TAG}"

sed -i "s,\${ETCDADM_CONTROLLER_IMAGE},${MANIFEST_IMAGE_OVERRIDE}," ./config/manager/manager.yaml
yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" config/manager/manager.yaml

mkdir -p $OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${TAG}
kustomize build config/default > bootstrap-components.yaml

cp bootstrap-components.yaml "$OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${TAG}"
cp ../manifests/metadata.yaml "$OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${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

ARTIFACTS_PATH="$1"
BASE_DIRECTORY="$2"
TAG="$3"

# TODO: use cert-manager make target to generate the cert-manager.yaml file when we upgrade cert-manager version (v1.7.0-alpha.0)
#
# The following commits would need to be added as patches:
# https://github.com/cert-manager/cert-manager/commit/6734e9b7469288b51848eb209597a1920e4801ea
# https://github.com/cert-manager/cert-manager/commit/32d716654a1091e99e80c10a2798cd839a705713
#
# Then would need to run the make target as follows (can specify -jN, like `-j8`, to run whatever targets that can in parallel):
# make -f make/Makefile bin/yaml/cert-manager.yaml
mkdir -p $ARTIFACTS_PATH/manifests/$TAG
cp $BASE_DIRECTORY/projects/cert-manager/cert-manager/manifests/cert-manager.yaml $ARTIFACTS_PATH/manifests/$TAG


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

TAG="${1?Specify first argument - git version tag}"
ARTIFACTS_PATH="${2?Specify second argument - artifacts path}"
REGISTRY="${3?Specify third argument - image registry}"

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

mkdir -p $ARTIFACTS_PATH

function build::install::helm(){
  mkdir -p $HELM_BIN
  export PATH=$HELM_BIN:$PATH
  curl -s https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | HELM_INSTALL_DIR=$HELM_BIN bash
}

function build::cilium::manifests(){
  export HELM_EXPERIMENTAL_OCI=1
  mkdir -p _output/manifests/cilium/$TAG
  helm template cilium oci://$REGISTRY/cilium --version ${TAG#"v"} --namespace kube-system -f manifests/cilium-eksa.yaml \
    --set operator.image.tag=$TAG --set image.tag=$TAG --set image.repository="$REGISTRY/cilium" --set operator.image.repository="$REGISTRY/operator" > _output/manifests/cilium/${TAG}/cilium.yaml
}

build::install::helm
build::cilium::manifests

cp -rf _output/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 nounset
set -o pipefail

IMAGE_REGISTRY="${1?Specify first argument - image registry}"
IMAGE_NAME="${2?Specify second argument - image name}"
IMAGE_TAG="${3? Specify third argument - image tag}"
DIGEST_DST="${4? Specify fourth argument - destination file for image digest}"

IMAGE=$IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_TAG

SHA256=$(skopeo inspect --raw docker://$IMAGE | sha256sum | awk '{print $1;}')
DIGEST="sha256:$SHA256"

echo -n $DIGEST > $DIGEST_DST


#!/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"
GIT_HASH="$7"
BINARY_DEPS_DIR="$8"

LICENSES_PATH="$OUTPUT_DIR/LICENSES"
ATTRIBUTION_PATH="$OUTPUT_DIR/ATTRIBUTION.txt"
REPO_PATH="containerd"

MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${MAKE_ROOT}/../../../build/lib/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"
    TAR_STAGING_DIR="${OUTPUT_BIN_DIR}/${OS}-${ARCH}/tar-staging"

    build::common::echo_and_run mkdir -p ${TAR_STAGING_DIR}/usr/local/{bin,sbin} ${TAR_STAGING_DIR}/etc/systemd/system
		build::common::echo_and_run find ${OUTPUT_BIN_DIR}/${OS}-${ARCH} -not -type d -execdir cp "{}" ${TAR_STAGING_DIR}/usr/local/bin ";"
    build::common::echo_and_run cp $ATTRIBUTION_PATH ${TAR_STAGING_DIR}/usr/local/bin/CONTAINERD_ATTRIBUTION.txt
    build::common::echo_and_run cp ${BINARY_DEPS_DIR}/${OS}-${ARCH}/eksa/opencontainers/runc/runc ${TAR_STAGING_DIR}/usr/local/sbin
    build::common::echo_and_run cp ${BINARY_DEPS_DIR}/${OS}-${ARCH}/eksa/opencontainers/runc/ATTRIBUTION.txt ${TAR_STAGING_DIR}/usr/local/sbin/RUNC_ATTRIBUTION.txt
    build::common::echo_and_run cp ${REPO_PATH}/containerd.service ${TAR_STAGING_DIR}/etc/systemd/system

    build::common::create_tarball ${TAR_PATH}/${TAR_FILE} ${TAR_STAGING_DIR} .

    rm -rf ${TAR_STAGING_DIR}
  done
  echo $GIT_HASH > $TAR_PATH/githash
}

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 -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

CAPI_REGISTRY_PREFIX="${IMAGE_REPO}/kubernetes-sigs/cluster-api"
KUBE_RBAC_PROXY_LATEST_TAG=latest

make set-manifest-image \
    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/cluster-api-controller MANIFEST_TAG=$IMAGE_TAG \
    TARGET_RESOURCE="./config/default/manager_image_patch.yaml"

# Set the kubeadm bootstrap image to the production bucket.
make set-manifest-image \
    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/kubeadm-bootstrap-controller MANIFEST_TAG=$IMAGE_TAG \
    TARGET_RESOURCE="./bootstrap/kubeadm/config/default/manager_image_patch.yaml"

# Set the kubeadm control plane image to the production bucket.
make set-manifest-image \
    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/kubeadm-control-plane-controller MANIFEST_TAG=$IMAGE_TAG  \
    TARGET_RESOURCE="./controlplane/kubeadm/config/default/manager_image_patch.yaml"

make set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE="./config/default/manager_pull_policy.yaml"
make set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE="./bootstrap/kubeadm/config/default/manager_pull_policy.yaml"
make set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE="./controlplane/kubeadm/config/default/manager_pull_policy.yaml"

yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" config/manager/manager.yaml
yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" bootstrap/kubeadm/config/manager/manager.yaml
yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" controlplane/kubeadm/config/manager/manager.yaml

## Build the manifests
make release-manifests

## Build the development manifests
make set-manifest-image \
    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/capd-manager MANIFEST_TAG=$IMAGE_TAG \
    TARGET_RESOURCE="./test/infrastructure/docker/config/default/manager_image_patch.yaml"
make set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE="./test/infrastructure/docker/config/default/manager_pull_policy.yaml"
make release-manifests-dev

mkdir -p $OUTPUT_DIR/manifests/{bootstrap-kubeadm,cluster-api,control-plane-kubeadm,infrastructure-docker}/$TAG
cp out/bootstrap-components.yaml "$OUTPUT_DIR/manifests/bootstrap-kubeadm/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/bootstrap-kubeadm/$TAG"

cp out/control-plane-components.yaml "$OUTPUT_DIR/manifests/control-plane-kubeadm/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/control-plane-kubeadm/$TAG"

cp out/core-components.yaml "$OUTPUT_DIR/manifests/cluster-api/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/cluster-api/$TAG"

cp out/infrastructure-components-development.yaml "$OUTPUT_DIR/manifests/infrastructure-docker/$TAG/infrastructure-components-development.yaml"
cp test/infrastructure/docker/templates/cluster-template-development.yaml "$OUTPUT_DIR/manifests/infrastructure-docker/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/infrastructure-docker/$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"
IMAGE_REPO="$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

KUBE_RBAC_PROXY_IMAGE_OVERRIDE=${IMAGE_REPO}/brancz/kube-rbac-proxy:latest
sed -i 's,image: .*,image: '"${KUBE_RBAC_PROXY_IMAGE_OVERRIDE}"',' ./config/default-with-metrics-port/manager_auth_proxy_patch.yaml

make release-manifests-metrics-port \
  RELEASE_DIR="out" \
  IMG="${IMAGE_REPO}/kubernetes-sigs/cluster-api-provider-cloudstack/release/manager:$IMAGE_TAG"

mkdir -p $OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG
cp templates/cluster-template.yaml "$OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG"
cp out/infrastructure-components.yaml "$OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG"
cp out/metadata.yaml "$OUTPUT_DIR/manifests/infrastructure-cloudstack/$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"
IMAGE_REPO="$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

yq eval -i -P ".spec.template.spec.containers[0].args += [\"--namespace=eksa-system\"]" config/manager/manager.yaml

make manifests STAGE="release" \
  MANIFEST_DIR="out" \
  PULL_POLICY="IfNotPresent" \
  IMAGE="${IMAGE_REPO}/kubernetes-sigs/cluster-api-provider-vsphere/release/manager:$IMAGE_TAG"

mkdir -p $OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG
cp out/cluster-template.yaml "$OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG"
cp out/infrastructure-components.yaml "$OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG"
cp metadata.yaml "$OUTPUT_DIR/manifests/infrastructure-vsphere/$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 -xe
set -o errexit
set -o nounset

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

image_os="${1?Specify the first argument - image os}"
image_os_version="${2?Specify the second argument - image os version}"
release_channel="${3?Specify the third argument - release channel}"
image_format="${4?Specify the fourth argument - image format}"
artifacts_bucket=${5-$ARTIFACTS_BUCKET}
latest=${6-latest}

# Download and setup latest image-builder cli
image_build::common::download_latest_dev_image_builder_cli "${HOME}" $artifacts_bucket 'amd64' 'jackson-test-build' # $latest

image_os_version_arg=""
if [[ "$image_os" == "ubuntu" ]]; then
  image_os_version_arg="--os-version ${image_os_version:0:2}.${image_os_version:2:2}"
elif [[ "$image_os" == "redhat" ]]; then
  image_os_version_arg="--os-version $image_os_version"
fi

image_builder_config_file="${HOME}/image_builder_config_file"
redhat_config_file="${HOME}/redhat_config_file"
if [[ $image_os == "redhat" ]]; then
  jq --null-input \
    --arg rhel_username $RHSM_USERNAME \
    --arg rhel_password $RHSM_PASSWORD \
    --arg iso_url "https://redhat-iso-pdx.s3.us-west-2.amazonaws.com/8.4/rhel-8.4-x86_64-dvd.iso" \
    --arg iso_checksum_type "sha256" \
    --arg iso_checksum "ea5f349d492fed819e5086d351de47261c470fc794f7124805d176d69ddf1fcd" \
    '{"rhel_username": $rhel_username, "rhel_password": $rhel_password, "iso_url": $iso_url, "iso_checksum_type": $iso_checksum_type, "iso_checksum": $iso_checksum}' > $redhat_config_file
fi

if [[ $image_format == "ova" ]]; then
  # Setup vsphere config
  vsphere_config_file="${HOME}/vsphere_config_file"
  echo "${VSPHERE_CONNECTION_DATA}" > $vsphere_config_file

  # Run image-builder cli
  if [[ $image_os == "redhat" ]]; then
    jq -s add $vsphere_config_file $redhat_config_file > $image_builder_config_file
  else
    image_builder_config_file=$vsphere_config_file
  fi

  "${HOME}"/image-builder build --hypervisor vsphere --os $image_os $image_os_version_arg --vsphere-config $image_builder_config_file --release-channel $release_channel
elif [[ $image_format == "raw" ]]; then
  # Run image-builder cli
  if [[ $image_os == "ubuntu" ]]; then
    "${HOME}"/image-builder build --hypervisor baremetal --os $image_os $image_os_version_arg --release-channel $release_channel
    echo "done with image builder"
  elif [[ $image_os == "redhat" ]]; then
    echo "Creating baremetal config"
    echo "$(jq --arg extra_rpms "https://redhat-iso-pdx.s3.us-west-2.amazonaws.com/8.4/rpms/kmod-megaraid_sas-07.719.06.00_el8.4-1.x86_64.rpm" \
      '. += {"extra_rpms": $extra_rpms}' $redhat_config_file)" > $image_builder_config_file

    "${HOME}"/image-builder build --hypervisor baremetal --os $image_os $image_os_version_arg --release-channel $release_channel --baremetal-config $image_builder_config_file
  fi
elif [[ $image_format == "cloudstack" ]]; then
  if [[ $image_os != "redhat" ]]; then
    echo "Cloudstack builds do not support any non-redhat OS"
    exit 1
  fi

  echo "Creating cloudstack config"
  image_builder_config_file=$redhat_config_file
  "${HOME}"/image-builder build --hypervisor cloudstack --os $image_os $image_os_version_arg --release-channel $release_channel --cloudstack-config $image_builder_config_file
elif [[ $image_format == "ami" ]]; then
  if [[ $image_os != "ubuntu" ]]; then
    echo "AMI builds do not support any non-ubuntu os"
    exit 1
  fi

  echo "Creating AMI config"
  jq --null-input \
    --arg ami_filter_owners "099720109477" \
    --arg custom_role_names "$MAKE_ROOT/ansible/roles/load_additional_files" \
    --arg ansible_extra_vars "@$MAKE_ROOT/packer/ami/ansible_extra_vars.yaml" \
    --arg manifest_output "$MANIFEST_OUTPUT" \
    '{"ami_filter_owners": $ami_filter_owners, "custom_role_names": $custom_role_names, "ansible_extra_vars": $ansible_extra_vars, "manifest_output": $manifest_output}' > $image_builder_config_file
  "${HOME}"/image-builder build --hypervisor ami --os $image_os $image_os_version_arg --release-channel $release_channel --ami-config $image_builder_config_file
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 -x
set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="${1?Specify first argument - repo root}"
PROJECT_PATH="${2?Specify second argument - Project path}"
RELEASE_BRANCH="${3?Specify third argument - Release branch}"
AMI_ID="${4?Specify fourth argument - AMI ID to create instance}"
INSTANCE_TYPE="${5?Specify fifth argument - Instance type to create}"
KEY_NAME="${6?Specify sixth argument - Key name to associate with instance}"
IMAGE_OS="${7?Specify seventh argument - Raw build target name}"
IMAGE_OS_VERSION="${8?Specify eight argument - Raw build target name}"
IMAGE_FORMAT="${9?Specify ninth argument - Image format}"
LATEST="${10?Specify the tenth argument - Latest tag}"
ARTIFACTS_PATH="${11?Specify the eleventh argument - Artifacts path}"
BRANCH_NAME="${12?Specify the twelveth argument - Branch Name}"

CODEBUILD_CI="${CODEBUILD_CI:-false}"
CI="${CI:-false}"

if [ "$CODEBUILD_CI" = "true" ]; then
    KEY_NAME="$KEY_NAME-$CODEBUILD_BUILD_ID"
    CREATOR=$CODEBUILD_BUILD_ID
elif [ "$CI" = "true" ]; then
    KEY_NAME="$KEY_NAME-$PROW_JOB_ID"
    CREATOR=$PROW_JOB_ID
fi

if [ "$IMAGE_FORMAT" != "raw" ] && [ "$IMAGE_FORMAT" != "cloudstack" ]; then
  echo "Unsupported image format. This script only supports building raw and cloudstack builds"
  exit 1
fi

REPO_NAME=$(basename $REPO_ROOT)
KEY_LOCATION=$REPO_ROOT/$PROJECT_PATH/$KEY_NAME.pem
REMOTE_HOME_DIR="/home/ubuntu"
REMOTE_PROJECT_PATH=$REMOTE_HOME_DIR/$REPO_NAME/$PROJECT_PATH
REMOTE_ARTIFACTS_PATH=$REMOTE_HOME_DIR/$PROJECT_PATH/artifacts
SSH_OPTS="-i $KEY_LOCATION -o StrictHostKeyChecking=no -o ConnectTimeout=120"

terminate_instance() {
    aws ec2 terminate-instances --instance-ids $1
}
delete_key_pair() {
    aws ec2 delete-key-pair --key-name $1
}

# Delete keypair and instance when exiting script. This will prevent
# lingering instances by deleting the EC2 instance regardless of success
# or failure of build
trap 'if [ -n "$INSTANCE_ID" ]; then terminate_instance $INSTANCE_ID; fi; delete_key_pair $KEY_NAME' EXIT

# Check if key of that name already exists, else create keypair
# Query and save the key contents into a local file for
# communicating to EC2 instance via SSH
if ! aws ec2 wait key-pair-exists --key-names=$KEY_NAME 2>/dev/null ; then
    aws ec2 create-key-pair --key-name $KEY_NAME --tag-specifications "ResourceType=key-pair,Tags=[{Key=Creator,Value=$CREATOR}]" --query "KeyMaterial" --output text > $KEY_LOCATION
fi
chmod 600 $KEY_LOCATION

RUN_INSTANCE_EXTRA_ARGS=""
if [ "$CODEBUILD_CI" = "true" ]; then
    # Select a random subnet from Codebuild project's private subnet list
    SUBNET_ID_LIST=$RAW_IMAGE_BUILD_SUBNET_ID
    SUBNET_COUNT=$(echo $SUBNET_ID_LIST | awk -F\, '{print NF}')
    INDEX=$((($RANDOM % $SUBNET_COUNT) + 1))
    SUBNET_ID=$(cut -d',' -f${INDEX} <<< $SUBNET_ID_LIST)

    # Query the availability zone that this subnet exists in
    SUBNET_AZ=$(aws ec2 describe-subnets --subnet-ids $SUBNET_ID --query "Subnets[].AvailabilityZone" --output text)

    # Define extra args to run the instance in the same subnet and use
    # the same security group as Codebuild
    RUN_INSTANCE_EXTRA_ARGS="--subnet-id $SUBNET_ID --placement AvailabilityZone=$SUBNET_AZ --security-group-ids $RAW_IMAGE_BUILD_SECURITY_GROUP --associate-public-ip-address --iam-instance-profile Name=eksa-imagebuilder-instance-profile"
fi

MAX_RETRIES=20
for i in $(seq 1 $MAX_RETRIES); do
    echo "Attempt $(($i)) of instance launch"

    # Create a single EC2 instance with provided instance type and AMI
    # Query the instance ID for use in future commands
    INSTANCE_ID=$(aws ec2 run-instances --count 1 --image-id=$AMI_ID --instance-type $INSTANCE_TYPE --key-name $KEY_NAME $RUN_INSTANCE_EXTRA_ARGS --tag-specifications "ResourceType=instance,Tags=[{Key=Creator,Value=$CREATOR}]" --query "Instances[0].InstanceId" --output text --metadata-options "HttpEndpoint=enabled,HttpTokens=required,HttpPutResponseHopLimit=2") && break

    if [ "$i" = "$MAX_RETRIES" ]; then
        exit 1
    fi
    sleep 30
done

# Wait in loop until instance is running
aws ec2 wait instance-running --instance-ids $INSTANCE_ID

# Get the public DNS of the instance to use as SSH hostname
PUBLIC_DNS_NAME=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query "Reservations[].Instances[].PublicDnsName" --output text)
REMOTE_HOST=ubuntu@$PUBLIC_DNS_NAME

# rsync might sometimes fail with flaky connection issues, so
# implementing retry logic will make it more robust to flakes
for i in $(seq 1 $MAX_RETRIES); do
    echo "Attempt $(($i))"

    # Transfer the repo contents from the CI environment to the EC2 instance
    rsync -azh -e "ssh $SSH_OPTS" $REPO_ROOT $REMOTE_HOST:~/ && echo "Files transferred!" && break

    if [ "$i" = "$MAX_RETRIES" ]; then
        exit 1
    fi
    sleep 10
done

# If not running on Codebuild, exit gracefully
if [ "$CODEBUILD_CI" = "false" ]; then
    exit 0
fi

SSH_COMMANDS="sudo usermod -a -G kvm ubuntu; sudo chmod 666 /dev/kvm; sudo chown root:kvm /dev/kvm; export IMAGE_OS=$IMAGE_OS IMAGE_OS_VERSION=$IMAGE_OS_VERSION IMAGE_FORMAT=$IMAGE_FORMAT; CODEBUILD_CI=true CODEBUILD_SRC_DIR=/home/ubuntu/$REPO_NAME BRANCH_NAME=$BRANCH_NAME ARTIFACTS_PATH=$REMOTE_ARTIFACTS_PATH $REMOTE_PROJECT_PATH/build/build_image.sh $IMAGE_OS $IMAGE_OS_VERSION $RELEASE_BRANCH $IMAGE_FORMAT $ARTIFACTS_BUCKET $LATEST"
if [[ "$IMAGE_OS" == "redhat" ]]; then
  SSH_COMMANDS="export RHSM_USERNAME='$RHSM_USERNAME' RHSM_PASSWORD='$RHSM_PASSWORD'; $SSH_COMMANDS"
fi

ssh $SSH_OPTS $REMOTE_HOST $SSH_COMMANDS
echo "done with ssh command"
# Copy built raw image from the instance back into the CI build environment
OUTPUT_IMAGE_BLOB="*.gz"
OUTPUT_IMAGE_FORMAT=$IMAGE_FORMAT
if [[ "$IMAGE_FORMAT" == "cloudstack" ]]; then
  OUTPUT_IMAGE_BLOB="*.qcow2"
fi
mkdir -p $ARTIFACTS_PATH
scp $SSH_OPTS $REMOTE_HOST:$REMOTE_HOME_DIR/$OUTPUT_IMAGE_BLOB $REPO_ROOT/$PROJECT_PATH/
scp $SSH_OPTS $REMOTE_HOST:$REMOTE_ARTIFACTS_PATH/$RELEASE_BRANCH/$IMAGE_OS/$IMAGE_OS_VERSION/$OUTPUT_IMAGE_FORMAT/{EKSD_MANIFEST_URL,KUBERNETES_VERSION,packer.log} $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 -o errexit
set -o nounset
set -o pipefail

EKSD_RELEASE_BRANCH="${1?Specify first argument - EKS-D release branch}"
AMI_MANIFEST_OUTPUT="${2?Specify second argument - AMI manifest output file from packer}"
IMAGE_FORMAT="${3?Specify third argument - Format for exported image \(vmdk\|raw\|vhd\)}"
S3_DST_EXPORT_PATH="${4?Specify fourth argument - Destination S3 path}"
REPLICAS="${5?Specify fourth argument - Comma separated list of s3 destinations for exported image copies}"

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

ARTIFACT_ID=$(cat $AMI_MANIFEST_OUTPUT | jq -r '.builds[0].artifact_id')
ARTIFACT_ID_SPLIT=(${ARTIFACT_ID//:/ })
AMI_ID=${ARTIFACT_ID_SPLIT[1]}

REPLICAS_SPLIT=(${REPLICAS//,/ })

DST_BUCKET_PATH=${S3_DST_EXPORT_PATH#"s3://"}
DST_BUCKET_NAME=${DST_BUCKET_PATH%%/*}
DST_PATH=${DST_BUCKET_PATH#"$DST_BUCKET_NAME/"}

EKSD_RELEASE=$(build::eksd_releases::get_eksd_release_name $EKSD_RELEASE_BRANCH)
EXPORTED_IMAGE_PREFIX="$DST_PATH/$EKSD_RELEASE-"

EXPORT_RESPONSE=$(aws ec2 export-image --disk-image-format $IMAGE_FORMAT --s3-export-location S3Bucket=$DST_BUCKET_NAME,S3Prefix=$EXPORTED_IMAGE_PREFIX --image-id $AMI_ID)
echo $EXPORT_RESPONSE

EXPORT_TASK_ID=$(echo $EXPORT_RESPONSE | jq -r '.ExportImageTaskId')
EXPORTED_IMAGE_LOCATION="s3://${DST_BUCKET_NAME}/${EXPORTED_IMAGE_PREFIX}${EXPORT_TASK_ID}.${IMAGE_FORMAT}"

FINAL_STATUSES=(completed deleted)
STATUS=$(echo $EXPORT_RESPONSE | jq -r '.Status')
STATUS_MESSAGE=$(echo $EXPORT_RESPONSE | jq -r '.StatusMessage')
PROGRESS=$(echo $EXPORT_RESPONSE | jq -r '.Progress')

until [[ "${FINAL_STATUSES[*]}" =~ "${STATUS}" ]]; do
  echo "Image import is $STATUS: $STATUS_MESSAGE $PROGRESS%"
  sleep 30

  DESCRIBE_RESPONSE=$(aws ec2 describe-export-image-tasks --export-image-task-ids $EXPORT_TASK_ID)
  STATUS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Status')
  STATUS_MESSAGE=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].StatusMessage')
  PROGRESS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Progress')
done

if [[ "$STATUS" != "completed" ]]; then
    echo "Image import failed: $STATUS - $STATUS_MESSAGE"
    exit 1
fi

echo "Image import for ami $AMI_ID succeeded"

for dst in "${REPLICAS_SPLIT[@]}"
do
  echo "Copying exported image to $dst"
  aws s3 cp --no-progress --acl public-read $EXPORTED_IMAGE_LOCATION $dst
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 -o errexit
set -o nounset
set -o pipefail

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

RELEASE_CHANNEL="${1?Specify first argument - EKS-D release channel}"
FORMAT="${2?Specify second argument - Image format}"
BOTTLEROCKET_DOWNLOAD_PATH="${3?Specify third argument - Download path for Bottlerocket-related files}"
PROJECT_PATH="${4?Specify fourth argument - Project path}"
LATEST_TAG="${5?Specify fifth argument - S3 destination folder for latest artifact upload}"

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

# Setting version and URL parameters for downloading the OVA
OS_DOWNLOAD_PATH=
KUBEVERSION=$(echo $RELEASE_CHANNEL | tr '-' '.')
BOTTLEROCKET_RELEASE_VERSION=$(yq e ".${RELEASE_CHANNEL}.${FORMAT}-release-version" $MAKE_ROOT/BOTTLEROCKET_RELEASES)
if [[ $BOTTLEROCKET_RELEASE_VERSION == "null" ]] ; then
  echo "Bottlerocket build for ${RELEASE_CHANNEL} is not enabled. Terminating silently."
  exit 0
fi
case $FORMAT in
ami)
  VARIANT="aws"
  TARGET="bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.img.lz4"
  ;;
raw)
  VARIANT="metal"
  TARGET="bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.img.lz4"
  ;;
ova)
  VARIANT="vmware"
  TARGET="bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.ova"
  ;;
*)
  echo "Invalid image format: $FORMAT"
  exit 1
  ;;
esac

BOTTLEROCKET_METADATA_URL="https://updates.bottlerocket.aws/2020-07-07/${VARIANT}-k8s-${KUBEVERSION}/x86_64/"
BOTTLEROCKET_TARGETS_URL="https://updates.bottlerocket.aws/targets/"
OS_DOWNLOAD_PATH=${BOTTLEROCKET_DOWNLOAD_PATH}/${FORMAT}
rm -rf $OS_DOWNLOAD_PATH

# Downloading the TARGET from the Bottlerocket target location using Tuftool
build::common::echo_and_run tuftool download "${OS_DOWNLOAD_PATH}" \
    --target-name "${TARGET}" \
    --root "${BOTTLEROCKET_DOWNLOAD_PATH}/root.json" \
    --metadata-url "${BOTTLEROCKET_METADATA_URL}" \
    --targets-url "${BOTTLEROCKET_TARGETS_URL}"

# Post processing for aws and metal variants
if [[ $VARIANT == "aws" ]] || [[ $VARIANT == "metal" ]]; then
  BOTTLEROCKET_IMG="${TARGET%.lz4}"
  build::common::echo_and_run lz4 --decompress ${OS_DOWNLOAD_PATH}/${TARGET} ${OS_DOWNLOAD_PATH}/${BOTTLEROCKET_IMG}
  build::common::echo_and_run gzip ${OS_DOWNLOAD_PATH}/${BOTTLEROCKET_IMG}
  rm -f ${OS_DOWNLOAD_PATH}/${TARGET}
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.

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

function image_build::common::download_latest_dev_image_builder_cli() {
  local -r download_location=${1-/usr/bin}
  local -r artifacts_bucket=${2-$ARTIFACTS_BUCKET}
  local -r arch=${3-amd64}
  local -r latest=${4-latest}

  local -r latest_tar_url=$(build::common::get_latest_eksa_asset_url $artifacts_bucket 'aws/image-builder' $arch $latest)

  # Download the tar ball and decompress
  local -r http_code=$(curl -s -w "%{http_code}" $latest_tar_url -o image-builder.tar.gz)
  if [[ "$http_code" != "200" ]]; then
    echo "Error downloading latest image builder cli"
    exit 1
  fi
  tar -xvf image-builder.tar.gz --directory $download_location/ ./image-builder
  rm -rf image-builder.tar.gz
}


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

RELEASE_BRANCH="${1?Specify first argument - release branch}"
IMAGE_FORMAT="${2?Specify second argument - image format}"
IMAGE_OS="${3?Specify third argument - image OS}"
ARTIFACTS_BUCKET="${4?Specify fourth argument - artifact bucket}"
OVA_PATH="${5? Specify fifth argument - ova output path}"
ADDITIONAL_PAUSE_IMAGE_FROM="${6? Specify sixth argument - additional pause image}"
LATEST_TAG="${7? Specify seventh argument - latest tag}"
IMAGE_BUILDER_DIR="${8? Specify eighth argument - image-builder directory}"
IMAGE_OS_DIR="${9? Specify ninth argument - image-os-dir}"
IMAGE_OS_VERSION="${10? Specify tenth argument - image-os-version}"

CI="${CI:-false}"
CODEBUILD_CI="${CODEBUILD_CI:-false}"
DEV_RELEASE=false
if [[ $CI == true || $CODEBUILD_CI == true ]]; then
  DEV_RELEASE=true
fi

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

function env_and_envsubst()
{
    echo -e "\nRunning envsubst with input file $2 saving to $3 with ENV: "
    local -r env_vars=(${1//:/ })
    for var in "${env_vars[@]}"; do
        local var_name=${var:1}
        echo "$var_name: ${!var_name:-}"
    done
    envsubst "$1" < "$2" > "$3"
}

# Preload release yaml
echo "Loading EKSD manifest from: $(build::eksd_releases::get_release_yaml_url $RELEASE_BRANCH)"
build::eksd_releases::load_release_yaml $RELEASE_BRANCH > /dev/null

echo "Loading EKSA manifest from: $(build::eksa_releases::get_eksa_release_manifest_url $DEV_RELEASE $LATEST_TAG)"
build::eksa_releases::load_bundle_manifest $DEV_RELEASE $LATEST_TAG > /dev/null

OUTPUT_CONFIGS="$MAKE_ROOT/_output/$RELEASE_BRANCH/$IMAGE_FORMAT/$IMAGE_OS_DIR/config"
mkdir -p $OUTPUT_CONFIGS

export CNI_SHA="sha256:$(build::eksd_releases::get_eksd_component_sha 'cni-plugins' $RELEASE_BRANCH)"
export PLUGINS_ASSET_BASE_URL=$(build::eksd_releases::get_eksd_cni_asset_base_url $RELEASE_BRANCH)
export CNI_VERSION=$(build::eksd_releases::get_eksd_component_version 'cni-plugins' $RELEASE_BRANCH)

# Get CNI sha256 to validate cni plugins in image are from eks-d
# Use sha from manfiest to validate tar and then generate sha from specific binary
echo "Downloading cni plugins to get shasum of host-device plugin for validation during image building"
TMP_CNI="$HOME/tmp/eks-image-builder-cni"
mkdir -p $TMP_CNI
curl -o $TMP_CNI/cni-plugins.tar.gz "$PLUGINS_ASSET_BASE_URL/$CNI_VERSION/cni-plugins-linux-amd64-$CNI_VERSION.tar.gz"
echo "$(echo $CNI_SHA | sed -E 's/.*sha256:(.*)$/\1/') $TMP_CNI/cni-plugins.tar.gz" > $TMP_CNI/cni.sha256
sha256sum -c $TMP_CNI/cni.sha256
tar -zxvf $TMP_CNI/cni-plugins.tar.gz -C $TMP_CNI ./host-device
export CNI_HOST_DEVICE_SHA256="$(sha256sum $TMP_CNI/host-device | awk -F ' ' '{print $1}')"
rm -rf $TMP_CNI

env_and_envsubst '$CNI_SHA:$PLUGINS_ASSET_BASE_URL:$CNI_VERSION:$CNI_HOST_DEVICE_SHA256' \
    "$MAKE_ROOT/packer/config/cni.json.tmpl" \
    "$OUTPUT_CONFIGS/cni.json"

export PAUSE_IMAGE=$(build::eksd_releases::get_eksd_kubernetes_image_url 'pause-image' $RELEASE_BRANCH)
env_and_envsubst '$PAUSE_IMAGE:$HTTP_PROXY:$HTTPS_PROXY:$NO_PROXY' \
    "$MAKE_ROOT/packer/config/common.json.tmpl" \
    "$OUTPUT_CONFIGS/common.json"

export IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $RELEASE_BRANCH)
export KUBERNETES_ASSET_BASE_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $RELEASE_BRANCH)
export KUBERNETES_VERSION=$(build::eksd_releases::get_eksd_component_version "kubernetes" $RELEASE_BRANCH)
export KUBERNETES_SERIES="v${RELEASE_BRANCH/-/.}"
export EKSD_NAME=$(build::eksd_releases::get_eksd_release_name $RELEASE_BRANCH)
EKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $RELEASE_BRANCH)
export KUBERNETES_FULL_VERSION="$KUBERNETES_VERSION-eks-$RELEASE_BRANCH-$EKSD_RELEASE"
export ETCD_HTTP_SOURCE=$(build::eksd_releases::get_eksd_component_url "etcd" $RELEASE_BRANCH)
export ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version "etcd" $RELEASE_BRANCH)
export ETCD_SHA256=$(build::eksd_releases::get_eksd_component_sha "etcd" $RELEASE_BRANCH)
export ETCDADM_HTTP_SOURCE=${ETCDADM_HTTP_SOURCE:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'etcdadm' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}
export ETCDADM_VERSION='v0.1.5'
export CRICTL_URL=${CRICTL_URL:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'crictl' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}
export CRICTL_SHA256="${CRICTL_SHA256:-$(build::eksa_releases::get_eksa_component_asset_artifact_checksum 'eksD' 'crictl' 'sha256' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}"

export CONTAINERD_URL=${CONTAINERD_URL:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'containerd' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}
export CONTAINERD_SHA256="${CONTAINERD_SHA256:-$(build::eksa_releases::get_eksa_component_asset_artifact_checksum 'eksD' 'containerd' 'sha256' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}"
# TEMP - workaround released image-builders using the main branch
# remove this before next release and after patch image builder to use specific release tag instead of main
if [[ "$CONTAINERD_URL" == "null" ]]; then
    export CONTAINERD_URL="https://github.com/containerd/containerd/releases/download/v1.6.19/cri-containerd-cni-1.6.19-linux-amd64.tar.gz"
    export CONTAINERD_SHA256="0457907ec410c2172829f6d1808f43fd2b83395a242bcb677cfe26320df13d5d"
fi

env_and_envsubst '$IMAGE_REPO:$KUBERNETES_ASSET_BASE_URL:$KUBERNETES_VERSION:$KUBERNETES_SERIES:$CRICTL_URL:$CRICTL_SHA256:$CONTAINERD_URL:$CONTAINERD_SHA256:$ETCD_HTTP_SOURCE:$ETCD_VERSION:$ETCDADM_HTTP_SOURCE:$ETCD_SHA256:$ETCDADM_VERSION:$KUBERNETES_FULL_VERSION' \
    "$MAKE_ROOT/packer/config/kubernetes.json.tmpl" \
    "$OUTPUT_CONFIGS/kubernetes.json"

ADDITIONAL_PAUSE_IMAGE_VERSION_BASE_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $ADDITIONAL_PAUSE_IMAGE_FROM)
ADDITIONAL_PAUSE_KUBERNETES_VERSION=$(build::eksd_releases::get_eksd_component_version "kubernetes" $ADDITIONAL_PAUSE_IMAGE_FROM)
export ADDITIONAL_PAUSE_IMAGE=$ADDITIONAL_PAUSE_IMAGE_VERSION_BASE_URL/$ADDITIONAL_PAUSE_KUBERNETES_VERSION/bin/linux/amd64/pause.tar
env_and_envsubst '$ADDITIONAL_PAUSE_IMAGE' \
    "$MAKE_ROOT/packer/config/additional_components.json.tmpl" \
    "$OUTPUT_CONFIGS/additional_components.json"

# Write kubernetes version and the eksd manifest url consumed to output directory
mkdir -p $OVA_PATH
echo "$KUBERNETES_VERSION" > "$OVA_PATH"/KUBERNETES_VERSION
export EKSD_MANIFEST_URL=$(build::eksd_releases::get_release_yaml_url $RELEASE_BRANCH)
echo "$EKSD_MANIFEST_URL" > "$OVA_PATH"/EKSD_MANIFEST_URL

env_and_envsubst '$CNI_VERSION:$ETCD_VERSION:$ETCD_SHA256:$ETCDADM_VERSION:$PAUSE_IMAGE:$CNI_HOST_DEVICE_SHA256' \
    "$MAKE_ROOT/packer/config/validate_goss_inline_vars.json.tmpl" \
    "$OUTPUT_CONFIGS/validate_goss_inline_vars.json"

env_and_envsubst '$EKSD_NAME' \
    "$MAKE_ROOT/packer/config/ovf_custom_properties.json.tmpl" \
    "$OUTPUT_CONFIGS/ovf_custom_properties.json"

# This is the IP address that Packer will create the server on to host the local
# directory containing the kickstart config
if [ "$IMAGE_FORMAT" = "ova" ] && \
    ( [ "$IMAGE_OS" = "redhat" ] || ( [ "$IMAGE_OS" = "ubuntu" ] && [ "$IMAGE_OS_VERSION" != "2004" ] )  ); then
    echo "Finding correct interface for packer temporary http server"
    ACTIVE_INTERFACE=""
    if [ "$(uname -s)" = "Linux" ]; then
        INTERFACES=($(ls /sys/class/net))
        for interface in "${INTERFACES[@]}"; do
            if [ "$interface" = "eth0" ] || [ "$interface" = "en0" ] || [ "$interface" = "eno1" ]; then
                ACTIVE_INTERFACE=$interface
                echo "Found interface: $interface"
                break
            fi
        done
        HTTP_SERVER_IP=$(ip a l $ACTIVE_INTERFACE | awk '/inet / {print $2}' | cut -d/ -f1)
    elif [ "$(uname -s)" = "Darwin" ]; then
        ACTIVE_INTERFACE="en0"
        HTTP_SERVER_IP=$(ifconfig $ACTIVE_INTERFACE | awk '/inet / {print $2}' | cut -d/ -f1)
    fi

    if [ -z $ACTIVE_INTERFACE ]; then
        echo "ACTIVE_INTERFACE cannot be an empty string. Please check your network configuration
        and set an appropriate value for ACTIVE_INTERFACE"
        exit 1
    fi

    PACKER_HTTP_SERVER_IP=${PACKER_HTTP_SERVER_IP:-$HTTP_SERVER_IP}
    if [ -z $PACKER_HTTP_SERVER_IP ]; then
        echo "PACKER_HTTP_SERVER_IP cannot be automatically determined.  Please export PACKER_HTTP_SERVER_IP=<Current Host's IP>"
        exit 1
    fi

    SED=sed
    if [ "$(uname -s)" = "Darwin" ]; then
      SED=gsed
    fi
    find ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ova -type f -name '*.json' | xargs $SED -i "s/{{ .HTTPIP }}/$PACKER_HTTP_SERVER_IP/g"
fi

# If the image format is AMI and our Packer config specifies a non-gp3 volume, then
# remove the throughput field in the upstream Packer config since only gp3 supports
# specifying throughput
if [ "$IMAGE_FORMAT" = "ami" ]; then
    volume_type="$(cat $MAKE_ROOT/packer/ami/ami.json | jq -r '.volume_type')"
    if [[ $volume_type != "null" && $volume_type != "gp3" ]]; then
        build::jq::update_in_place ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ami/packer.json "del(.builders[0].launch_block_device_mappings[].throughput)"
    else
        build::jq::update_in_place ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ami/packer.json '.builders[0].launch_block_device_mappings[].throughput = "{{ user `throughput` }}"'
    fi
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

RELEASE_CHANNEL="${1?Specify first argument - EKS-D release channel}"
FORMAT="${2?Specify second argument - Image format}"
ARTIFACTS_PATH="${3?Specify third argument - Artifacts path}"
ARTIFACTS_UPLOAD_PATH="${4?Specify fourth argument - Artifacts upload path}"
IMAGE_OS_VERSION="${5?Specify fifth argument - OS version}"

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

release_availability=$(build::bottlerocket::check_release_availablilty $MAKE_ROOT/BOTTLEROCKET_RELEASES $RELEASE_CHANNEL $FORMAT)
if [ $release_availability -ne 0 ]; then
  echo "No Bottlerocket release found for release branch. Terminating silently..."
  exit 0
fi

build::common::echo_and_run make -C $MAKE_ROOT s3-artifacts-${FORMAT}-bottlerocket-${IMAGE_OS_VERSION} IMAGE_OS=bottlerocket
build::common::echo_and_run make -C $MAKE_ROOT upload-artifacts ARTIFACTS_PATH=$ARTIFACTS_PATH ARTIFACTS_UPLOAD_PATH=$ARTIFACTS_UPLOAD_PATH IMAGE_FORMAT=$FORMAT IMAGE_OS=bottlerocket IMAGE_OS_VERSION=$IMAGE_OS_VERSION


#!/bin/bash
source /etc/eks/logging.sh

set -uxo pipefail

SCRIPT_LOG=/var/log/eks-bootstrap.log
touch $SCRIPT_LOG

# save stdout and stderr to file descriptors 3 and 4,
# then redirect them to "$SCRIPT_LOG"
# restore stdout and stderr at bottom of script
exec 3>&1 4>&2 >>$SCRIPT_LOG 2>&1

echo "127.0.0.1   $(hostname)" >>/etc/hosts

NETWORK_CONFIG_PATH=/tmp/network.yaml
NETPLAN_CONFIG_PATH=/etc/netplan/config.yaml

# dynamically get default network interface name using mac address
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
DEFAULT_MAC=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/mac)
DEFAULT_NETWORK=$(ip -br link | grep $DEFAULT_MAC | awk '{print $1}')

# configure DNI
DNI_COUNT=$(grep -E "dniCount" $NETWORK_CONFIG_PATH | awk '{print $2}')
DNI_LIST=$(ip -br link | grep -Ev "$DEFAULT_NETWORK|lo" | awk '{print $1}')
while [ -z "$DNI_LIST" ] || [[ $(echo "$DNI_LIST" | wc -l) != "$DNI_COUNT" ]]
do
  # creating DNI is a separate api call, which has some delays
  log::info "DNI is not ready, retrying"
  sleep 5
  DNI_LIST=$(ip -br link | grep -Ev "$DEFAULT_NETWORK|lo" | awk '{print $1}')
done
log::info "Using DNI: $DNI_LIST"

DEFAULT_GATEWAY=$(ip r | grep default | awk '{print $3}')
log::info "Using default gateway: $DEFAULT_GATEWAY"

# route imds traffic to private nic
cat<<EOF >"$NETPLAN_CONFIG_PATH"
network:
    version: 2
    renderer: networkd
    ethernets:
        $DEFAULT_NETWORK:
            routes:
                - to: 169.254.169.254
                  via: $DEFAULT_GATEWAY
EOF

METRIC=0
INDEX=1
for DNI in $DNI_LIST
do
MAC=$(ip -br link | grep -E "$DNI" |  awk '{print $3}')
if ! grep -q "static" "$NETWORK_CONFIG_PATH"
then
echo "Configuring DHCP"
cat<<EOF >>"$NETPLAN_CONFIG_PATH"
        $DNI:
            set-name: $DNI
            dhcp4: true
            dhcp-identifier: mac
            dhcp4-overrides:
                route-metric: $METRIC
                send-hostname: true
                hostname: $(hostname)
            match:
                macaddress: $MAC
EOF
else
echo "Configuring static ips: $(cat $NETWORK_CONFIG_PATH)"
STATIC_IP=$(awk -v j="$INDEX" '/address/{i++}i==j{print;exit}' $NETWORK_CONFIG_PATH | awk '{print $3}')
GATEWAY=$(awk -v j="$INDEX" '/gateway/{i++}i==j{print;exit}' $NETWORK_CONFIG_PATH | awk '{print $2}')
if grep -A 2 "$STATIC_IP" "$NETWORK_CONFIG_PATH" | grep -q "primary"
then
METRIC=0
else
METRIC=50
fi
cat<<EOF >>"$NETPLAN_CONFIG_PATH"
        $DNI:
            set-name: $DNI
            addresses:
                - $STATIC_IP
            routes:
                - to: default
                  via: $GATEWAY
                  metric: $METRIC
            match:
                macaddress: $MAC
EOF
fi
METRIC=50
((INDEX=INDEX+1))
done

netplan --debug apply

sleep 5
DNI_IP_LIST=$(ip route show | grep -Ev "$DEFAULT_NETWORK|default|lo"  | awk '{print $9}' | sort | uniq)
while [ -z "$DNI_IP_LIST" ] || [[ $(echo "$DNI_IP_LIST" | wc -l) != "$DNI_COUNT" ]]
do
    # if ip is not ready in 5 s, need to retry netplan apply
    log::info "IP is not ready, retrying"
    netplan --debug apply
    sleep 5
    DNI_IP_LIST=$(ip route show | grep -Ev "$DEFAULT_NETWORK|default|lo" | awk '{print $9}' | sort | uniq)
done
log::info "IP leased: $DNI_IP_LIST"

log::info "network configuration finished"

# mount container data volume if exists
DEVICE=$(lsblk | grep -E vd | awk '{print $1}')
if [ -n "$DEVICE" ]; then
    log::info "found new device /dev/$DEVICE"

    # stop containerd and kubelet
    systemctl stop containerd
    systemctl stop kubelet

    MOUNT_POINT=/var/lib/containerd
    BACKUP_DIR=/var/lib/containerd_backup

    # backup containerd data
    mv "$MOUNT_POINT" "$BACKUP_DIR"

    # recreate dir
    mkdir "$MOUNT_POINT"

    # format disk
    mkfs -t ext4 /dev/"$DEVICE"

    # mount new device
    echo "/dev/$DEVICE $MOUNT_POINT     ext4    defaults        0 0" >>/etc/fstab
    mount -a

    # move containerd data back
    mv "$BACKUP_DIR"/* "$MOUNT_POINT"/
    rm -rf "$BACKUP_DIR"

    # restart containerd and kubelet
    systemctl restart containerd
    systemctl restart kubelet

    log::info "successfully mounted new device /dev/$DEVICE"
else
    log::info "no new device found, skipping volume mount process"
fi

# restore stdout and stderr
exec 1>&3 2>&4


#!/bin/bash

set -uxo pipefail

log::error() {
  local message="${1}"
  timestamp=$(date --iso-8601=seconds)
  echo "!!! [${timestamp}] ${1}" >&2
}

# Print a status line. Formatted to show up in a stream of output.
log::info() {
  timestamp=$(date --iso-8601=seconds)
  echo "+++ [${timestamp}] ${1}"
}


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

INLINE_VARS_FILE="${1?Specify first argument - inline vars file for goss}"

TEST_VM_NAME=vendor-validation-testing
SSH_KEY=$(cat ${HOME}/.ssh/id_rsa.pub)
USERNAME=tester

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

GOSS_DIR=$MAKE_ROOT/image-builder/images/capi/packer/goss
REMOTE_GOSS_DIR=/home/$USERNAME

# Clone the template to a vm
govc vm.clone -on=false -vm $TEMPLATE -net=sddc-cgw-network-1 $TEST_VM_NAME

# Set the meta data to the clonned vm
govc vm.change -vm $TEST_VM_NAME \
	-e guestinfo.metadata="$(MACADDRESS=$(govc device.info -vm $TEST_VM_NAME -json ethernet-0 | jq ".Devices[0].MacAddress") TEST_VM_NAME=$TEST_VM_NAME envsubst < $MAKE_ROOT/validate/metadata.yaml | base64)" \
	-e guestinfo.metadata.encoding="base64"

# Set the user data to the clonned vm to add users
govc vm.change -vm $TEST_VM_NAME \
	-e guestinfo.userdata="$(SSH_KEY=$SSH_KEY USERNAME=$USERNAME envsubst < $MAKE_ROOT/validate/cloudconfig.yaml | base64)" \
	-e guestinfo.userdata.encoding="base64"

govc vm.power -on $TEST_VM_NAME

# Wait for the vm to get an ip
echo "Waiting for vm"
govc vm.info -waitip $TEST_VM_NAME

REMOTE_IP=$(govc vm.ip $TEST_VM_NAME)
echo "Remote vm ip address is" $REMOTE_IP

# Run all the pre-reqs commands
declare -a cmds=("sudo apt install git -y"
				 "sudo curl -L https://github.com/aelsabbahy/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss"
				 "sudo chmod +rx /usr/local/bin/goss"
)

for cmd in "${cmds[@]}"
do
	ssh -o StrictHostKeyChecking=no $USERNAME@$REMOTE_IP "$cmd"
done

# Copy over all the goss scripts
scp -o StrictHostKeyChecking=no -r $GOSS_DIR/* $USERNAME@$REMOTE_IP:$REMOTE_GOSS_DIR

# Run the goss scripts
INLINE_VARS=$(cat $INLINE_VARS_FILE)
ssh -o StrictHostKeyChecking=no $USERNAME@$REMOTE_IP "sudo goss -g goss.yaml --vars goss-vars.yaml --vars-inline '$INLINE_VARS' validate --retry-timeout 0s --sleep 1s -f json -o pretty"

if [ $? -ne 0 ]; then
	echo "Goss validation failed"
	echo "The vm is left on, please access with $USERNAME@$REMOTE_IP"
	exit 1
else
	echo "Goss validation passed"
fi

# Deleting and removing the vm
govc vm.destroy $TEST_VM_NAME
exit 0


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

EKSD_RELEASE_BRANCH="$1"
ARTIFACTS_BUCKET="$2"
OUTPUT_FILE="$3"
LATEST_TAG="$4"

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

# Preload release yaml
build::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH false

KUBE_VERSION=$(build::eksd_releases::get_eksd_component_version "kubernetes" $EKSD_RELEASE_BRANCH)
EKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)
EKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)
EKSD_VERSION_SUFFIX="eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE"
EKSD_KUBE_VERSION="$KUBE_VERSION-$EKSD_VERSION_SUFFIX"
COREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version "coredns" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX
ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version "etcd" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX

CNI_PLUGINS_AMD64_URL=$(build::eksd_releases::get_eksd_component_url "cni-plugins" $EKSD_RELEASE_BRANCH amd64)
CNI_PLUGINS_ARM64_URL=$(build::eksd_releases::get_eksd_component_url "cni-plugins" $EKSD_RELEASE_BRANCH arm64)
CNI_PLUGINS_AMD64_SHA256SUM=$(build::eksd_releases::get_eksd_component_sha "cni-plugins" $EKSD_RELEASE_BRANCH amd64)
CNI_PLUGINS_ARM64_SHA256SUM=$(build::eksd_releases::get_eksd_component_sha "cni-plugins" $EKSD_RELEASE_BRANCH arm64)

CRICTL_AMD64_URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET 'kubernetes-sigs/cri-tools' amd64 $LATEST_TAG)
CRICTL_ARM64_URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET 'kubernetes-sigs/cri-tools' arm64 $LATEST_TAG)
CRICTL_AMD64_SHA256SUM_URL=$CRICTL_AMD64_URL.sha256
CRICTL_ARM64_SHA256SUM_URL=$CRICTL_ARM64_URL.sha256

mkdir -p $(dirname $OUTPUT_FILE)
cat <<EOF >> $OUTPUT_FILE
EKSD_KUBE_VERSION=$EKSD_KUBE_VERSION
EKSD_IMAGE_REPO=$EKSD_IMAGE_REPO
COREDNS_VERSION=$COREDNS_VERSION
ETCD_VERSION=$ETCD_VERSION
CNI_PLUGINS_AMD64_URL=$CNI_PLUGINS_AMD64_URL
CNI_PLUGINS_ARM64_URL=$CNI_PLUGINS_ARM64_URL
CNI_PLUGINS_AMD64_SHA256SUM=$CNI_PLUGINS_AMD64_SHA256SUM
CNI_PLUGINS_ARM64_SHA256SUM=$CNI_PLUGINS_ARM64_SHA256SUM
CRICTL_AMD64_SHA256SUM_URL=$CRICTL_AMD64_SHA256SUM_URL
CRICTL_ARM64_SHA256SUM_URL=$CRICTL_ARM64_SHA256SUM_URL
CRICTL_AMD64_URL=$CRICTL_AMD64_URL
CRICTL_ARM64_URL=$CRICTL_ARM64_URL
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 -x
set -o errexit
set -o pipefail

EKSD_RELEASE_BRANCH="${1?Specify first argument - release branch}"
INTERMEDIATE_BASE_IMAGE="${2?Specify second argument - kind base tag}"
ARCH="${3?Specify third argument - Targetarch}"

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

# Include common constants and other vars needed when building image
source "${MAKE_ROOT}/_output/$EKSD_RELEASE_BRANCH/kind-node-image-build-args"

INTERMEDIATE_NODE_IMAGE="kind/build/node-image:$KUBE_VERSION-$EKSD_RELEASE_BRANCH"

# Uses kind cli to build node-image, usually the fake kubernetes src
# to download the eks-d release artifacts instead of building from src
# ouput image: $INTERMEDIATE_NODE_IMAGE
function build::kind::build_node_image(){
    export KUBE_VERSION=$KUBE_VERSION
    export EKSD_RELEASE_BRANCH=$EKSD_RELEASE_BRANCH
    export EKSD_RELEASE=$EKSD_RELEASE
    export EKSD_IMAGE_REPO=$EKSD_IMAGE_REPO
    export EKSD_ASSET_URL=$EKSD_ASSET_URL
    export KUBE_ARCH=$ARCH

    KIND_PATH="$MAKE_ROOT/_output/bin/kind/$(uname | tr '[:upper:]' '[:lower:]')-$(go env GOHOSTARCH)/kind"
    $KIND_PATH build node-image $MAKE_ROOT/images/k8s.io/kubernetes \
        --base-image $INTERMEDIATE_BASE_IMAGE --image $INTERMEDIATE_NODE_IMAGE --arch $ARCH
}

function build::kind::validate_versions(){
    local -r container_id=$1
    local -r eksd_tag="$KUBE_VERSION-eks-" # there is a commit hash at the end
    # We expect certain versions to be in the kind base/node images since we end up replacing them
    # validate they haven't changed
    if ! docker exec -i $container_id grep "image: $KINDNETD_IMAGE_TAG"  /kind/manifests/default-cni.yaml > /dev/null 2>&1; then
        echo "Did not find expected version of kindnetd: $KINDNETD_IMAGE_TAG"
        exit 1
    fi
    if ! docker exec -i $container_id grep "$LOCAL_PATH_HELPER_IMAGE_TAG"  /kind/manifests/default-storage.yaml > /dev/null 2>&1; then
        echo "Did not find expected version of debian base: $LOCAL_PATH_HELPER_IMAGE_TAG"
        exit 1
    fi
    if ! docker exec -i $container_id grep "image: $LOCAL_PATH_PROVISONER_IMAGE_TAG"  /kind/manifests/default-storage.yaml > /dev/null 2>&1; then
        echo "Did not find expected version of local path provisoner: $LOCAL_PATH_PROVISONER_IMAGE_TAG"
        exit 1
    fi
    if ! docker exec -i $container_id grep "$PAUSE_IMAGE_TAG"  /etc/containerd/config.toml > /dev/null 2>&1; then
        echo "Did not find expected version of pause image: $PAUSE_IMAGE_TAG"
        exit 1
    fi
    if ! docker exec -i $container_id /usr/bin/kubeadm version -oshort | grep "$eksd_tag" > /dev/null 2>&1; then
        echo "Did not find expected version of kubeadm: $eksd_tag"
        exit 1
    fi
    if ! docker exec -i $container_id kubectl version --short --client=true | grep "$eksd_tag" > /dev/null 2>&1; then
        echo "Did not find expected version of kubectl: $eksd_tag"
        exit 1
    fi
    if ! docker exec -i $container_id kubelet --version | grep "$eksd_tag" > /dev/null 2>&1; then
        echo "Did not find expected version of kubelet: $eksd_tag"
        exit 1
    fi
}

# This whole process of creating a container from the image, loading images
# and commit it back is a recreation of what the kind build node-image does
# the reason being is this is the easiest way to convert a docker/oci image
# into an on disk containerd format
# output image: $INTERMEDIATE_NODE_IMAGE
function build::kind::load_images(){
    CONTAINER_ID=$(docker run --platform linux/$ARCH --entrypoint sleep -d -i $INTERMEDIATE_NODE_IMAGE infinity)

    build::kind::validate_versions $CONTAINER_ID

    docker exec --privileged -i $CONTAINER_ID bash -c "nohup containerd > /dev/null 2>&1 & sleep 5"
    docker exec --privileged -i $CONTAINER_ID crictl images

    # pull local-path-provisioner + al2 helper image
    IMAGES_FOLDER=$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/images
    mkdir -p $IMAGES_FOLDER
    IMAGES=("$AL2_HELPER_IMAGE" "$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE" "$PAUSE_IMAGE_TAG_OVERRIDE" "$KIND_KINDNETD_IMAGE_OVERRIDE" "$ETCD_IMAGE_TAG" "$COREDNS_IMAGE_TAG")

    declare -A release_image_overrides
    release_image_overrides["$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE"]=$LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE
    release_image_overrides["$KIND_KINDNETD_IMAGE_OVERRIDE"]=$KIND_KINDNETD_RELEASE_OVERRIDE

    for image in "${IMAGES[@]}"; do
        # docker pull when passing a platform will pull the image for the given platform
        # and that new image id will "take over" the tag which we can use to trigger the save
        build::docker::retry_pull --platform linux/$ARCH $image
        image_id=$(docker images $image --format "{{.ID}}")

        if [ ! -f $IMAGES_FOLDER/$image_id.tar ]; then
            if [[ $image =~ local-path-provisioner ]] || [[ $image =~ kindnetd ]]; then
                docker tag $image_id ${release_image_overrides[$image]}
                docker save ${release_image_overrides[$image]} -o $IMAGES_FOLDER/$image_id.tar
            else
                docker save $image -o $IMAGES_FOLDER/$image_id.tar
            fi
        fi
        docker exec --privileged -i $CONTAINER_ID \
            ctr --namespace=k8s.io images import --all-platforms --no-unpack - < $IMAGES_FOLDER/$image_id.tar
    done

    docker exec --privileged -i $CONTAINER_ID crictl images

    # Validate all images in the image are from public.ecr
    EXPECTED_FINAL_IMAGES=("amazonlinux/amazonlinux" "kind/kindnetd" "rancher/local-path-provisioner" \
        "kubernetes/kube-apiserver" "kubernetes/kube-controller-manager" "kubernetes/kube-proxy" \
        "kubernetes/kube-scheduler" "kubernetes/pause" "coredns/coredns" "etcd-io/etcd")
    declare -a FOUND_EXPECTED_IMAGES
    FINAL_IMAGES=$(docker exec -i $CONTAINER_ID crictl images -o json | jq ".images[].repoTags[]" -r)
    mapfile -t FINAL_IMAGES <<< "$FINAL_IMAGES"
    declare -p FINAL_IMAGES
    for image in "${FINAL_IMAGES[@]}"; do
        if [[ ! $image =~ ^public\.ecr\.aws\/ ]]; then
            echo "$image is not from public.ecr.aws!"
            exit 1
        fi
        EXPECTED_IMAGE=false
        for expected in "${EXPECTED_FINAL_IMAGES[@]}"; do
            if [[ $image =~ $expected ]]; then
                FOUND_EXPECTED_IMAGES+=( "$expected}" )
                EXPECTED_IMAGE=true
                break
            fi
        done
        if ! $EXPECTED_IMAGE; then
            echo "$image is not expected to be included in final image!"
            exit 1
        fi
        if [[ $ARCH != $(docker exec --privileged -i $CONTAINER_ID \
                crictl inspecti -o go-template --template={{.info.imageSpec.architecture}} $image) ]]; then
            echo "saved image: $image is not the correct arch: $ARCH!"
            exit 1
        fi
    done

    if [[ "${#FOUND_EXPECTED_IMAGES[@]}" != "${#EXPECTED_FINAL_IMAGES[@]}" ]]; then
        echo "${EXPECTED_FINAL_IMAGES[*]} are expected to be included in the final image but only ${FOUND_EXPECTED_IMAGES[*]} exist!"
        exit 1
    fi

    if [[ $(docker exec --privileged -i $CONTAINER_ID ctr -n k8s.io snapshots ls | wc -l) -gt 1 ]]; then
        echo "Snapshots exists, all images should have been loaded but not unpacked!"
        exit 1
    fi

    docker exec --privileged -i $CONTAINER_ID pkill containerd

    docker commit --change 'ENTRYPOINT [ "/usr/local/bin/entrypoint", "/sbin/init" ]' $CONTAINER_ID | sed -E 's/.*sha256:(.*)$/\1/'

    docker kill $CONTAINER_ID

    # Copy files created by the node build process and ctr import out to be used in next build
    FILES_DIR=$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/linux-$ARCH/files
    ROOT_FS=$FILES_DIR/rootfs
    mkdir -p $ROOT_FS/var/lib/containerd $ROOT_FS/etc/containerd
    docker cp $CONTAINER_ID:/etc/containerd/config.toml $ROOT_FS/etc/containerd
    docker cp $CONTAINER_ID:/kind $ROOT_FS
    docker cp $CONTAINER_ID:/var/lib/containerd/io.containerd.content.v1.content $ROOT_FS/var/lib/containerd

    mkdir -p $ROOT_FS/usr/bin
    for binary in kubeadm kubelet kubectl; do
        docker cp $CONTAINER_ID:/usr/bin/$binary $ROOT_FS/usr/bin
    done

    # meta.db is the databse for containerd and its not reproducible since dates are included
    # moving out of file directly to support reusing buildkit cache as much as possible
    docker cp $CONTAINER_ID:/var/lib/containerd/io.containerd.metadata.v1.bolt $FILES_DIR

    # update kind default manifests to use overridden images
	sed -i "s,image: $LOCAL_PATH_PROVISONER_IMAGE_TAG,image: $LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE," $ROOT_FS/kind/manifests/default-storage.yaml
	sed -i "s,$LOCAL_PATH_HELPER_IMAGE_TAG,$AL2_HELPER_IMAGE," $ROOT_FS/kind/manifests/default-storage.yaml
	sed -i "s,image: $KINDNETD_IMAGE_TAG,image: $KIND_KINDNETD_RELEASE_OVERRIDE," $ROOT_FS/kind/manifests/default-cni.yaml
	# Update containerd config to have eks-d pause image tag
	sed -i "s,$PAUSE_IMAGE_TAG,$PAUSE_IMAGE_TAG_OVERRIDE," $ROOT_FS/etc/containerd/config.toml
}

if command -v docker &> /dev/null && docker info > /dev/null 2>&1 ; then
    build::kind::build_node_image
    build::kind::load_images
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 -x
set -o errexit
set -o nounset
set -o pipefail

IMAGE="$1"
ARCH="$2"
EKSD_RELEASE_BRANCH="$3"

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

# Preload release yaml
build::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH false

KUBE_VERSION=$(build::eksd_releases::get_eksd_component_version "kubernetes" $EKSD_RELEASE_BRANCH)
EKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)
EKSD_VERSION_SUFFIX="eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE"
EKSD_KUBE_VERSION="$KUBE_VERSION-$EKSD_VERSION_SUFFIX"
COREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version "coredns" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX
ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version "etcd" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX
EKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)

# Make sure the correct arch image is pulled and tagged
build::docker::retry_pull --platform linux/$ARCH $IMAGE

KIND_PATH="$MAKE_ROOT/_output/bin/kind/$(uname | tr '[:upper:]' '[:lower:]')-$(go env GOHOSTARCH)/kind"
cat << EOF \
  | $KIND_PATH create cluster \
    --name "eks-a-kind-test-$ARCH" \
    --image="$IMAGE" \
    --wait="5m" -v9 --retain \
    --config=/dev/stdin \
    || true
apiVersion: kind.x-k8s.io/v1alpha4
kind: Cluster
kubeadmConfigPatches:
- |
    kind: ClusterConfiguration
    dns:
        type: CoreDNS
        imageRepository: $EKSD_IMAGE_REPO/coredns
        imageTag: $COREDNS_VERSION
    etcd:
        local:
            imageRepository: $EKSD_IMAGE_REPO/etcd-io
            imageTag: $ETCD_VERSION
    imageRepository: $EKSD_IMAGE_REPO/kubernetes
    kubernetesVersion: $EKSD_KUBE_VERSION
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 -x
set -o errexit
set -o pipefail

EKSD_RELEASE_BRANCH="$1"
KINDNETD_IMAGE_COMPONENT="$2"
IMAGE_REPO="$3"
ARTIFACTS_BUCKET="$4"
IMAGE_TAG="$5"
LATEST="$6"
OUTPUT_FILE="$7"

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

# This is used by the local-path-provisioner within the kind node
AL2_HELPER_IMAGE="public.ecr.aws/amazonlinux/amazonlinux:2"
LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE="$IMAGE_REPO/rancher/local-path-provisioner:$LATEST"
LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE="public.ecr.aws/eks-anywhere/rancher/local-path-provisioner:$(cat $MAKE_ROOT/../../rancher/local-path-provisioner/GIT_TAG)"
KIND_KINDNETD_RELEASE_OVERRIDE="public.ecr.aws/eks-anywhere/kubernetes-sigs/kind/kindnetd:$(cat $MAKE_ROOT/GIT_TAG)"
KIND_KINDNETD_IMAGE_OVERRIDE="$IMAGE_REPO/$KINDNETD_IMAGE_COMPONENT:$LATEST"

# Preload release yaml
build::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH

KUBE_VERSION=$(build::eksd_releases::get_eksd_component_version "kubernetes" $EKSD_RELEASE_BRANCH)
EKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)
EKSD_KUBE_VERSION="$KUBE_VERSION-eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE"
PAUSE_IMAGE_TAG_OVERRIDE=$(build::eksd_releases::get_eksd_kubernetes_image_url "pause-image" $EKSD_RELEASE_BRANCH)
EKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)
EKSD_ASSET_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $EKSD_RELEASE_BRANCH)/$KUBE_VERSION

EKSD_VERSION_SUFFIX="eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE"
COREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version "coredns" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX
ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version "etcd" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX

# Expected versions provided by kind which are replaced in the docker build with our versions
# when updating kind check the following, they may need to be updated
# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_cni.go#L23
KINDNETD_IMAGE_TAG="docker.io/kindest/kindnetd:v20230330-48f316cd@sha256:c19d6362a6a928139820761475a38c24c0cf84d507b9ddf414a078cf627497af"
# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_storage.go#L28
LOCAL_PATH_PROVISONER_IMAGE_TAG="docker.io/kindest/local-path-provisioner:v0.0.23-kind.0@sha256:f2d0a02831ff3a03cf51343226670d5060623b43a4cfc4808bd0875b2c4b9501"
# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_storage.go#L29
LOCAL_PATH_HELPER_IMAGE_TAG="docker.io/kindest/local-path-helper:v20230330-48f316cd@sha256:135203f2441f916fb13dad1561d27f60a6f11f50ec288b01a7d2ee9947c36270"
# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/images/base/files/etc/containerd/config.toml#L37
PAUSE_IMAGE_TAG="registry.k8s.io/pause:3.7"

mkdir -p $(dirname $OUTPUT_FILE)
cat <<EOF >> $OUTPUT_FILE
AL2_HELPER_IMAGE=$AL2_HELPER_IMAGE
LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE=$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE
LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE=$LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE
KIND_KINDNETD_RELEASE_OVERRIDE=$KIND_KINDNETD_RELEASE_OVERRIDE
KIND_KINDNETD_IMAGE_OVERRIDE=$KIND_KINDNETD_IMAGE_OVERRIDE
KUBE_VERSION=$KUBE_VERSION
EKSD_RELEASE=$EKSD_RELEASE
EKSD_KUBE_VERSION=$EKSD_KUBE_VERSION
PAUSE_IMAGE_TAG_OVERRIDE=$PAUSE_IMAGE_TAG_OVERRIDE
EKSD_IMAGE_REPO=$EKSD_IMAGE_REPO
EKSD_ASSET_URL=$EKSD_ASSET_URL
KINDNETD_IMAGE_TAG=$KINDNETD_IMAGE_TAG
LOCAL_PATH_HELPER_IMAGE_TAG=$LOCAL_PATH_HELPER_IMAGE_TAG
LOCAL_PATH_PROVISONER_IMAGE_TAG=$LOCAL_PATH_PROVISONER_IMAGE_TAG
PAUSE_IMAGE_TAG=$PAUSE_IMAGE_TAG
NODE_IMAGE_TAG=$EKSD_KUBE_VERSION-$IMAGE_TAG
NODE_IMAGE_LATEST_TAG=$EKSD_KUBE_VERSION-$LATEST
ETCD_IMAGE_TAG=$EKSD_IMAGE_REPO/etcd-io/etcd:$ETCD_VERSION
COREDNS_IMAGE_TAG=$EKSD_IMAGE_REPO/coredns/coredns:$COREDNS_VERSION
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 -x
set -o errexit
set -o pipefail

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

EKSD_RELEASE_BRANCH="${1?Specify first argument - release branch}"
ARCH="${2?Specify second argument - Targetarch}"

DEP_FOLDER="$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/linux-$ARCH"
OUTPUT_FOLDER="$DEP_FOLDER/files/rootfs"
mkdir -p $OUTPUT_FOLDER/LICENSES

for FOLDER in eksd/kubernetes eksa/kubernetes-sigs/etcdadm eksd/cni-plugins eksa/kubernetes-sigs/cri-tools; do
    cp -rf $DEP_FOLDER/$FOLDER/LICENSES "$OUTPUT_FOLDER/LICENSES/$(echo $(basename $FOLDER) | tr a-z A-Z  | tr -d '-'  )_LICENSES"
    cp $DEP_FOLDER/$FOLDER/ATTRIBUTION.txt "$OUTPUT_FOLDER/LICENSES/$(echo $(basename $FOLDER) | tr a-z A-Z  | tr -d '-'  )_ATTRIBUTION.txt"
done

mkdir -p $OUTPUT_FOLDER/usr/bin/
cp $DEP_FOLDER/eksa/kubernetes-sigs/etcdadm/etcdadm $OUTPUT_FOLDER/usr/bin/

# Place etcd tarball etcdadm cache directory to avoid downloading at runtime
ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version "etcd" $EKSD_RELEASE_BRANCH $ARCH)
FOLDER="$OUTPUT_FOLDER/var/cache/etcdadm/etcd/$ETCD_VERSION"
mkdir -p $FOLDER
cp $DEP_FOLDER/eksd/etcd/etcd.tar.gz $FOLDER/etcd-$ETCD_VERSION-linux-$ARCH.tar.gz


#!/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/kubeadm --config /etc/kubeadm.config "$@"


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

# the upstream version of this script builds the image
# download them from eks-distro public.ecr
# and pulls the binaries from the eks-d release bucket

# since kind is calling this directly, cannot require args
# instead the following env vars are required
if [[ -z "${KUBE_VERSION}" ]]; then
    echo "KUBE_VERSION env var not set"
    exit 1
fi

if [[ -z "${EKSD_RELEASE_BRANCH}" ]]; then
    echo "EKSD_RELEASE_BRANCH env var not set"
    exit 1
fi

if [[ -z "${EKSD_RELEASE}" ]]; then
    echo "EKSD_RELEASE env var not set"
    exit 1
fi

if [[ -z "${EKSD_IMAGE_REPO}" ]]; then
    echo "EKSD_IMAGE_REPO env var not set"
    exit 1
fi
if [[ -z "${EKSD_ASSET_URL}" ]]; then
    echo "EKSD_ASSET_URL env var not set"
    exit 1
fi

if [[ -z "${KUBE_ARCH}" ]]; then
    echo "KUBE_ARCH env var not set"
    exit 1
fi

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

# symlink to project root _output to make sure files are properly cleaned up
# when running make clean
PROJECT_ROOT="$(cd "$SOURCE_ROOT/../../.." && pwd -P)"

source "${PROJECT_ROOT}/../../../build/lib/common.sh"

rm -f $SOURCE_ROOT/_output
ln -s $PROJECT_ROOT/_output/$EKSD_RELEASE_BRANCH $SOURCE_ROOT/_output

# Download binaries
mkdir -p $SOURCE_ROOT/_output/dockerized/bin/linux/$KUBE_ARCH

for binary in "kubeadm" "kubelet" "kubectl"; do
    FILE="$SOURCE_ROOT/_output/dockerized/bin/linux/$KUBE_ARCH/$binary "
    if [ ! -f $FILE ]; then
        curl $EKSD_ASSET_URL/bin/linux/$KUBE_ARCH/$binary -o $FILE
    fi
done

# Download container images
EKSD_TAG="$KUBE_VERSION-eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE"

mkdir -p $SOURCE_ROOT/_output/release-images/$KUBE_ARCH/

for container in "kube-apiserver" "kube-controller-manager" "kube-scheduler" "kube-proxy"; do
    IMAGE_TAG="$EKSD_IMAGE_REPO/kubernetes/$container:$EKSD_TAG"
    FILE="$SOURCE_ROOT/_output/release-images/$KUBE_ARCH/$container.tar"
    if [ ! -f $FILE ]; then
        build::docker::retry_pull --platform linux/$KUBE_ARCH $IMAGE_TAG
        docker save $IMAGE_TAG -o $FILE
    fi
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

# kind calls this scripts to build the binaries
# for versions < 1.21. for other versions it relies
# on the download-images script to also build the binaries
# this script will be a noop only to support < 1.21 builds


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

# the upstream verison of this scripts a number of
# version related information, but all kind is checking for
# is gitVersion

# since kind is calling this directly, cannot require args
# instead the following env vars are required
# KUBE_VERSION

if [[ -z "${KUBE_VERSION}" ]]; then
    echo "KUBE_VERSION env var not set"
    exit 1
fi

echo "gitVersion $KUBE_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 -x
set -o errexit
set -o pipefail

REPO="$1"
OUTPUT_DIR="$2"
ARTIFACTS_PATH="$3"
TAG="$4"
IMAGE_REPO="$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

sed -i'' -e 's@newName: .*@newName: '"${IMAGE_REPO}/nutanix-cloud-native/cluster-api-provider-nutanix"'@' config/manager/kustomization.yaml
sed -i'' -e 's@newTag: .*@newTag: '"${IMAGE_TAG}"'@' config/manager/kustomization.yaml
sed -i'' -e 's@image: .*@image: '"${IMAGE_REPO}/brancz/kube-rbac-proxy:latest"'@' config/default/manager_auth_proxy_patch.yaml

make release-manifests \
  RELEASE_DIR="out" \
  IMG="${IMAGE_REPO}:${IMAGE_TAG}"

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

cp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH