#!/bin/bash
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#

set -e

if [[ $# -lt 1 ]]; then
  echo "Usage: "
  echo "    ci-action <action> [args...]"
  echo "      OR"
  echo "    ci-action --shell"
  echo
  echo "Runs the given action (or opens a shell) in the build Docker container."
  echo "The build image must already be acquired with 'acquire-build-image' before this is run."
  echo "The <action> is the name of a script in 'tools/ci-scripts', and the [args...] will be forwarded to it."
  exit 1
fi

ACTION_NAME="$1"
shift
ACTION_ARGS=("$@")

if [[ ! -d smithy-rs ]]; then
  echo "A fresh copy of smithy-rs must be checked out from the path this script is executed from."
  exit 1
fi

START_PATH="$(realpath "$(pwd)")"
SCRIPT_PATH="$(realpath "$(dirname "$0")")"
ACTION_PATH="$("${SCRIPT_PATH}"/ci-create-workspace)"
cd "${SCRIPT_PATH}"

function cleanup {
    docker compose -f build.docker-compose.yml down
    cd "${START_PATH}"
    mv "${ACTION_PATH}/workspace/artifacts" .
    if [[ -d "${ACTION_PATH}/workspace/smithy-rs/target" ]]; then
        mv "${ACTION_PATH}/workspace/smithy-rs/target" ./smithy-rs-target
    else
        mkdir -p ./smithy-rs-target
    fi
    rm -rf "${ACTION_PATH}"
}
trap cleanup EXIT

cd "${ACTION_PATH}"
USER_ID="$(id -u)"
GROUP_ID="$(id -g)"
export USER_ID
export GROUP_ID
export GRADLE_CACHE_PATH="${START_PATH}/gradle"
docker compose -f build.docker-compose.yml up -d
if [[ "${ACTION_NAME}" == "--shell" ]]; then
    docker compose -f build.docker-compose.yml exec smithy-rs-build /bin/bash
else
    docker compose -f build.docker-compose.yml exec -T smithy-rs-build bash -c "cd workspace; ./ci-scripts/${ACTION_NAME} ${ACTION_ARGS[*]}"
fi
exit $?
