#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/docker_buildx

source $SCRIPT_ROOT/common_vars.sh

DOCKER_BUILDX_URL="https://github.com/docker/buildx/releases/download/$DOCKER_BUILDX_VERSION/buildx-$DOCKER_BUILDX_VERSION.linux-$TARGETARCH"
DOCKER_BUILDX_CHECKSUM_URL="https://github.com/docker/buildx/releases/download/$DOCKER_BUILDX_VERSION/checksums.txt"

function install_docker_buildx() {
    wget \
        --progress dot:giga \
        $DOCKER_BUILDX_URL
    sha256sum -c $BASE_DIR/docker-buildx-$TARGETARCH-checksum
    mkdir -p ${NEWROOT}/usr/local/lib/docker/cli-plugins
    mv buildx-$DOCKER_BUILDX_VERSION.linux-$TARGETARCH ${NEWROOT}/usr/local/lib/docker/cli-plugins/docker-buildx
    chmod a+x ${NEWROOT}/usr/local/lib/docker/cli-plugins/docker-buildx
}

[ ${SKIP_INSTALL:-false} != false ] || install_docker_buildx


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/ecr-cred-helper

source $SCRIPT_ROOT/common_vars.sh

AMAZON_ECR_CRED_HELPER_DOWNLOAD_URL="https://amazon-ecr-credential-helper-releases.s3.us-east-2.amazonaws.com/${AMAZON_ECR_CRED_HELPER_VERSION}/linux-$TARGETARCH/docker-credential-ecr-login"
AMAZON_ECR_CRED_HELPER_CHECKSUM_URL="${AMAZON_ECR_CRED_HELPER_DOWNLOAD_URL}.sha256"

function install_docker_cred() {
    wget \
        --progress dot:giga \
        $AMAZON_ECR_CRED_HELPER_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/amazon-ecr-cred-helper-$TARGETARCH-checksum
    mv docker-credential-ecr-login $USR_BIN/
    chmod +x $USR_BIN/docker-credential-ecr-login

    ls -al $USR_BIN
}

[ ${SKIP_INSTALL:-false} != false ] || install_docker_cred


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

# The base image is the kind-minimal image with a /etc/passwd file
# based from the minimal base, which is setup manually.  The root
# user's shell is configured as /sbin/nologin
# This doesnt work for the builder-base usage in Codebuild which runs
# certain commands specifically as root.  We need the shell to be bash.
usermod --shell /bin/bash root

# user for goss/imagebuilder
# to make sure the home dir is created correctly, tmp move the goss plugin
# on arm goss does not exist
if [ -f /home/imagebuilder/.packer.d/plugins/packer-provisioner-goss ]; then
    mv /home/imagebuilder/.packer.d/plugins/packer-provisioner-goss /tmp
fi

rm -rf /home/imagebuilder
useradd -ms /bin/bash -u 1100 imagebuilder

if [ -f /tmp/packer-provisioner-goss ]; then
    mkdir -p /home/imagebuilder/.packer.d/plugins/
    mv /tmp/packer-provisioner-goss /home/imagebuilder/.packer.d/plugins/
fi

# directory setup
mkdir -p /go/src/github.com/aws/eks-distro

yum install -y \
    bc \
    bind-utils \
    bzip2 \
    cpio \
    curl \
    docker \
    gettext \
    git-core \
    jq \
    less \
    make \
    openssh-clients \
    openssl \
    patch \
    procps-ng \
    rsync \
    tar \
    unzip \
    vim \
    wget \
    which \
    yum-utils

# We see issues in fargate when installing on top of these images
# including this plugin appears to fix it
# ref: https://unix.stackexchange.com/questions/348941/rpmdb-checksum-is-invalid-trying-to-install-gcc-in-a-centos-7-2-docker-image
if [ "$IS_AL23" = "false" ]; then
    yum install -y yum-plugin-ovl
fi

if [ "${FINAL_STAGE_BASE}" = "full-copy-stage" ]; then
    yum install -y \
        gcc \
        openssl-devel \
        pkgconfig \
        python3-pip

    # for building containerd
    yum install -y \
        glibc-static \
        libseccomp-static

    # headers for btrfs do not exist in al23. well need to address this in the future
    # if we want to build containerd with btrfs support on al23
    if [ "$IS_AL23" = "false" ]; then
        yum install -y btrfs-progs-devel
    fi
fi

#################### CLEANUP ####################
# truncate logs
find /var/log -type f | while read file; do echo -ne '' > $file; done

# Removing doc and man files
# to get all symlinks run twice
for i in {1..2}; do
    find /usr/share/{doc,man} \( -xtype l -o -type f \) \
        ! \( -iname '*lice*' -o -iname '*copy*' -o -iname '*gpl*' -o -iname '*not*' -o -iname "*credits*" \) \
        -delete
done
find /usr/share/{doc,man} -type d -empty -delete

rm -rf /root/.cache


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

$SCRIPT_ROOT/install_base_yum_packages.sh

yum install --setopt=install_weak_deps=False -y \
    gcc \
    git-core \
    make \
    pkgconfig


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/gh-cli

source $SCRIPT_ROOT/common_vars.sh

GITHUB_CLI_DOWNLOAD_URL="https://github.com/cli/cli/releases/download/v${GITHUB_CLI_VERSION}/gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz"
GITHUB_CLI_CHECKSUM_URL="https://github.com/cli/cli/releases/download/v${GITHUB_CLI_VERSION}/gh_${GITHUB_CLI_VERSION}_checksums.txt"

function install_gh_cli() {
    wget --progress dot:giga $GITHUB_CLI_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/github-cli-$TARGETARCH-checksum
    tar -xzf gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz
    mv gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH/bin/gh $USR_BIN
    rm -rf gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH
}

[ ${SKIP_INSTALL:-false} != false ] || install_gh_cli


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -x
set -e
set -o pipefail

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

VERSION="$1"

