# #!/bin/bash

# Load config file
source ./config.env

# Step 1: set branch Name
IMAGE_NAME=$API_IMAGE_NAME
CONTAINER_NAME=$API_CONTAINER_NAME
REPO_DIR="marco.pms.api"

# Navigate into the project directory

if [ -d "$REPO_DIR" ]; then
    cd "$REPO_DIR" || exit
    echo "Changed directory to $REPO_DIR"
else
    echo "Folder '$REPO_DIR' does not exist. Exiting..."
    exit 1
fi


# Step 2: Build the Docker image
echo "Building the Docker image..."
# docker build -t $IMAGE_NAME -f Marco.Pms.Services/Dockerfile .
echo "?? Building Docker image: $IMAGE_NAME"
if ! docker build -t "$IMAGE_NAME" -f Marco.Pms.Services/Dockerfile .; then
    echo "? Docker build failed for image: $IMAGE_NAME"
    exit 1
fi



echo "Image Name:$IMAGE_NAME"
echo "Container Name: $CONTAINER_NAME"


# Step 3: Stop and remove any existing container with the same name

if sudo docker ps -q --filter "name=$CONTAINER_NAME"; then
    echo "Stopping  and removing existing container..."
    sudo docker stop "$CONTAINER_NAME"
    sudo docker rm "$CONTAINER_NAME"
fi


# Step 5: Run the Docker containerer
echo "Running Docker container..."

docker run -d --name $CONTAINER_NAME --network mynetwork -p 8080:8080 -p 8081:8081 $IMAGE_NAME

# Step 6: Final Message
echo "Successfully Running $CONTAINER_NAME"
