#!/bin/bash

configuration="Release"
baseOutputPath="./artifacts"

# Detect platform
if [[ "$OSTYPE" == "darwin"* ]]; then
    currentPlatform="osx-x64"
else
    currentPlatform="linux-x64"
fi

echo "Building for current platform: $currentPlatform"

# Create output directories
exeOutputPath="$baseOutputPath/exe"
nativeOutputPath="$baseOutputPath/native"
mkdir -p "$exeOutputPath"
mkdir -p "$nativeOutputPath"

# Build executable
echo "Building executable..."
dotnet publish \
    -c $configuration \
    -r $currentPlatform \
    --self-contained true \
    -p:PublishDir=$exeOutputPath

if [ $? -ne 0 ]; then
    echo "Executable build failed. Check the error messages above."
    exit 1
fi

# Build native shared library
echo "Building native shared library..."
dotnet publish \
    -c $configuration \
    -r $currentPlatform \
    --self-contained true \
    -p:BuildType=lib \
    -p:PublishDir=$nativeOutputPath

if [ $? -ne 0 ]; then
    echo "Library build failed. Check the error messages above."
    exit 1
fi

# Rename the native library to the expected name
dllPath="$nativeOutputPath/FireflyClient.so"
libDllPath="$nativeOutputPath/libFireflyClient.so"
if [ -f "$dllPath" ]; then
    echo "Renaming native library to libFireflyClient.so..."
    mv "$dllPath" "$libDllPath"
fi

echo "Build complete. Outputs available at:"
echo "Executable: $exeOutputPath"
echo "Native library: $nativeOutputPath"

# Make the outputs executable
if [[ "$currentPlatform" == "linux-x64" ]]; then
    chmod +x "$exeOutputPath/FireflyClient"
    if [ -f "$libDllPath" ]; then
        chmod +x "$libDllPath"
    else
        echo "Warning: Native library not found at $libDllPath"
    fi
elif [[ "$currentPlatform" == "osx-x64" ]]; then
    chmod +x "$exeOutputPath/FireflyClient"
    chmod +x "$nativeOutputPath/libFireflyClient.dylib"
fi 