GOLANG_MAJOR_VERSION=$(if [[ $(echo "$VERSION"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${VERSION%.*}; else echo ${VERSION%-*}; fi)

NEWROOT=/golang-${GOLANG_MAJOR_VERSION}

source $SCRIPT_ROOT/common_vars.sh

mkdir -p /go/src /go/bin /go/pkg

function build::go::symlink() {
    local -r version=$1

    # Removing the last number as we only care about the major version of golang
    local -r majorversion=$(if [[ $(echo "$version"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${version%.*}; else echo ${version%-*}; fi)
    mkdir -p ${GOPATH}/go${majorversion}/bin

    for binary in go gofmt; do
        ln -s /root/sdk/go${version}/bin/${binary} ${GOPATH}/go${majorversion}/bin/${binary}
    done

    if [ "$version" != "$majorversion" ]; then
        ln -s ${GOPATH}/bin/go${version} ${GOPATH}/bin/go${majorversion}
    fi
}

function build::go::install(){
    # Set up specific go version by using go get, additional versions apart from default can be installed by calling
    # the function again with the specific parameter.
    local version=${1%-*}
    build::go::extract $version
    build::go::symlink $version
}

function build::go::extract() {
    local version=$1

    if [ $TARGETARCH == 'amd64' ]; then
        local arch='x86_64'
    else
        local arch='aarch64'
    fi

    mkdir -p /tmp/go-extracted
    for rpm in /tmp/$arch/golang-*.noarch.rpm /tmp/$arch/golang-*.$arch.rpm ; do $(cd /tmp/go-extracted && rpm2cpio $rpm | cpio -idm && rm -f $rpm); done

    local -r golang_version=$(/tmp/go-extracted/usr/lib/golang/bin/go version | grep -o "go[0-9].* " | xargs)

    mkdir -p /root/sdk/$golang_version
    mv /tmp/go-extracted/usr/lib/golang/* /root/sdk/$golang_version

    for license_dir in "/usr/share/licenses/golang" "/usr/share/doc/golang-$VERSION"; do
        if [ -d /tmp/go-extracted/$license_dir ]; then
            mv /tmp/go-extracted/$license_dir/* /root/sdk/$golang_version
        fi
    done

    version=$(echo "$golang_version" | grep -o "[0-9].*")
    ln -s /root/sdk/go${version}/bin/go ${GOPATH}/bin/$golang_version

    rm -rf /tmp/go-extracted /tmp/golang-*.rpm
}

build::go::install "${VERSION}"

# symlink default golang install to newroot bin
for binary in go gofmt; do
    ln -s ${GOPATH}/go${GOLANG_MAJOR_VERSION}/bin/${binary} ${USR_BIN}/${binary}
done

mkdir -p ${NEWROOT}/root
mv /root/sdk ${NEWROOT}/root
mv ${GOPATH} ${NEWROOT}/${GOPATH}


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/goss

source $SCRIPT_ROOT/common_vars.sh

GOSS_DOWNLOAD_URL="https://github.com/YaleUniversity/packer-provisioner-goss/releases/download/v${GOSS_VERSION}/packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz"
GOSS_CHECKSUM_URL="https://github.com/YaleUniversity/packer-provisioner-goss/releases/download/v${GOSS_VERSION}/packer-provisioner-goss_v${GOSS_VERSION}_SHA256SUMS"

function install_goss() {
    mkdir -p /goss/home/imagebuilder/.packer.d/plugins

    # Installing Goss for imagebuilder validation
    wget \
        --progress dot:giga \
        $GOSS_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/goss-$TARGETARCH-checksum
    tar -C ${NEWROOT}/home/imagebuilder/.packer.d/plugins -xzf packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz
    rm -rf packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz
}

[ ${SKIP_INSTALL:-false} != false ] || install_goss


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/govc

source $SCRIPT_ROOT/common_vars.sh

if [ $TARGETARCH == 'amd64' ]; then
    ARCH='x86_64'
else
    ARCH='arm64'
fi

GOVC_FILENAME="govc_Linux_$ARCH.tar.gz"
GOVC_DOWNLOAD_URL="https://github.com/vmware/govmomi/releases/download/v${GOVC_VERSION}/${GOVC_FILENAME}"
GOVC_CHECKSUM_URL="https://github.com/vmware/govmomi/releases/download/v${GOVC_VERSION}/checksums.txt"

function install_govc() {
    # Installing govc CLI
    wget \
        --progress dot:giga \
        $GOVC_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/govc-$TARGETARCH-checksum
    tar -xf govc_Linux_$ARCH.tar.gz
    mv govc $USR_BIN/govc
    chmod +x $USR_BIN/govc
}

[ ${SKIP_INSTALL:-false} != false ] || install_govc


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

VERSION=$(go version | grep -o "go[0-9].* ")
GOLANG_MAJOR_VERSION=$(if [[ $(echo "$VERSION"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${VERSION%.*}; else echo ${VERSION%-*}; fi)

NEWROOT=/go-licenses-${GOLANG_MAJOR_VERSION#go}

source $SCRIPT_ROOT/common_vars.sh

function install_go_licenses() {

    # installing go-licenses has to happen after we have set the main go
    # to symlink to the one in /root/sdk to ensure go-licenses gets built
    # with GOROOT pointed to /root/sdk/go... instead of /usr/local/go so it
    # is able to properly packages from the standard Go library
    # We currently  use 1.19, 1.17 or 1.16, so installing for all
    if [ "${GOLANG_MAJOR_VERSION}" = "go1.16" ]; then
        GO111MODULE=on GOBIN=${NEWROOT}/${GOPATH}/${GOLANG_MAJOR_VERSION}/bin go install github.com/jaxesn/go-licenses@4497a2a38565e4e6ad095ea8117c25ecd622d0cc
    else
        GO111MODULE=on GOBIN=${NEWROOT}/${GOPATH}/${GOLANG_MAJOR_VERSION}/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48
    fi

    # symlink to go/bin and depending on which go-licenses vs is added last to
    # the final image, will take precedent and be the default
    # similiar to the strategy with golang
    mkdir -p ${NEWROOT}/${GOPATH}/bin
    ln -s ${GOPATH}/${GOLANG_MAJOR_VERSION}/bin/go-licenses ${NEWROOT}/${GOPATH}/bin/go-licenses

    rm -rf ${GOPATH}
}

[ ${SKIP_INSTALL:-false} != false ] || install_go_licenses


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/helm

source $SCRIPT_ROOT/common_vars.sh

HELM_DOWNLOAD_URL="https://get.helm.sh/helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz"
HELM_CHECKSUM_URL="$HELM_DOWNLOAD_URL.sha256"

function install_helm() {
    # Installing Helm
    wget \
        --progress dot:giga \
        $HELM_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/helm-$TARGETARCH-checksum
    tar -xzvf helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz linux-$TARGETARCH/helm
    mv linux-$TARGETARCH/helm $USR_BIN/helm
    chmod +x $USR_BIN/helm
    rm -f helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz
}

[ ${SKIP_INSTALL:-false} != false ] || install_helm


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/hugo

source $SCRIPT_ROOT/common_vars.sh

if [ $TARGETARCH == 'amd64' ]; then
    HUGO_FILENAME="hugo_extended_${HUGO_VERSION}_Linux-64bit.tar.gz"
else
    HUGO_FILENAME="nhugo_extended_${HUGO_VERSION}_Linux-ARM64.tar.gz"
fi
HUGO_DOWNLOAD_URL="https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/$HUGO_FILENAME"
HUGO_CHECKSUM_URL="https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_checksums.txt"

function install_hugo() {
    if [ $TARGETARCH == 'amd64' ]; then
        ARCH='64bit'
    else
        ARCH='ARM64'
        # there is no extended build for arm
        return
    fi

    # Installing Hugo for docs
    wget --progress dot:giga $HUGO_DOWNLOAD_URL
    sha256sum -c ${BASE_DIR}/hugo-$TARGETARCH-checksum
    tar -xf hugo_extended_${HUGO_VERSION}_Linux-${ARCH}.tar.gz
    mv hugo $USR_BIN/hugo
    rm -rf hugo_extended_${HUGO_VERSION}_Linux-${ARCH}.tar.gz LICENSE README.md
}

[ ${SKIP_INSTALL:-false} != false ] || install_hugo


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/linuxkit

source $SCRIPT_ROOT/common_vars.sh

function install_linuxkit() {
    # linuxkit is used by tinkerbell/hook for building an operating system installation environment (osie)
    # We need a higher version of linuxkit hence we do go install of a particular commit
    GO111MODULE=on GOBIN=${GOPATH}/go1.19/bin ${GOPATH}/go1.19/bin/go install github.com/linuxkit/linuxkit/src/cmd/linuxkit@$LINUXKIT_VERSION

    mv ${GOPATH}/go1.19/bin/linuxkit ${USR_BIN}/linuxkit

    rm -rf ${GOPATH}
}

[ ${SKIP_INSTALL:-false} != false ] || install_linuxkit


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/nodejs

source $SCRIPT_ROOT/common_vars.sh

if [ $TARGETARCH == 'amd64' ]; then
    NODEJS_FILENAME="node-$NODEJS_VERSION-linux-x64.tar.gz"
    NODEJS_FOLDER="node-$NODEJS_VERSION-linux-x64"
else
    NODEJS_FILENAME="node-$NODEJS_VERSION-linux-arm64.tar.gz"
    NODEJS_FOLDER="node-$NODEJS_VERSION-linux-arm64"
fi
NODEJS_DOWNLOAD_URL="https://nodejs.org/dist/$NODEJS_VERSION/$NODEJS_FILENAME"
NODEJS_CHECKSUM_URL="https://nodejs.org/dist/$NODEJS_VERSION/SHASUMS256.txt.asc"

function install_nodejs() {
    # Installing NodeJS to run attribution generation script
    wget --progress dot:giga $NODEJS_DOWNLOAD_URL
    sha256sum -c ${BASE_DIR}/nodejs-$TARGETARCH-checksum
    tar -C $USR --strip-components=1 -xzf $NODEJS_FILENAME $NODEJS_FOLDER
    rm -rf $NODEJS_FILENAME
}

function install_generate_attribution() {
    # Installing attribution generation script
    mkdir ${NEWROOT}/generate-attribution-file
    mv /package*.json /generate-attribution /generate-attribution-file.js /LICENSE-2.0.txt ${NEWROOT}/generate-attribution-file

    cd ${NEWROOT}/generate-attribution-file
    ln -s /generate-attribution-file/generate-attribution $USR_BIN/generate-attribution

    ln -s /$USR_BIN/node /usr/bin/node
    $USR_BIN/npm install
}

[ ${SKIP_INSTALL:-false} != false ] || (install_nodejs && install_generate_attribution)


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/packer

source $SCRIPT_ROOT/common_vars.sh

PACKER_DOWNLOAD_URL="https://releases.hashicorp.com/packer/$PACKER_VERSION/packer_${PACKER_VERSION}_linux_$TARGETARCH.zip"
PACKER_CHECKSUM_URL="https://releases.hashicorp.com/packer/$PACKER_VERSION/packer_${PACKER_VERSION}_SHA256SUMS"

function install_packer() {
    # put packer in /usr/local/bin so it takes precedent
    # over the /usr/sbin/packer which is supplied by the cracklib package
    wget \
        --progress dot:giga \
        $PACKER_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/packer-$TARGETARCH-checksum
    unzip -o packer_${PACKER_VERSION}_linux_$TARGETARCH.zip -d $USR_LOCAL_BIN
}

[ ${SKIP_INSTALL:-false} != false ] || install_packer


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/skopeo

source $SCRIPT_ROOT/common_vars.sh

function install_skopeo() {
    local -r deps="device-mapper-devel libassuan-devel gpgme-devel"
    yum install -y $deps

    # Installing Skopeo
    git clone https://github.com/containers/skopeo
    cd skopeo
    git checkout $SKOPEO_VERSION
    make bin/skopeo
    mv bin/skopeo $USR_BIN/skopeo

    cd ..
    rm -rf ${GOPATH} skopeo
}

[ ${SKIP_INSTALL:-false} != false ] || install_skopeo


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/tuftool

source $SCRIPT_ROOT/common_vars.sh

RUSTUP_DOWNLOAD_URL="https://sh.rustup.rs"

function install_tuftool() {
    local -r deps="openssl openssl-devel"
    yum install -y $deps

    # Installing Tuftool for Bottlerocket downloads
    curl -fsS $RUSTUP_DOWNLOAD_URL | CARGO_HOME=$CARGO_HOME RUSTUP_HOME=$RUSTUP_HOME sh -s -- -y
    find $CARGO_HOME/bin -type f -not -name "cargo" -not -name "rustc" -not -name "rustup" -delete
    $CARGO_HOME/bin/rustup default stable
    CARGO_NET_GIT_FETCH_WITH_CLI=true $CARGO_HOME/bin/cargo install --force -v --root $CARGO_HOME tuftool
    cp $CARGO_HOME/bin/tuftool $USR_BIN/tuftool

    rm -rf $RUSTUP_HOME $CARGO_HOME
}

[ ${SKIP_INSTALL:-false} != false ] || install_tuftool


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

NEWROOT=/yq

source $SCRIPT_ROOT/common_vars.sh

YQ_DOWNLOAD_URL="https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/yq_linux_$TARGETARCH.tar.gz"
YQ_CHECKSUM_URL="https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/checksums"
YQ_CHECKSUM_ORDER_URL="https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/checksums_hashes_order"

function install_yq() {
    # needed to parse eks-d release yaml to get latest artifacts
    wget \
        --progress dot:giga \
        $YQ_DOWNLOAD_URL
    sha256sum -c $BASE_DIR/yq-$TARGETARCH-checksum
    tar -C $USR_BIN -xzf yq_linux_$TARGETARCH.tar.gz
    mv $USR_BIN/yq_linux_$TARGETARCH $USR_BIN/yq
}

[ ${SKIP_INSTALL:-false} != false ] || install_yq


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

yum history | awk -F '|' 'NR>2{print $1}' | awk 'NF{print $1}' | grep -o '[0-9]\+' | while read id; do yum history undo --skip-broken --setopt=protected_packages=False -y $id; done


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

eval $(yq  e 'to_entries | .[] | [.key,.value] | join("=") ' versions.yaml)

for TARGETARCH in arm64 amd64; do
    source $SCRIPT_ROOT/versions.sh

    # YQ
    yq_checksum_order=($(curl -sSL --retry 5 $YQ_CHECKSUM_ORDER_URL))
    yq_checksums=$(curl -sSL --retry 5 -v --silent $YQ_CHECKSUM_URL)
    yq_checksums=$(echo "$yq_checksums" | grep yq_linux_$TARGETARCH.tar.gz | cut -d ":" -f 2)
    IFS=' ' read -r -a yq_checksums_ar <<< "$yq_checksums"

    yq_checksum_index=-1
    for i in "${!yq_checksum_order[@]}"; do
        if [[ "${yq_checksum_order[$i]}" = "SHA-256" ]]; then
            yq_checksum_index=$(($i+1))
        fi
    done
    echo $yq_checksum_index
    echo "${yq_checksums_ar[*]}"
    sha256="${yq_checksums_ar[$yq_checksum_index]}"
    echo "$sha256  yq_linux_$TARGETARCH.tar.gz" > $CHECKSUMS_ROOT/checksums/yq-$TARGETARCH-checksum

    # AMAZON_ECR_CRED_HELPER
    curl -sSL --retry 5 $AMAZON_ECR_CRED_HELPER_CHECKSUM_URL -o $CHECKSUMS_ROOT/checksums/amazon-ecr-cred-helper-$TARGETARCH-checksum

    # BUILDKIT
    sha256=$(curl -sSL --retry 5 $BUILDKIT_DOWNLOAD_URL | sha256sum | awk '{print $1}')
    echo "$sha256  buildkit-$BUILDKIT_VERSION.linux-$TARGETARCH.tar.gz" > $CHECKSUMS_ROOT/checksums/buildkit-$TARGETARCH-checksum

    # DOCKER_BUILDX
    echo "$(curl -sSL --retry 5 -v --silent $DOCKER_BUILDX_CHECKSUM_URL 2>&1 | grep buildx-${DOCKER_BUILDX_VERSION}.linux-$TARGETARCH | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/docker-buildx-$TARGETARCH-checksum

    # GITHUB CLI
    echo "$(curl -sSL --retry 5 -v --silent $GITHUB_CLI_CHECKSUM_URL 2>&1 | grep  gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/github-cli-$TARGETARCH-checksum

    # PACKER
    echo "$(curl -sSL --retry 5 -v --silent $PACKER_CHECKSUM_URL 2>&1 | grep packer_${PACKER_VERSION}_linux_$TARGETARCH.zip | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/packer-$TARGETARCH-checksum

    # NODEJS
    echo "$(curl -sSL --retry 5 -v --silent $NODEJS_CHECKSUM_URL 2>&1 | grep $NODEJS_FILENAME | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/nodejs-$TARGETARCH-checksum

    # HELM
    sha256=$(curl -sSL --retry 5 $HELM_CHECKSUM_URL)
    echo "$sha256  helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz" > $CHECKSUMS_ROOT/checksums/helm-$TARGETARCH-checksum

    # GOVC
    echo "$(curl -sSL --retry 5 -v  $GOVC_CHECKSUM_URL 2>&1 | grep $GOVC_FILENAME | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/govc-$TARGETARCH-checksum

    # GOSS
    echo "$(curl -sSL --retry 5 -v --silent $GOSS_CHECKSUM_URL 2>&1 | grep packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/goss-$TARGETARCH-checksum
done

# HUGO
echo "$(curl -sSL --retry 5 -v --silent $HUGO_CHECKSUM_URL 2>&1 | grep $HUGO_FILENAME | cut -d ":" -f 2)" > $CHECKSUMS_ROOT/checksums/hugo-$TARGETARCH-checksum

# BASH
sha256=$(curl -sSL --retry 5 $BASH_DOWNLOAD_URL | sha256sum | awk '{print $1}')
echo "$sha256  bash-$OVERRIDE_BASH_VERSION.tar.gz" > $CHECKSUMS_ROOT/checksums/bash-checksum


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

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

uname -a

docker-credential-ecr-login -v
yq --version
gh --version
govc version
helm version
/usr/local/lib/docker/cli-plugins/docker-buildx version
buildctl --version
aws --version
bash --version

if [ $TARGETARCH == 'amd64' ]; then
    hugo version
    # goss
fi

tuftool --help
skopeo --version

# node + go + gcc are only included in the standard image
if [ "${FINAL_STAGE_BASE}" = "full-copy-stage" ]; then
    packer --version
    ansible --version

    node --version

    # validate default symlinks are correctly setup
    go version
    go-licenses --help

    /go/bin/go1.16 version
    /go/go1.16/bin/go-licenses --help
    linuxkit version
    /go/bin/go1.17 version
    /go/go1.17/bin/go-licenses --help
    /go/bin/go1.18 version
    /go/go1.18/bin/go-licenses --help
    /go/bin/go1.19 version
    /go/go1.19/bin/go-licenses --help

    gcc --version
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.

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

export SKIP_INSTALL="true"

source $SCRIPT_ROOT/install_aws_cli.sh
source $SCRIPT_ROOT/install_buildkit.sh
source $SCRIPT_ROOT/install_docker_buildx.sh
source $SCRIPT_ROOT/install_ecr_cred_helper.sh
source $SCRIPT_ROOT/install_gh_cli.sh
source $SCRIPT_ROOT/install_yq.sh
source $SCRIPT_ROOT/install_packer.sh
source $SCRIPT_ROOT/install_nodejs.sh
source $SCRIPT_ROOT/install_helm.sh
source $SCRIPT_ROOT/install_goss.sh
source $SCRIPT_ROOT/install_govc.sh
source $SCRIPT_ROOT/install_hugo.sh
source $SCRIPT_ROOT/install_bash.sh


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail
set -x

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

IMAGE_NAME="$1"
AL_TAG="$2"
NAME_FOR_TAG_FILE="$3"

if [[ $IMAGE_NAME == *-builder ]]; then
    # ignore checking builder images
    exit 0
fi

BASE_IMAGE_TAG="$(yq e ".al$AL_TAG.\"$NAME_FOR_TAG_FILE\"" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)"
BASE_IMAGE=public.ecr.aws/eks-distro-build-tooling/$IMAGE_NAME:$BASE_IMAGE_TAG
mkdir -p check-update

cat << EOF > check-update/Dockerfile
FROM $BASE_IMAGE AS base_image

FROM public.ecr.aws/amazonlinux/amazonlinux:$AL_TAG as builder

RUN rm -rf /var/lib/rpm
COPY --from=base_image /var/lib/rpm /var/lib/rpm
COPY --from=base_image /etc/yum.repos.d /etc/yum.repos.d

RUN set -x && \
    if grep -q "2023" "/etc/os-release"; then \
        yum check-update --security --releasever=latest  > ./check_update_output; echo \$? > ./return_value; \
    else \
        yum check-update --security  > ./check_update_output; echo \$? > ./return_value; \
    fi && \
    cat ./check_update_output | awk '/^$/,0' | awk '{print \$1}' > ./update_packages

FROM scratch

COPY --from=builder ./return_value ./return_value
COPY --from=builder ./update_packages ./update_packages
EOF

$SCRIPT_ROOT/../scripts/buildkit.sh build --frontend dockerfile.v0 \
         --opt platform=linux/amd64 \
         --opt filename=./check-update/Dockerfile \
         --local context=. \
         --progress plain \
         --output type=local,dest=/tmp/${IMAGE_NAME} \
    || {
            mkdir -p /tmp/${IMAGE_NAME}
            echo "100" > /tmp/${IMAGE_NAME}/return_value
            echo "" > /tmp/${IMAGE_NAME}/update_packages
        }

RETURN_STATUS=$(cat /tmp/${IMAGE_NAME}/return_value)

if [ "$JOB_TYPE" != "periodic" ]; then
    echo "none" > ./check-update/${NAME_FOR_TAG_FILE}
    exit 0
fi

if [ $RETURN_STATUS -eq 100 ]; then
    cat /tmp/${IMAGE_NAME}/update_packages > ${SCRIPT_ROOT}/../eks-distro-base-updates/${AL_TAG}/update_packages-${NAME_FOR_TAG_FILE}
    echo "updates" > ./check-update/${NAME_FOR_TAG_FILE}
elif [ $RETURN_STATUS -eq 0 ]; then
    echo "none" > ./check-update/${NAME_FOR_TAG_FILE}
elif [ $RETURN_STATUS -eq 1 ]; then
    echo "error" > ./check-update/${NAME_FOR_TAG_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 -e
set -o pipefail
set -x
SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

IMAGE_NAME="$1"
AL_TAG="$2"
NAME_FOR_TAG_FILE="$3"

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

BASE_IMAGE_TAG="$(yq e ".windows.\"$NAME_FOR_TAG_FILE\"" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)"

mkdir -p check-update

if [ "$BASE_IMAGE_TAG" = "null" ]; then
    echo "updates" > ./check-update/${NAME_FOR_TAG_FILE}
    exit 0
fi

BASE_IMAGE=public.ecr.aws/eks-distro-build-tooling/$IMAGE_NAME

# Pull the buildinfo from the last published image which will contain the sha of the two windows images
# used to build that image. Compare these sha with the current shas tagged upstream for this given
# windows version. If the current tag points to a different sha, the image needs updating
BUILDINFO=$(retry skopeo inspect --config --override-os windows --override-arch amd64 docker://$BASE_IMAGE:$BASE_IMAGE_TAG --raw   | jq -r '."moby.buildkit.buildinfo.v1"' | base64 -d)

for variant in "nanoserver" "servercore"; do
    SOURCE_IMAGE_REF=$(jq -r ".sources | .[] | select(.ref | contains(\"$variant\")) | .ref" <<< "$BUILDINFO")
    SOURCE_IMAGE_PIN=$(jq -r ".sources | .[] | select(.ref | contains(\"$variant\")) | .pin" <<< "$BUILDINFO")

    if [ "$(retry docker buildx imagetools inspect --raw $SOURCE_IMAGE_REF@$SOURCE_IMAGE_PIN)" != "$(retry docker buildx imagetools inspect --raw $SOURCE_IMAGE_REF)" ]; then
        echo "updates" > ./check-update/${NAME_FOR_TAG_FILE}
        exit 0
    fi
done

echo "none" > ./check-update/${NAME_FOR_TAG_FILE}


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

IMAGE_NAME="$1"
IMAGE="$2"
LATEST_IMAGE="$3"
WINDOWS_IMAGE_VERSION="$4"
WINDOWS_IMAGE_REGISTRY="$5"
WINDOWS_BASE_IMAGE_NAME="$6"

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

if [ ! -f /tmp/$IMAGE_NAME-metadata.json ]; then
    echo "No metadata file for image: /tmp/$IMAGE_NAME-metadata.json!"
    exit 1
fi

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

retry docker buildx imagetools inspect --raw $WINDOWS_IMAGE_REGISTRY/$WINDOWS_BASE_IMAGE_NAME:$WINDOWS_IMAGE_VERSION \
    | jq '.manifests[0] | {platform}' \
    | jq add -s - /tmp/$IMAGE_NAME-descr.json > /tmp/$IMAGE_NAME-descr-final.json

retry docker buildx imagetools create --dry-run -f /tmp/$IMAGE_NAME-descr-final.json -t $IMAGE -t $LATEST_IMAGE > /tmp/$IMAGE_NAME-manfiest-final.json

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

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

retry docker buildx imagetools create -f /tmp/$IMAGE_NAME-descr-final.json -t $IMAGE -t $LATEST_IMAGE

retry docker buildx imagetools inspect $IMAGE

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

retry validate_latest

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


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

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

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

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

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

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

touch $HELPFILE

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

VARIANTS=$(make --no-print-directory -C $MAKE_ROOT var-value-MINIMAL_VARIANTS)
VARIANTS=(${VARIANTS// / })

MAIN_MINIMAL_TARGETS="${NL}${NL}##@ Main Minimal Targets"
EXPORT_MINIMAL_TARGETS="${NL}${NL}##@ Package Export Minimal Targets"
VALIDATE_MINIMAL_TARGETS="${NL}${NL}##@ Validate Minimal Targets"
TEST_MINIMAL_TARGETS="${NL}${NL}##@ Test Minimal Targets"
UPDATE_MINIMAL_TARGETS="${NL}${NL}##@ Update Minimal Targets"
CREATE_PR_MINIMAL_TARGETS="${NL}${NL}##@ Create PR Minimal Targets"

for variant in "${VARIANTS[@]}"; do
    MAIN_MINIMAL_TARGETS+="${NL}minimal-images-${variant}: ## Build, export packages, validate and run tests for minimal variant \`${variant}\`"
    EXPORT_MINIMAL_TARGETS+="${NL}packages-export-minimal-images-${variant}: ## Export packages for minimal variant \`${variant}\`"
    VALIDATE_MINIMAL_TARGETS+="${NL}validate-minimal-images-${variant}: ## Validate for minimal variant \`${variant}\`"
    TEST_MINIMAL_TARGETS+="${NL}test-minimal-images-${variant}: ## Run tests for minimal variant \`${variant}\`"
    UPDATE_MINIMAL_TARGETS+="${NL}minimal-update-${variant}: ## Run update logic for minimal variant \`${variant}\`"
    CREATE_PR_MINIMAL_TARGETS+="${NL}minimal-create-pr-${variant}: ## Run create pr logic for minimal variant \`${variant}\`"
done

COMPILERS_TARGETS="${NL}${NL}##@ Compiler Images Targets"
COMPILERS=$(make --no-print-directory -C $MAKE_ROOT var-value-COMPILERS)
COMPILERS=(${COMPILERS// / })
for compiler in "${COMPILERS[@]}"; do
    COMPILERS_TARGETS+="${NL}${compiler}-compiler-images: ## Build compiler images for all versions of ${compiler}"
    VERSIONS=$(make --no-print-directory -C $MAKE_ROOT var-value-BASE_${compiler^^}_VARIANT_VERSIONS)
    VERSIONS=(${VERSIONS// / })
    for version in "${VERSIONS[@]}"; do
        COMPILERS_TARGETS+="${NL}${compiler}-${version}-compiler-images: ## Build compiler images for ${compiler}-${version}"
    done
done

cat >> $HELPFILE << EOF
${NL}${NL}${NL}${HEADER}
# To update call: make add-generated-help-block
# This is added to help document dynamic targets and support shell autocompletion
${MAIN_MINIMAL_TARGETS}${EXPORT_MINIMAL_TARGETS}${VALIDATE_MINIMAL_TARGETS}${TEST_MINIMAL_TARGETS}${UPDATE_MINIMAL_TARGETS}${CREATE_PR_MINIMAL_TARGETS}${COMPILERS_TARGETS}

${FOOTER}
EOF

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


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

MIRROR=$(curl -s http://amazonlinux.default.amazonaws.com/2/core/latest/debuginfo/x86_64/mirror.list)
VERSION=$(curl -s $MIRROR/repodata/primary.xml.gz | gunzip | sed -rn 's/^.*python3-debuginfo-(.*)\-[0-9].amzn.*$/\1/p' | sed '/-/!{s/$/_/}' | sort -V | sed 's/_$//' | tail -1)

if [ -f /etc/os-release ] && grep "Amazon Linux 2" /etc/os-release; then
    if [ "$(yum info python3  | grep "^Version" | cut -d: -f2 | xargs)" != "$VERSION" ]; then
        echo "Yum version does not match curl'd!"
        exit 1
    fi
fi

echo $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 -e
set -o pipefail
set -x

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
IMAGE_TAG=$1
IMAGE_NAME=$2
AL_TAG=$3
PR_BRANCH="$4"

if [ "$AL_TAG" != "windows" ]; then
    AL_TAG="al$AL_TAG"
fi

OLD_TAG="$(yq e ".al$AL_TAG.\"$IMAGE_NAME\"" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)"
BASE_IMAGE_TAG_FILE="$(echo ${IMAGE_NAME^^} | sed 's/[\.-]/_/g')_TAG_FILE"

${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh eks-distro-build-tooling $PR_BRANCH
${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-distro-build-tooling $OLD_TAG ".$AL_TAG.\"$IMAGE_NAME\" |= \"$IMAGE_TAG\"" "EKS_DISTRO_TAG_FILE.yaml" true


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail
set -x

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

OTHER_CLONE_ROOT=${OTHER_CLONE_ROOT:-${SCRIPT_ROOT}/../../..}
if [ $REPO_OWNER = "aws" ]; then
    ORIGIN_ORG="eks-distro-pr-bot"
else
    ORIGIN_ORG=$REPO_OWNER
fi

EXTRA_PR_BODY=""

REPOS=(eks-distro eks-anywhere-build-tooling eks-anywhere)
for repo in "${REPOS[@]}"; do
    ${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh "$repo"
done
while IFS=, read -r key
do
    key=${key:2} # strip leading - space
    while IFS=, read -r image
    do
        image=${image:2} # strip leading - space
        BASE_IMAGE_TAG_FILE="$(echo ${image^^} | tr '-' '_')_TAG_FILE"

        if [[ "$key" == "al2023" ]]; then
            BASE_IMAGE_TAG_FILE="$(echo ${image^^} | tr '-' '_')_AL2023_TAG_FILE"
        fi

        IMAGE_TAG=$(yq e ".$key.\"$image\"" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)
        # we will set the tag to null to trigger new builds. we dont want PRs being open setting
        # tag file values to null
        if [[ "${IMAGE_TAG}" = "null" ]]; then
            continue
        fi
        for repo in "${REPOS[@]}"; do
            ${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh "$repo" '.*' $IMAGE_TAG $BASE_IMAGE_TAG_FILE

            if [ "$(git -C ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${repo} status --porcelain -- $BASE_IMAGE_TAG_FILE | wc -l)" -gt 0 ]; then
                UPDATE_PACKAGES="$(cat ${SCRIPT_ROOT}/../eks-distro-base-updates/${key#al}/update_packages-${image})"
                if [ "$UPDATE_PACKAGES" != "" ]; then
                    EXTRA_PR_BODY+="\n${BASE_IMAGE_TAG_FILE}\nThe following yum packages were updated:\n\`\`\`bash\n${UPDATE_PACKAGES}\n\`\`\`\n"
                fi
            fi
        done
    done < <(yq e ".$key | keys" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)
done < <(yq e "keys" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)

for repo in "${REPOS[@]}"; do
   ${SCRIPT_ROOT}/../pr-scripts/create_pr.sh "$repo" 'EKS_DISTRO*_TAG_FILE' "image-tag-update" "$EXTRA_PR_BODY"
done


#!/bin/bash
#
# Copyright 2020 The Kubernetes Authors.
#
# 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

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

build_arg=""
build_fail=0
nft_fail=0

while [[ $# -gt 1 ]]; do
    case "$1" in
	--build-arg=*)
	    build_arg="${1#--build_arg=}"
	    ;;
	--build-arg)
	    shift
	    build_arg="$1"
	    ;;
	--build-fail)
	    build_fail=1
	    ;;
	--nft-fail)
	    nft_fail=1
	    ;;
	*)
	    echo "Unrecognized flag '$1'" 1>&2
	    exit 1
	    ;;
    esac
    shift
done
tag="$1"

if podman -h &> /dev/null; then
    docker_binary=podman
elif docker -h &> /dev/null; then
    if docker version &> /dev/null; then
	docker_binary=docker
    else
	docker_binary="sudo docker"
	# Get the password prompting out of the way now
	sudo docker version > /dev/null
    fi
else
    echo "Could not find podman or docker" 1>&2
    exit 1
fi

function docker() {
    if [[ -n "${DEBUG:-}" ]]; then
	command ${docker_binary} "$@"
    else
	if [[ "$1" == "build" ]]; then
	    echo "    docker $*"
	fi
	# Redirect stdout to /dev/null and indent stderr
	command ${docker_binary} "$@" 2>&1 > /dev/null | \
	    sed -e '/debconf: delaying package configuration/ d' \
		-e 's/^/    /'
    fi
}

function build() {
	if [[ -z "${DEBUG:-}" ]]; then
		quiet="-q"
	fi

	if [[ -z "${CACHE_BUILDS:-}" ]]; then
		no_cache="--no-cache"
	fi

    build_tag=iptables-wrapper-test-$1
    dockerfile=Dockerfile.test-${1%%-*}
    shift

    docker build ${no_cache:-} ${quiet:-} -t ${build_tag} -f test/${dockerfile} "$@" .
}

function PASS() {
    printf "\033[1;92mPASS: $@\033[0m\n\n"
    exit 0
}

function FAIL() {
    printf "\033[1;31mFAIL: $@\033[0m\n" 1>&2
    exit 1
}

if ! build "${tag}" ${build_arg}; then
    if [[ "${build_fail}" = 1 ]]; then
	PASS "build failed as expected"
    fi
    FAIL "build failed unexpectedly"
fi

if ! docker run --privileged "iptables-wrapper-test-${tag}" /tests -test.v -test.run "^TestIPTablesWrapperLegacy$" ; then
    FAIL "failed legacy iptables"
fi
if ! docker run --privileged "iptables-wrapper-test-${tag}" /tests -test.v -test.run "^TestIPTablesWrapperNFT$" ; then
    FAIL "failed nft iptables"
fi

if ! docker run --privileged "iptables-wrapper-test-${tag}" /tests -test.v -test.run "^TestIP6TablesWrapperLegacy$" ; then
    FAIL "failed legacy ip6tables"
fi
if ! docker run --privileged "iptables-wrapper-test-${tag}" /tests -test.v -test.run "^TestIP6TablesWrapperNFT$" ; then
    FAIL "failed nft ip6tables"
fi

PASS "success"


#!/bin/sh

# Copyright 2022 The Kubernetes Authors.
#
# 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.

# USAGE: clean-distroless.sh

# Modified version of https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/clean-distroless.sh

REMOVE="/usr/share/base-files
/usr/share/man
/usr/lib/*-linux-gnu/gconv/
/usr/bin/c_rehash
/usr/bin/openssl
/bin/mv
/bin/chmod
/bin/grep
/bin/ln
/bin/sleep
/usr/bin/wc
/iptables-wrapper-installer.sh
/bin/sh
/bin/dash
/clean-distroless.sh
/bin/rm"

IFS="
"

for item in ${REMOVE}; do
    rm -rf "${item}"
done


#!/bin/bash

# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/package-utils.sh

# Copyright 2022 The Kubernetes Authors.
#
# 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.

# file_to_package identifies the debian package that provided the file $1
file_to_package() {
    # `dpkg-query --search $file-pattern` outputs lines with the format: "$package: $file-path"
    # where $file-path belongs to $package
    # https://manpages.debian.org/jessie/dpkg/dpkg-query.1.en.html
    dpkg-query --search "$(realpath "${1}")" | cut -d':' -f1
}

# package_to_copyright gives the path to the copyright file for the package $1
package_to_copyright() {
    echo "/usr/share/doc/${1}/copyright"
}

# stage_file stages the filepath $1 to $2, following symlinks
# and staging copyrights
stage_file() {
    cp -a --parents "${1}" "${2}"
    # recursively follow symlinks
    if [[ -L "${1}" ]]; then
        stage_file "$(cd "$(dirname "${1}")" || exit; realpath -s "$(readlink "${1}")")" "${2}"
    fi
    # get the package so we can stage package metadata as well
    package="$(file_to_package "${1}")"
    # stage the copyright for the file
    cp -a --parents "$(package_to_copyright "${package}")" "${2}"
    # stage the package status mimicking bazel
    # https://github.com/bazelbuild/rules_docker/commit/f5432b813e0a11491cf2bf83ff1a923706b36420
    # instead of parsing the control file, we can just get the actual package status with dpkg
    dpkg -s "${package}" > "${2}/var/lib/dpkg/status.d/${package}"
}


#!/bin/bash

# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/stage-binaries-from-package.sh

# Copyright 2022 The Kubernetes Authors.
#
# 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.

# USAGE: stage-binaries-from-package.sh /opt/stage package1 package2
#
# Stages all the packages and its dependencies (+ libraries and copyrights) to $1
#
# This is intended to be used in a multi-stage docker build with a distroless/base
# or distroless/cc image.
set -e

. package-utils.sh

stage_file_list() {
    IFS="
    "
    REQUIRED_FILES="$(dpkg -L "${1}" | grep -vE '(/\.|/s?bin/|/usr/share/(man|doc|.*-completion))' | sed 's/\n/ /g')"
    for file in $REQUIRED_FILES; do
        if [ -f "$file" ]; then
            stage_file "${file}" "${STAGE_DIR}"
        fi
    done

    BIN_LIST="$(dpkg -L "${1}" | grep -E '/s?bin/' |sed 's/\n/ /g')"
    for binary in $BIN_LIST; do
        /stage-binary-and-deps.sh "${2}" "${binary}"
    done
}

get_dependent_packages() {
    apt-cache depends "${1}" |grep Depends|awk -F '.*Depends:[[:space:]]?' '{print $2}'
}

main() {
    STAGE_DIR="${1}/"
    mkdir -p "${STAGE_DIR}"/var/lib/dpkg/status.d/
    apt -y update
    shift
    while (( "$#" )); do        # While there are arguments still to be shifted
        PACKAGE="${1}"
        apt -y install "${PACKAGE}"
        stage_file_list "${PACKAGE}" "$STAGE_DIR"
        while IFS= read -r c_dep; do
            stage_file_list "${c_dep}" "${STAGE_DIR}"
        done < <(get_dependent_packages "${PACKAGE}")
        shift
    done
}

main "$@"


#!/bin/bash

# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/stage-binary-and-deps.sh

# Copyright 2021 The Kubernetes Authors.
#
# 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.

# USAGE: stage-binary-and-deps.sh haproxy /opt/stage
#
# Stages $1 and its dependencies + their copyright files to $2
#
# This is intended to be used in a multi-stage docker build with a distroless/base
# or distroless/cc image.
# This script was originally created by KinD maintainers and can be found at:
#   https://github.com/kubernetes-sigs/kind/blob/v0.14.0/images/haproxy/stage-binary-and-deps.sh

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

. package-utils.sh

# binary_to_libraries identifies the library files needed by the binary $1 with ldd
binary_to_libraries() {
    # see: https://man7.org/linux/man-pages/man1/ldd.1.html
    ldd "${1}" \
    `# strip the leading '${name} => ' if any so only '/lib-foo.so (0xf00)' remains` \
    | sed -E 's#.* => /#/#' \
    `# we want only the path remaining, not the (0x${LOCATION})` \
    | awk '{print $1}' \
    `# linux-vdso.so.1 is a special virtual shared object from the kernel` \
    `# see: http://man7.org/linux/man-pages/man7/vdso.7.html` \
    | grep -v 'linux-vdso.so.1'
}

# main script logic
main(){
    local STAGE_DIR="${1}/"
    shift
    while (( "$#" )); do
        BINARY="${1}"
        # locate the path to the binary
        local binary_path
        binary_path="$(which "${BINARY}")"

        # ensure package metadata dir
        mkdir -p "${STAGE_DIR}"/var/lib/dpkg/status.d/

        # stage the binary itself
        stage_file "${binary_path}" "${STAGE_DIR}"

        # stage the dependencies of the binary
        while IFS= read -r c_dep; do
            stage_file "${c_dep}" "${STAGE_DIR}"
        done < <(binary_to_libraries "${binary_path}")
        shift
    done
}

main "$@"


#!/usr/bin/env bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail
set -x

IMAGE_REPO=$1
IMAGE_TAG=$2
AL_TAG=$3
PLATFORMS="$4"
TEST=$5
LOCAL_REGISTRY=$6

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

if [ "$AL_TAG" = "2023" ]; then
    AL_TAG="23"
fi

function retry() {
  local n=1
  local max=120
  local delay=5
  while true; do
    "$@" && break || {
      if [[ $n -lt $max ]]; then
        ((n++))
        sleep $delay;
      fi
    }
  done
}

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

function check_base() {
    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --progress plain \
        --opt target=check-base \
        --local dockerfile=./ \
		--local context=./tests \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest\",push=true

    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest
        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest; then
            echo "base issue!"
            exit 1
        fi
    done
}

function check_base-nonroot() {
    echo "not impl"
}

function check_base-glibc() {
    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-glibc:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --progress plain \
        --opt target=check-cgo \
        --local dockerfile=./ \
		--local context=./tests \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest\",push=true

    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest
        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest | grep -v 'Printed from unsafe C code'; then
            echo "glibc issue!"
            exit 1
        fi
    done
}

function cleanup-iptable-rules() {
    local mode
    local ip
    for mode in legacy nft; do
        # ensure they do not already exist
        for ip in iptables ip6tables; do
            docker run --privileged --rm --net host --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-$mode-latest $ip -t mangle -X KUBE-IPTABLES-HINT &> /dev/null || true
        done
    done
}

function check_base-iptables() {
    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --progress plain \
        --opt target=check-iptables-legacy \
        --local dockerfile=./ \
		--local context=./tests \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest\",push=true

    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --progress plain \
        --opt target=check-iptables-nft \
        --local dockerfile=./ \
		--local context=./tests \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest\",push=true

    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --progress plain \
        --opt target=check-iptables-wrapper \
        --local dockerfile=./ \
		--local context=$SCRIPT_ROOT/../ \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest\",push=true

    local platform
    local mode
    local ip
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest

        # ensure defatult is set to legacy which was set in dockerfile
        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest update-alternatives --list | grep 'iptables' | xargs)" != "iptables manual /usr/sbin/iptables-legacy" ]]; then
            echo "iptables legacy alternative issue!"
            exit 1
        fi

        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest update-alternatives --list | grep 'ip6tables' | xargs)" != "ip6tables manual /usr/sbin/ip6tables-legacy" ]]; then
            echo "ip6tables legacy alternative issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest iptables --version | grep -v 'legacy'; then
            echo "iptables legacy issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest ip6tables --version | grep -v 'legacy'; then
            echo "ip6tables legacy issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest iptables-save; then
            echo "iptables-save legacy issue!"
            exit 1
        fi
        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest ip6tables-save; then
            echo "ip6tables-save legacy issue!"
            exit 1
        fi

        # nft mode will fail when running on a host that does not match the arch, both arch have been confirmed to work on their respective
        # arch based instances
        if [[ ! "$platform" = "linux/$(go env GOHOSTARCH)" ]]; then
            continue
        fi

        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest

        # ensure defatult is set to nft which was set in dockerfile
        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest update-alternatives --list | grep 'iptables' | xargs)" != "iptables manual /usr/sbin/iptables-nft" ]]; then
            echo "iptables nft alternative issue!"
            exit 1
        fi

        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest update-alternatives --list | grep 'ip6tables' | xargs)" != "ip6tables manual /usr/sbin/ip6tables-nft" ]]; then
            echo "ip6tables nft alternative issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest iptables --version | grep -v 'nf_tables'; then
            echo "iptables nft issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest ip6tables --version | grep -v 'nf_tables'; then
            echo "ip6tables nft issue!"
            exit 1
        fi

        # these are included to match upstream, but default to nft and are not explictly set anywhere accross eks-d/a
        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest ebtables --version; then
            echo "ebtables nft issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest arptables --version; then
            echo "arptables nft issue!"
            exit 1
        fi

        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest

        # ensure defatult is set to wrapper which was set in dockerfile
        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest update-alternatives --list | grep '^iptables' | xargs)" != "iptables manual /usr/sbin/iptables-wrapper" ]]; then
            echo "iptables wrapper alternative issue!"
            exit 1
        fi

        if [[ "$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest update-alternatives --list | grep 'ip6tables' | xargs)" != "ip6tables manual /usr/sbin/iptables-wrapper" ]]; then
            echo "ip6tables wrapper alternative issue!"
            exit 1
        fi

        # iptables-wrapper defaults to nft mode when none of the kubelet hint rules are set
        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest iptables --version | grep -v 'nf_tables'; then
            echo "iptables wrapper issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest ip6tables --version | grep -v 'nf_tables'; then
            echo "ip6tables wrapper issue!"
            exit 1
        fi

        # create KUBE-IPTABLES-HINT and test that wrapper sets the correct mode
        for mode in nft legacy; do
            local expected="$mode"
            if [[ "$mode" == "nft" ]]; then
                expected="nf_tables"
            fi

            # no matter which version of a given iptables mode is used to add the hint, it should trigger the wrapper to use that mode for both
            # depending on how the hint rule is set, the resulting mode should be set
            for ip in iptables ip6tables; do
                cleanup-iptable-rules

                docker run --privileged --rm --net host --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-$mode-latest $ip -t mangle -N KUBE-IPTABLES-HINT

                if docker run --privileged --net host --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest iptables --version | grep -v "$expected"; then
                    echo "iptables wrapper issue!"
                    exit 1
                fi

                if docker run --privileged --net host --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest ip6tables --version | grep -v "$expected"; then
                    echo "iptables wrapper issue!"
                    exit 1
                fi
            done
        done

        cleanup-iptable-rules

        # run upstream test binaries which tests a number of similiar cases as above
        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run "^TestIPTablesWrapperLegacy$"; then
            echo "iptables wrapper legacy issue!"
            exit 1
        fi

        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run "^TestIPTablesWrapperNFT$"; then
            echo "iptables wrapper nft issue!"
            exit 1
        fi

        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run "^TestIP6TablesWrapperLegacy$"; then
            echo "iptables wrapper ipv6 legacy issue!"
            exit 1
        fi

        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run "^TestIP6TablesWrapperNFT$"; then
            echo "ip6tables wrapper ipv6 nft issue!"
            exit 1
        fi
    done
}

function check_base-csi() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi:$IMAGE_TAG
        if docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi:$IMAGE_TAG xfs_info -V | grep -v 'xfs_info version'; then
            echo "csi xfs issue!"
            exit 1
        fi
    done
 }

 function check_base-csi-ebs() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi-ebs:$IMAGE_TAG
        if docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi-ebs:$IMAGE_TAG mount --version | grep -v 'mount'; then
            echo "csi xfs issue!"
            exit 1
        fi
    done
 }

 function check_base-git() {
    if [[ -z "$PRIVATE_REPO" ]]; then
        echo "Error: Please set PRIVATE_REPO to a private github repo in your github account"
        echo "example: PRIVATE_REPO=git@github.com:jaxesn/test-private.git"
        exit 1
    fi

    if [[ -z "$SSH_KEY_FOLDER" ]]; then
        echo "Error: Please set SSH_KEY_FOLDER to the local folder which contains your github private/public key"
        echo "example: SSH_KEY_FOLDER=/Users/jgw/.ssh "
        exit 1
    fi

    local netrc=""
    if [ -f $HOME/.netrc ]; then
        netrc="--secret id=netrc,src=$HOME/.netrc"
    fi

    $SCRIPT_ROOT/../../scripts/buildkit.sh  \
        build \
        --frontend dockerfile.v0 \
        --opt filename=./tests/Dockerfile \
		--opt platform=$PLATFORMS \
        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-git:$IMAGE_TAG \
        --opt build-arg:AL_TAG=$AL_TAG \
        --opt build-arg:GOPROXY=${GOPROXY:-direct} \
        --progress plain \
        --opt target=check-git \
        --local dockerfile=./ \
		--local context=./tests $netrc \
        --export-cache type=inline \
        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest \
        --output type=image,oci-mediatypes=true,\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest\",push=true

    for platform in ${PLATFORMS//,/ }; do
        # use git cli to clone private and public repo
        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest
        docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \
            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \
            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \
            $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest git clone $PRIVATE_REPO

        docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \
            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \
            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \
            $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest git clone https://github.com/aws/eks-distro.git

        # use lib git to clone private and public repo
        if docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \
            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \
            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \
            -e PRIVATE_REPO=$PRIVATE_REPO $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest check-git | grep -v 'Successfully cloned!'; then
            echo "git issue!"
            exit 1
        fi
    done

 }

 check_base-docker-client() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-docker-client:$IMAGE_TAG

        if ! docker run --rm --platform=$platform -v /var/run/docker.sock:/var/run/docker.sock $IMAGE_REPO/eks-distro-minimal-base-docker-client:$IMAGE_TAG docker info; then
            echo "docker client issue!"
            exit 1
        fi
    done
 }

 check_base-haproxy() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-haproxy:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-haproxy:$IMAGE_TAG haproxy -v; then
            echo "haproxy issue!"
            exit 1
        fi
    done
 }

 check_base-nginx() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nginx:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nginx:$IMAGE_TAG nginx -v; then
            echo "nginx issue!"
            exit 1
        fi
    done
 }

 check_base-kind() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-kind:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-kind:$IMAGE_TAG ctr -v; then
            echo "kind issue!"
            exit 1
        fi
    done
 }

 check_base-nsenter() {
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nsenter:$IMAGE_TAG

        if docker run --rm --platform=$platform  $IMAGE_REPO/eks-distro-minimal-base-nsenter:$IMAGE_TAG nsenter --version | grep -v 'nsenter from util-linux'; then
            echo "nsenter issue!"
            exit 1
        fi
    done
  }

 check_base-python3() {
    local -r version="$1"
    local -r image_component="${2:-eks-distro-minimal-base-python}"
    # Cases based on distroless's test cases
    # https://github.com/GoogleContainerTools/distroless/blob/main/experimental/python3/testdata/python3.yaml
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG

        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "print('Hello World')" | grep -v 'Hello World'; then
            echo "python3 issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "import subprocess, sys; subprocess.check_call(sys.executable + ' --version', shell=True)" | grep -v 'Python 3'; then
            echo "python3 issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "import ctypes.util; ctypes.CDLL(ctypes.util.find_library('rt')).timer_create"; then
            echo "python3 issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "import distutils.dist"; then
            echo "python3 issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "open(u'h\\xe9llo', 'w'); import sys; print(sys.getfilesystemencoding())" | grep -v 'utf-8'; then
            echo "python3 issue!"
            exit 1
        fi

        if docker run --rm --platform=$platform -v $SCRIPT_ROOT/python3-test.py:/eks-d-python-validate.py $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 /eks-d-python-validate.py | grep -v 'FINISHED ENTIRE SCRIPT'; then
            echo "python3 issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c "import ssl; print(ssl.OPENSSL_VERSION)"; then
            echo "python3 issue!"
            exit 1
        fi
    done
  }

check_base-python-3.7() {
    check_base-python3 3.7
    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-python:$IMAGE_TAG pip3 --version >/dev/null 2>&1; then
        echo "pip should not exist!"
        exit 1
    fi
}

check_base-python-3.9() {
    check_base-python3 3.9
    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-python:$IMAGE_TAG pip3 --version >/dev/null 2>&1; then
        echo "pip should not exist!"
        exit 1
    fi
}

check_base-python-compiler() {
    local -r version="$1"
    local -r variant="$2"

    check_base-compiler-$2 python
    check_base-python3 "$1" python

    for platform in ${PLATFORMS//,/ }; do
        if ! docker run --rm --platform=$platform --pull=always $IMAGE_REPO/python:$IMAGE_TAG pip3 --version; then
            echo "python issue!"
            exit 1
        fi
    done
}

check_base-python-compiler-3.7-base() {
    check_base-python-compiler 3.7 base
}

check_base-python-compiler-3.7-yum() {
    check_base-python-compiler 3.7 yum
}

check_base-python-compiler-3.7-gcc() {
    check_base-python-compiler 3.7 gcc
}

check_base-python-compiler-3.9-base() {
    check_base-python-compiler 3.9 base
}

check_base-python-compiler-3.9-yum() {
    check_base-python-compiler 3.9 yum
}

check_base-python-compiler-3.9-gcc() {
    check_base-python-compiler 3.9 gcc
}

check_base-nodejs() {
    local -r version="$1"
    local -r image_component="${2:-eks-distro-minimal-base-nodejs}"
    for platform in ${PLATFORMS//,/ }; do
        if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/$image_component:$IMAGE_TAG node --version | grep -v $version; then
            echo "nodejs issue!"
            exit 1
        fi

        if ! docker run --rm --platform=$platform --pull=always $IMAGE_REPO/$image_component:$IMAGE_TAG env node; then
            echo "nodejs issue!"
            exit 1
        fi

    done
}

check_base-nodejs-16() {
    check_base-nodejs 16

    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-nodejs:$IMAGE_TAG npm --version > /dev/null 2>&1; then
        echo "npm should not exist!"
        exit 1
    fi
}

check_base-nodejs-compiler() {
    local -r version="$1"
    local -r variant="$2"

    check_base-compiler-$2 nodejs
    check_base-nodejs "$1" nodejs

    for platform in ${PLATFORMS//,/ }; do
        if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/nodejs:$IMAGE_TAG npm --version | grep -v '8'; then
            echo "npm issue!"
            exit 1
        fi
    done
}

check_base-nodejs-compiler-16-base() {
    check_base-nodejs-compiler 16 base
}

check_base-nodejs-compiler-16-yum() {
    check_base-nodejs-compiler 16 yum
}

check_base-nodejs-compiler-16-gcc() {
    check_base-nodejs-compiler 16 gcc
}

check_base-compiler-base() {
    local -r image_component="${1:-compiler-base}"
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG curl --version; then
            echo "compiler-base issue!"
            exit 1
        fi
    done
}

check_base-compiler-yum() {
    local -r image_component="${1:-compiler-base}"
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG yum --version; then
            echo "compiler-base issue!"
            exit 1
        fi
    done
}

check_base-compiler-gcc() {
    local -r image_component="${1:-compiler-base}"
    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG

        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG gcc --version; then
            echo "compiler-base issue!"
            exit 1
        fi
    done
}

check_base-golang-compiler() {
    local -r version="$1"
    local -r variant="$2"

    check_base-compiler-$2 golang

    for platform in ${PLATFORMS//,/ }; do
        build::docker::retry_pull --platform=$platform $IMAGE_REPO/golang:$IMAGE_TAG

        if docker run --rm --platform=$platform $IMAGE_REPO/golang:$IMAGE_TAG go version | grep -v $version; then
            echo "golang issue!"
            exit 1
        fi
    done
}

check_base-golang-compiler-1.18-base() {
    check_base-golang-compiler 1.18 base
}

check_base-golang-compiler-1.18-yum() {
    check_base-golang-compiler 1.18 yum
}

check_base-golang-compiler-1.18-gcc() {
    check_base-golang-compiler 1.18 gcc
}

check_base-golang-compiler-1.19-base() {
    check_base-golang-compiler 1.19 base
}

check_base-golang-compiler-1.19-yum() {
    check_base-golang-compiler 1.19 yum
}

check_base-golang-compiler-1.19-gcc() {
    check_base-golang-compiler 1.19 gcc
}

check_base-golang-compiler-1.20-base() {
    check_base-golang-compiler 1.20 base
}

check_base-golang-compiler-1.20-yum() {
    check_base-golang-compiler 1.20 yum
}

check_base-golang-compiler-1.20-gcc() {
    check_base-golang-compiler 1.20 gcc
}

$TEST


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

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

declare -A cases["coredns/coredns"]='github.com/coredns/coredns'
    cases['containernetworking/plugins']='github.com/containernetworking/plugins'
    cases['etcd-io/etcd']='go.etcd.io/etcd'
    cases['fluxcd/source-controller']='github.com/fluxcd/source-controller'
    cases['kubernetes/release']='k8s.io/release/images/build/go-runner'
    cases['kubernetes-csi/external-attacher']='github.com/kubernetes-csi/external-attacher'
    cases['kubernetes-csi/external-provisioner']='github.com/kubernetes-csi/external-provisioner'
    cases['kubernetes-csi/external-resizer']='github.com/kubernetes-csi/external-resizer'
    cases['kubernetes-csi/external-snapshotter']='github.com/kubernetes-csi/external-snapshotter/v3'
    cases['kubernetes-csi/livenessprobe']='github.com/kubernetes-csi/livenessprobe'
    cases['kubernetes-csi/node-driver-registrar']='github.com/kubernetes-csi/node-driver-registrar'
    cases['kubernetes-sigs/aws-iam-authenticator']='sigs.k8s.io/aws-iam-authenticator'
    cases['kubernetes-sigs/cri-tools']='github.com/kubernetes-sigs/cri-tools'
    cases['kubernetes-sigs/metrics-server']='sigs.k8s.io/metrics-server'
    cases['kubernetes/kubernetes-1-19']='k8s.io/'

for i in "${!cases[@]}"
do
  rm -f "$SRC_ROOT/tests/cases/$i/_output/ATTRIBUTION.txt"
  (cd "$SRC_ROOT/tests/cases/$i" &&  node $SRC_ROOT/generate-attribution-file.js ${cases[$i]} ./ go1.15.6 ./_output)
  (cd "$SRC_ROOT/tests/cases/$i" && diff ./_output/attribution/ATTRIBUTION.txt ATTRIBUTION.txt)
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 -euo pipefail

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

PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$([[ $(uname -m) = "x86_64" ]] && echo 'amd64' || echo 'arm64')
TMP_DIR="${BUILD_DIR}/tmp"
mkdir -p "${TOOLS_DIR}"

HELM_VERSION=v3.7.1
KUBECTL_VERSION=v1.22.6
KIND_VERSION=v0.11.1
RELEASE_BRANCH=1-22
RELEASE=3

## Install kubectl
if ! command -v kubectl &> /dev/null; then
    echo "kubectl could not be found. Downloading..."
    curl -sSL "https://distro.eks.amazonaws.com/kubernetes-${RELEASE_BRANCH}/releases/${RELEASE}/artifacts/kubernetes/${KUBECTL_VERSION}/bin/linux/amd64/kubectl" -o "${TOOLS_DIR}/kubectl"
    chmod +x "${TOOLS_DIR}/kubectl"
fi

## Install kubeval
if ! command -v kubeval &> /dev/null; then
    echo "kubeval could not be found. Downloading..."
    mkdir -p "${TMP_DIR}/kubeval"
    curl -sSL https://github.com/instrumenta/kubeval/releases/latest/download/kubeval-${PLATFORM}-${ARCH}.tar.gz | tar xz -C "${TMP_DIR}/kubeval"
    mv "${TMP_DIR}/kubeval/kubeval" "${TOOLS_DIR}/kubeval"
fi

## Install helm
if ! command -v helm &> /dev/null; then
    echo "helm could not be found. Downloading..."
    mkdir -p "${TMP_DIR}/helm"
    curl -sSL https://get.helm.sh/helm-${HELM_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C "${TMP_DIR}/helm"
    mv "${TMP_DIR}/helm/${PLATFORM}-${ARCH}/helm" "${TOOLS_DIR}/helm"
    rm -rf "${PLATFORM}-${ARCH}"
fi

## Install kind
if ! command -v kind &> /dev/null; then
    echo "kind could not be found. Downloading..."
    curl -sSL "https://github.com/kubernetes-sigs/kind/releases/download/${KIND_VERSION}/kind-${PLATFORM}-${ARCH}" -o "${TOOLS_DIR}/kind"
    chmod +x "${TOOLS_DIR}/kind"
fi

rm -rf ${TMP_DIR}

echo "Tools installed successfully"


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

CHART_BUCKET="prowdataclusterstack-316-prowchartsbucket2e50b8d9-8b0f36hrcee8"
REPO_URL="https://${CHART_BUCKET}.s3.amazonaws.com"

CHART_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
STABLE="${CHART_ROOT}/stable"
BUILD_DIR="${CHART_ROOT}/build"
TOOLS_DIR="${BUILD_DIR}/tools"
export PATH="${TOOLS_DIR}:${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 -euo pipefail

err_report() {
    echo "Exited with error on line $1"
}
trap 'err_report $LINENO' ERR

CHARTS_DIR=$1

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

mkdir -p "${BUILD_DIR}"

if [ -e "${CHARTS_DIR}/Chart.yaml" ]
then
	helm package "${CHARTS_DIR}/" --destination "${BUILD_DIR}/stable"
else
	helm package "${CHARTS_DIR}/"* --destination "${BUILD_DIR}/stable"
fi

set +e # Should have exit code 18
RETURN_CODE="$(curl --write-out '%{http_code}' --silent --output /dev/null -X HEAD ${REPO_URL}/index.yaml)"
CURL_EXIT_CODE=$?
set -e

if [ "$CURL_EXIT_CODE" != "18" ] && [ "$CURL_EXIT_CODE" != "0" ]; then
    echo "Error! Got exit code $CURL_EXIT_CODE from curl"
    exit 1
fi

MERGE_ARG=""
# When initially creating the repo, we need to skip adding the merge argument
if [ "$RETURN_CODE" == "200" ]; then
    MERGE_ARG="--merge index.yaml"
    curl -o index.yaml --silent "${REPO_URL}/index.yaml"
fi
helm repo index $BUILD_DIR/stable --url $REPO_URL $MERGE_ARG
aws s3 cp --recursive --acl public-read ${BUILD_DIR}/stable  "s3://${CHART_BUCKET}"
echo "âœ… Published charts"