#!/bin/bash

# build amd64 and arm64 versions of dropshell, to:
# build/dropshell.amd64
# build/dropshell.arm64

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUTPUT_DIR="$SCRIPT_DIR/output"
DOCKERFILE="$SCRIPT_DIR/Dockerfile.multiarch"

mkdir -p "$OUTPUT_DIR"

# Ensure buildx is available
if ! docker buildx version &>/dev/null; then
    echo "Docker Buildx is required. Please install Docker Buildx." >&2
    exit 1
fi

# Build for x86_64
DOCKER_BUILDKIT=1 docker buildx build --platform linux/amd64 \
    -f "$DOCKERFILE" \
    --output type=local,dest="$OUTPUT_DIR/amd64_tmp" \
    --cache-from type=local,src=/tmp/dropshell-cache \
    --cache-to type=local,dest=/tmp/dropshell-cache,mode=max \
    "$SCRIPT_DIR"

mv "$OUTPUT_DIR/amd64_tmp/dropshell" "$OUTPUT_DIR/dropshell.amd64"
rm -rf "$OUTPUT_DIR/amd64_tmp"

echo "Built output/dropshell.amd64"

# Build for aarch64
DOCKER_BUILDKIT=1 docker buildx build --platform linux/arm64 \
    -f "$DOCKERFILE" \
    --output type=local,dest="$OUTPUT_DIR/arm64_tmp" \
    --cache-from type=local,src=/tmp/dropshell-cache \
    --cache-to type=local,dest=/tmp/dropshell-cache,mode=max \
    "$SCRIPT_DIR"

mv "$OUTPUT_DIR/arm64_tmp/dropshell" "$OUTPUT_DIR/dropshell.arm64"
rm -rf "$OUTPUT_DIR/arm64_tmp"

echo "Built output/dropshell.arm64"

echo "Builds complete:"
ls -lh "$OUTPUT_DIR"/dropshell.*