# This script uses a pre-built docker container to build two executables:
# 1. dropshell-x86_64, using musl and static linking
# 2. dropshell-arm64, using musl and static linking

# The executables are copied to ./output, with the ownership changed to current user.

#!/bin/bash
set -e

# Get current user's UID and GID
USER_ID=$(id -u)
GROUP_ID=$(id -g)

# Create output directory if it doesn't exist
mkdir -p output

# Build Docker image if it doesn't exist
if ! docker image inspect dropshell-builder:latest >/dev/null 2>&1; then
    echo "Building builder image..."
    docker build -t dropshell-builder:latest .
fi

# Build x86_64 executable
docker run --rm -v "$(pwd)/..:/src" -u root dropshell-builder:latest bash -c '
    rm -rf build && \
    mkdir -p build && \
    cd build && \
    cmake -DCMAKE_BUILD_TYPE=Release .. && \
    make && \
    cp dropshell ../packages/output/dropshell-x86_64 && \
    chown '"$USER_ID:$GROUP_ID"' ../packages/output/dropshell-x86_64 && \
    rm -rf build
'

# Build arm64 executable
docker run --rm -v "$(pwd)/..:/src" -u root dropshell-builder:latest bash -c '
    rm -rf build && \
    mkdir -p build && \
    cd build && \
    cmake -DCMAKE_CXX_COMPILER=aarch64-linux-gnu-g++ \
          -DCMAKE_BUILD_TYPE=Release .. && \
    make && \
    cp dropshell ../packages/output/dropshell-arm64 && \
    chown '"$USER_ID:$GROUP_ID"' ../packages/output/dropshell-arm64 && \
    rm -rf build
'