# Check if the Docker image name and second tag are provided as arguments
if [ $# -ne 2 ] && [ $# -ne 3 ]; then
  echo "Usage: $0 <dockerImageName> <secondTag> <containerManagerApiKey> (optional if you want to deploy)"
  exit 1
fi

# Path to your package.json file
PACKAGE_JSON="./package.json"

# Check if the package.json file exists
if [ ! -f "$PACKAGE_JSON" ]; then
  echo "Error: package.json file not found at $PACKAGE_JSON"
  exit 1
fi

# Extract the version from package.json
VERSION=$(jq -r .version "$PACKAGE_JSON")

# Extract the project name from package.json
PROJECT_NAME=$(jq -r .name "$PACKAGE_JSON" | awk -F'/' '{print $2}')

# Check if jq is installed
if ! command -v jq &> /dev/null; then
  echo "Error: 'jq' is not installed. Please install jq to continue."
  exit 1
fi

# Check if the version is empty
if [ -z "$VERSION" ]; then
  echo "Error: Version not found in package.json"
  exit 1
fi

# Get the Docker image name and second tag from the arguments
DOCKER_IMAGE="$1"
SECOND_TAG="$2"
API_KEY="$3"


# Build the Docker image in the current folder
docker build -t "$DOCKER_IMAGE" .

# Tag your Docker container with the extracted version and the second tag
docker tag "$DOCKER_IMAGE" "$DOCKER_IMAGE:$VERSION-$SECOND_TAG"
docker tag "$DOCKER_IMAGE" "$DOCKER_IMAGE:$SECOND_TAG"

# Push the Docker image to Docker Hub
docker push "$DOCKER_IMAGE:$VERSION-$SECOND_TAG"
docker push "$DOCKER_IMAGE:$SECOND_TAG"

echo "Docker container tagged as: $DOCKER_IMAGE:$VERSION-$SECOND_TAG and $DOCKER_IMAGE:$SECOND_TAG"
echo "Docker container pushed to Docker Hub with tags: $DOCKER_IMAGE:$VERSION-$SECOND_TAG and $DOCKER_IMAGE:$SECOND_TAG"

if [ $# -eq 3 ]; then
  # Update the container in the container manager
  curl --location "https://cm.social-selling-cockpit.co/service/$PROJECT_NAME/$VERSION" --header "Authorization: $API_KEY" --header 'Content-Type: application/json' --data "{\"image_url\": \"$DOCKER_IMAGE:$VERSION-$SECOND_TAG\"}"
  echo ""
  echo "Container updated in the container manager"
fi


