#!/bin/bash

IMAGE_NAME=$1
REGISTRY=${2:-"docker.io"}  # 默认使用 docker.io (Docker Hub)，如果指定 registry 则使用指定的
BUILD_CONTEXT=${3:-"."}  # 默认使用当前目录作为构建上下文

if [ -z "$IMAGE_NAME" ]; then
    echo "Error: Image name not provided"
    echo "Usage: buildAndPush.sh imageName [registry] [buildContext]"
    exit 1
fi

echo "Using $IMAGE_NAME as the image name"
echo "Using $REGISTRY as the registry"
echo "Using $BUILD_CONTEXT as the build context"

# Build the Docker image
BUILD_LOG=$(mktemp)
docker build -t $IMAGE_NAME $BUILD_CONTEXT --progress=plain > $BUILD_LOG 2>&1
BUILD_EXIT_CODE=$?

if [ $BUILD_EXIT_CODE -ne 0 ]; then
    echo "Docker build failed with exit code $BUILD_EXIT_CODE"
    echo "Build log:"
    cat $BUILD_LOG
    rm $BUILD_LOG
    exit 1
fi

rm $BUILD_LOG

# Tag the image for the specified registry
if [ "$REGISTRY" != "docker.io" ]; then
    FULL_IMAGE_NAME="$REGISTRY/$IMAGE_NAME"
    docker tag $IMAGE_NAME $FULL_IMAGE_NAME
    if [ $? -ne 0 ]; then
        echo "Docker tagging failed"
        exit 1
    fi
    IMAGE_NAME="$FULL_IMAGE_NAME"
fi

# Push the Docker image
docker push $IMAGE_NAME
if [ $? -ne 0 ]; then
    echo "Docker push failed"
    exit 1
fi

echo "Docker image successfully pushed to $IMAGE_NAME"
