#!/bin/bash
#
# Copyright 2025 PingCAP, Inc.
#
# 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

CURRENT_DIR="$(dirname "$0")"
cd ${CURRENT_DIR}

# Allow us to Ctrl+C outside CI
USE_TTY=""
test -t 1 && USE_TTY="-it"

# Don't use a new ID, to make sure previous build can be cleaned up.
IMAGE_ID=clusterintegrationtest:latest

function build_new_image() {
  DOCKERFILE_NAME=${1:-Dockerfile}
  echo "+ Building TiDB server with current source..."
  pushd ../.. > /dev/null
  export TIDB_BUILD_TIME="2024-01-01 00:00:00" # Use a fixed build time to keep cache valid
  make server
  popd > /dev/null

  # Make an image with TiDB+TiKV+TiFlash
  cp ../../bin/tidb-server ./tidb-server
  echo "+ Building container with other components..."
  docker build --pull --rm -t $IMAGE_ID -f $DOCKERFILE_NAME .
  echo
  echo "+ Clean up previous builds..."
  docker builder prune --force
}

function run_in_container() {
  docker run -v clusterintegrationtest_tiup_cache:/root/.tiup/components --rm $USE_TTY $IMAGE_ID /bin/bash -c $1
}

function run_in_container_with_port_forward() {
  docker run -v clusterintegrationtest_tiup_cache:/root/.tiup/components --rm $USE_TTY -p 4000:4000 $IMAGE_ID /bin/bash -c $1
}