#!/bin/bash

# Load config file
source ./config.env


# Set the name for the Docker image and container
IMAGE_NAME=$WEB_IMAGE_NAME
CONTAINER_NAME=$WEB_CONTAINER_NAME
REPO_DIR="marco.pms.web"
VITE_API_URL=$API_URL


# Navigate into the cloned 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

#cd marco.pms.web || exit

# Step 2: Install dependencies
echo "------------ Installing dependencies using npm..."
npm install

# Step 3: Build the Client app
echo "------------ Building the React app..."
npm run build


# Step 4: Delete Existing Container
if sudo docker ps -q --filter "name=$CONTAINER_NAME"; then
    echo "------------ Stopping existing container..."
    sudo docker stop "$CONTAINER_NAME"
    sudo docker rm "$CONTAINER_NAME"
else
    echo "------------ No existing container found for: $CONTAINER_NAME"
fi


# Step 5: Delete Existing Image
# Check if the image exists
if docker images | awk '{print $1}' | grep -q "^$IMAGE_NAME"; then
    echo "------------ Deleting existing Docker image: $IMAGE_NAMEE"
    docker rmi -f $IMAGE_NAME
else
    echo "------------ No existing image found for: $IMAGE_NAME"
fi


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


# Step 6: Build New Client Image

echo "------------ Building Docker image..."
sudo docker build -t "$IMAGE_NAME" .

# Go to outer directory
cd ../ 

# Step 7: Run the Docker containerer
echo "------------ Running Docker container..."
docker run -d --name "$CONTAINER_NAME" -p 4175:4173 \
	 -e VITE_API_URL="$VITE_API_URL"  "$IMAGE_NAME"


# Final message
echo "------------ Successfully Running $CONTAINER_NAME"
