#!/bin/bash

# --- Configuration ---
IMAGE_NAME="workit"
TAG="latest"
OUTPUT_FILE="workit-amd64.tar"
TARGET_PLATFORM="linux/amd64"
BUILD_DIR="public_build"

# --- Script Start ---
echo "--- Preparing build directory ---"
# Clean up previous build directory if it exists
rm -rf ${BUILD_DIR}
# Create a temporary build directory to avoid modifying source files
cp -r public ${BUILD_DIR}

# Step 1: Run the Node.js script to inline audio files.
# This modifies the app.js inside the temporary BUILD_DIR.
echo ""
node scripts/inline-audio.js

# Check if the node script was successful.
if [ $? -ne 0 ]; then
    echo "!!! Audio inlining failed. Aborting build."
    rm -rf ${BUILD_DIR} # Clean up
    exit 1
fi

echo ""
echo "--- Starting Docker image build for ${TARGET_PLATFORM} ---"

# Step 2: Build the multi-platform image using the modified files.
docker buildx build --platform ${TARGET_PLATFORM} -t ${IMAGE_NAME}:${TAG} --load .

# Check if the build command was successful.
if [ $? -ne 0 ]; then
    echo "!!! Docker build failed. Aborting script."
    rm -rf ${BUILD_DIR} # Clean up
    exit 1
fi

# Step 3: Clean up the temporary build directory.
echo ""
echo "--- Cleaning up build directory ---"
rm -rf ${BUILD_DIR}

echo ""
echo "--- Build successful. Saving image to ${OUTPUT_FILE} ---"

# Step 4: Save the newly created image to a .tar archive.
docker save -o ${OUTPUT_FILE} ${IMAGE_NAME}:${TAG}

if [ $? -ne 0 ]; then
    echo "!!! Failed to save Docker image. Aborting script."
    exit 1
fi

echo ""
echo "✅ Done!"
echo "Image has been saved to: ${OUTPUT_FILE}"
