#!/bin/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. A copy of
# the License is located at
#
# 	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

# Run a local registry on the 'well known' port 51670 if it is not running.
# Also push images we will need to it.
set -ex

REGISTRY_IMAGE="public.ecr.aws/docker/library/registry:2.7.1"

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

# Starts a registry container
start_registry() {
    local REGISTRY_CONTAINER_NAME=$1
    local HOST_ADDRESS=$2
    local HOST_HTPASSWD_PATH=$3 # Optional

    echo "Removing $REGISTRY_CONTAINER_NAME"
    # stop and remove the registry container. The script will not exit if the container is not running
    docker stop "$REGISTRY_CONTAINER_NAME" || true && docker rm "$REGISTRY_CONTAINER_NAME" || true

    echo "Running $REGISTRY_CONTAINER_NAME"
    if [ -z "$HOST_HTPASSWD_PATH" ]; then
        docker run -d --name="$REGISTRY_CONTAINER_NAME" \
            -e SETTINGS_FLAVOR=local \
            -p "${HOST_ADDRESS}:5000" "${REGISTRY_IMAGE}"
    else
        local HOST_HTPASSWD_DIR HTPASSWD_FILENAME
        HOST_HTPASSWD_DIR=$(dirname "$HOST_HTPASSWD_PATH")
        HTPASSWD_FILENAME=$(basename "$HOST_HTPASSWD_PATH")
        docker run -d --name="$REGISTRY_CONTAINER_NAME" \
            -e SETTINGS_FLAVOR=local \
            -e REGISTRY_AUTH_HTPASSWD_REALM=basic-realm \
            -e REGISTRY_AUTH_HTPASSWD_PATH="/agent-integ-htpasswd/${HTPASSWD_FILENAME}" \
            -v "${HOST_HTPASSWD_DIR}:/agent-integ-htpasswd" \
            -p "${HOST_ADDRESS}:5000" "${REGISTRY_IMAGE}"
    fi

    # give the registry some seconds to get ready for pushes
    sleep 7

}

mirror_local_image() {
  echo "Mirroring $1"
  docker tag "$1" "$2"
  docker push "$2"
  docker rmi "$2"
}

# Pull busybox image for later use
docker pull public.ecr.aws/docker/library/busybox:1.34.1

# --- Start public registry ---
REGISTRY_CONTAINER_NAME="test-ecs-registry"
HOST_ADDRESS="127.0.0.1:51670"
start_registry $REGISTRY_CONTAINER_NAME $HOST_ADDRESS 

for image in "amazon/amazon-ecs-netkitten" "amazon/amazon-ecs-volumes-test" \
				"amazon/image-cleanup-test-image1" "amazon/image-cleanup-test-image2" \
				"amazon/image-cleanup-test-image3" "amazon/amazon-ecs-exec-command-agent-test"; do
    mirror_local_image "${image}:make" "${HOST_ADDRESS}/${image}:latest"
done

if [[ "$(uname -m)" == "x86_64" ]]; then
    mirror_local_image "amazon/fluentd:make" "${HOST_ADDRESS}/amazon/fluentd:latest"
fi

# Remove the tag so this image can be deleted successfully in the docker image cleanup integ tests
docker rmi amazon/image-cleanup-test-image1:make amazon/image-cleanup-test-image2:make amazon/image-cleanup-test-image3:make

# Add a busybox image to the registry
mirror_local_image public.ecr.aws/docker/library/busybox:1.34.1 "${HOST_ADDRESS}/busybox:latest"

# --- Start private registry ---

# Set up an htpasswd file containing test auth credentials for the registry
# Username is 'username' and password is 'password'
# The password is hashed with bcrypt
HOST_HTPASSWD_PATH="/tmp/private-test-registry-htpasswd/htpasswd"
mkdir -p "$(dirname "$HOST_HTPASSWD_PATH")"
# shellcheck disable=SC2016
echo 'username:$2y$10$agMyRiMiqDWu.W6RpS3LS.qowb3wwee5BSkonzVp.sx1phbAK.H1a' > "$HOST_HTPASSWD_PATH"

REGISTRY_CONTAINER_NAME="test-ecs-registry-private"
HOST_ADDRESS="127.0.0.1:51671"
start_registry $REGISTRY_CONTAINER_NAME $HOST_ADDRESS $HOST_HTPASSWD_PATH

# Upload images
echo "password" | docker login -u username --password-stdin "$HOST_ADDRESS"
mirror_local_image public.ecr.aws/docker/library/busybox:1.34.1 "${HOST_ADDRESS}/busybox:latest"

# create a context folder used by docker build. It will only have a file
# full of random bits so that the parallel pull images are different.
mkdir -p docker-context
cat << EOF > docker-context/Dockerfile
FROM amazon/amazon-ecs-pause:0.1.0
ADD random-bits /random-bits
EOF

# cleanup the context
rm -rf docker-context
