#!/bin/bash

# Specify the image name and tag
IMAGE_NAME="myp-rp"
IMAGE_TAG="latest"

# Create a new builder instance with a sensible name
BUILDER_NAME="myp-rp-arm64-builder"
echo "Creating a new builder instance named $BUILDER_NAME..."
docker buildx create --name $BUILDER_NAME --use

# Build the Docker image from Dockerfile for arm64
echo "Building Docker image from Dockerfile for arm64..."
docker buildx build --platform linux/arm64 -t ${IMAGE_NAME}:${IMAGE_TAG} -f $PWD/Dockerfile $PWD --output type=docker,dest=docker/${IMAGE_NAME}_${IMAGE_TAG}.tar

# Check if the build was successful
if [ $? -ne 0 ]; then
    echo "Error occurred while building the Docker image"
    docker buildx rm $BUILDER_NAME
    exit 1
fi

echo "Docker image built successfully"

# Compress the tar file using xz
COMPRESSED_FILE="docker/${IMAGE_NAME}_${IMAGE_TAG}.tar.xz"
echo "Compressing the image to $COMPRESSED_FILE..."

# Check if the compressed file exists and remove it
if [ -f "$COMPRESSED_FILE" ]; then
    echo "Removing existing compressed file $COMPRESSED_FILE..."
    rm "$COMPRESSED_FILE"
fi

# Proceed with compression
xz -z docker/${IMAGE_NAME}_${IMAGE_TAG}.tar

# Check if the compression was successful
if [ $? -ne 0 ]; then
    echo "Error occurred while compressing the Docker image"
    docker buildx rm $BUILDER_NAME
    exit 1
fi

echo "Docker image compressed successfully as docker/${IMAGE_NAME}_${IMAGE_TAG}.tar.xz"

# Remove the builder instance
docker buildx rm $BUILDER_NAME

echo "Build process completed"