#!/bin/bash
# Script to build and push Docker images to the private registry at docker.d-popov.com
# Usage: ./build-and-push.sh [version]

set -e

# Configuration
REGISTRY="docker.d-popov.com"
IMAGE_NAME="jwpw"
DOCKERFILE="_deploy/prod.Dockerfile"
VERSION="${1:-latest}"  # Use first argument as version or default to 'latest'

# Display build information
echo "====================================================="
echo "Building ${REGISTRY}/${IMAGE_NAME}:${VERSION}"
echo "Using Dockerfile: ${DOCKERFILE}"
echo "====================================================="

# Check if Docker is available
if ! command -v docker &> /dev/null; then
    echo "Error: Docker is not installed or not in the PATH"
    exit 1
fi

# Check if user is logged in to the registry
if ! docker info | grep -q "Registry: ${REGISTRY}"; then
    echo "You need to log in to the registry first:"
    echo "docker login ${REGISTRY}"
    exit 1
fi

# Build the Docker image
echo "Building Docker image..."
docker build -t "${REGISTRY}/${IMAGE_NAME}:${VERSION}" -f "${DOCKERFILE}" .

# Tag as latest if version is not 'latest'
if [ "${VERSION}" != "latest" ]; then
    echo "Tagging also as latest..."
    docker tag "${REGISTRY}/${IMAGE_NAME}:${VERSION}" "${REGISTRY}/${IMAGE_NAME}:latest"
fi

# Push the image to the registry
echo "Pushing Docker image ${REGISTRY}/${IMAGE_NAME}:${VERSION} to registry..."
docker push "${REGISTRY}/${IMAGE_NAME}:${VERSION}"

# Push latest tag if version is not 'latest'
if [ "${VERSION}" != "latest" ]; then
    echo "Pushing Docker image ${REGISTRY}/${IMAGE_NAME}:latest to registry..."
    docker push "${REGISTRY}/${IMAGE_NAME}:latest"
fi

echo "====================================================="
echo "Build and push completed successfully!"
echo "Image: ${REGISTRY}/${IMAGE_NAME}:${VERSION}"
if [ "${VERSION}" != "latest" ]; then
    echo "Image: ${REGISTRY}/${IMAGE_NAME}:latest"
fi
echo "=====================================================" 