#!/bin/bash

# Exit on error and catch pipeline errors
set -eo pipefail

# Source Jabba for Java version management
source /home/anon/.jabba/jabba.sh

# Set Java version with Jabba
jabba use 21.0.2

# Variables for Docker image
IMAGE_NAME="nise-backend"
IMAGE_REGISTRY="git.nise.moe/nuff"
IMAGE_VERSION="latest"

# Clean up previous build artifacts
rm -rf target/

# Clean and build the Maven project
echo "Building main project..."
mvn clean package || { echo "Maven build failed"; exit 1; }

# Build Docker image
echo "Building Docker image..."
docker build . -t "$IMAGE_NAME:$IMAGE_VERSION" || { echo "Docker build failed"; exit 1; }

# Tag and push Docker image
docker tag "$IMAGE_NAME:$IMAGE_VERSION" "$IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION"
docker push "$IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION" || { echo "Error: Failed to push $IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION"; exit 1; }

echo "Docker image pushed successfully to $IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION"