#!/bin/bash

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"

cd "$SCRIPT_DIR" || exit 1

# Clean up old test data and any existing binaries
# Force removal with chmod to handle permission issues
if [ -d dehydrate_test_data ]; then
    chmod -R u+w dehydrate_test_data 2>/dev/null || true
    rm -rf dehydrate_test_data
fi
rm -f dehydrate_test

# Build the test program using Docker
# The Docker container supports both amd64 and arm64 architectures
echo "Building dehydrate test executable..."

# Use docker cp approach since volume mounting may not work in CI
CONTAINER_NAME="dehydrate-test-build-$$"

# Start container in detached mode
docker run -d --name "$CONTAINER_NAME" \
    gitea.jde.nz/public/dropshell-build-base:latest \
    sleep 60

# Copy source file into container
docker cp dehydrate_test.cpp "$CONTAINER_NAME":/dehydrate_test.cpp

# Compile in container
docker exec "$CONTAINER_NAME" bash -c "
    echo 'Compiling dehydrate test...'
    if ! g++ -std=c++23 -static /dehydrate_test.cpp -o /dehydrate_test; then
        echo 'ERROR: Compilation failed'
        exit 1
    fi
    
    # Verify binary was created
    if [ ! -f /dehydrate_test ]; then
        echo 'ERROR: Binary was not created'
        exit 1
    fi
    
    # Quick architecture check
    if ! file /dehydrate_test | grep -q 'executable'; then
        echo 'ERROR: Generated file is not an executable'
        file /dehydrate_test
        exit 1
    fi
    
    echo 'Compilation successful'
"

# Copy binary back to host
docker cp "$CONTAINER_NAME":/dehydrate_test ./dehydrate_test

# Clean up container
docker rm -f "$CONTAINER_NAME"

# Check if compilation succeeded
if [ ! -f "./dehydrate_test" ]; then
    echo "Error: Failed to compile dehydrate_test - binary not found"
    echo "Files in current directory:"
    ls -la
    exit 1
fi

# Fix ownership of the binary (created by Docker as root)
if [ "$(stat -c %u ./dehydrate_test)" != "$(id -u)" ]; then
    # Use Docker to change ownership to current user
    docker run --rm -v "$PROJECT_DIR":/workdir -w /workdir/test \
        gitea.jde.nz/public/dropshell-build-base:latest \
        chown "$(id -u):$(id -g)" dehydrate_test
fi

# Run the test
./dehydrate_test