#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
BUILD_DIR="$SCRIPT_DIR/build"

HOST_ARCH="$(uname -m)"
REQUESTED_ARCH="${ARCH:-}"

if [ -n "$REQUESTED_ARCH" ]; then
    case "$REQUESTED_ARCH" in
        arm64|aarch64)
            PLATFORM="linux/arm64"
            OUTPUT_ARCH="arm64"
            ;;
        amd64|x86_64)
            PLATFORM="linux/amd64"
            OUTPUT_ARCH="x86_64"
            ;;
        *)
            echo "ERROR: Unsupported ARCH='$REQUESTED_ARCH' (supported: arm64, amd64)"
            exit 1
            ;;
    esac
else
    case "$HOST_ARCH" in
        x86_64)
            PLATFORM="linux/amd64"
            OUTPUT_ARCH="x86_64"
            ;;
        aarch64|arm64)
            PLATFORM="linux/arm64"
            OUTPUT_ARCH="arm64"
            ;;
        *)
            echo "WARNING: Unknown host architecture '$HOST_ARCH', defaulting to linux/amd64"
            PLATFORM="linux/amd64"
            OUTPUT_ARCH="$HOST_ARCH"
            ;;
    esac
fi

OUTPUT_NAME="nostr-id-tui_static_${OUTPUT_ARCH}"
BASE_IMAGE_TAG="n-os-tr/alpine-musl-base:3.19"
APP_IMAGE_TAG="n-os-tr/nostr-id-tui-musl-builder:latest"

mkdir -p "$BUILD_DIR"

echo "=========================================="
echo "n-OS-tr nostr-id-tui static build"
echo "=========================================="
echo "Repo root:  $REPO_ROOT"
echo "Platform:   $PLATFORM"
echo "Output:     $BUILD_DIR/$OUTPUT_NAME"
echo ""

echo "[1/3] Building shared base image ($BASE_IMAGE_TAG)"
docker build \
    --platform "$PLATFORM" \
    -f "$REPO_ROOT/stack/build-common/Dockerfile.alpine-musl" \
    -t "$BASE_IMAGE_TAG" \
    "$REPO_ROOT/stack/build-common"

echo "[2/3] Building nostr-id-tui musl image ($APP_IMAGE_TAG)"
docker build \
    --platform "$PLATFORM" \
    -f "$SCRIPT_DIR/Dockerfile.alpine-musl" \
    -t "$APP_IMAGE_TAG" \
    "$REPO_ROOT"

echo "[3/3] Extracting binary"
CONTAINER_ID="$(docker create "$APP_IMAGE_TAG" /nostr-id-tui)"
trap 'docker rm -f "$CONTAINER_ID" >/dev/null 2>&1 || true' EXIT

docker cp "$CONTAINER_ID:/nostr-id-tui" "$BUILD_DIR/$OUTPUT_NAME"
chmod +x "$BUILD_DIR/$OUTPUT_NAME"

file "$BUILD_DIR/$OUTPUT_NAME"
if LDD_OUT="$(ldd "$BUILD_DIR/$OUTPUT_NAME" 2>&1 || true)"; then
    echo "$LDD_OUT"
fi

echo "Built: $BUILD_DIR/$OUTPUT_NAME"
echo "Size:  $(stat -c '%s bytes' "$BUILD_DIR/$OUTPUT_NAME")"
