# Docker context should be the parent of PeerDrop, ipfs-lite, and py-libp2p
# Run from /Users/sumanjeet/code/:
#   docker build -f PeerDrop/packaging/Dockerfile.linux -t peerdrop-linux-builder .
#
# Or from PeerDrop/:
#   bash packaging/docker-build-linux.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CODE_ROOT="$(cd "$PROJECT_ROOT/.." && pwd)"

# Ensure the Docker context excludes heavy local artifacts (venvs, .git, prior
# dists, caches) — otherwise every build ships gigabytes of context.
DOCKERIGNORE="$CODE_ROOT/.dockerignore"
if [ ! -f "$DOCKERIGNORE" ]; then
  echo "=== Generating $DOCKERIGNORE ==="
  cat > "$DOCKERIGNORE" <<'EOF'
# Docker build context for PeerDrop packaging — keep context tiny.
**/.git
**/.venv
**/__pycache__
**/.pytest_cache
**/.mypy_cache
**/.ruff_cache
**/*.pyc
**/*.log
**/.benchmarks
PeerDrop/dist
PeerDrop/dist-linux-x64
PeerDrop/build
PeerDrop/android/.gradle
PeerDrop/android-wheels
EOF
fi

echo "=== Building Linux executables via Docker ==="
echo "Project: $PROJECT_ROOT"
echo "Context: $CODE_ROOT"

docker build \
    --platform linux/amd64 \
    -f "$SCRIPT_DIR/Dockerfile.linux" \
    -t peerdrop-linux-builder-x64 \
    "$CODE_ROOT"

# Extract build output
mkdir -p "$PROJECT_ROOT/dist-linux-x64"
CONTAINER_ID=$(docker create peerdrop-linux-builder-x64)
docker cp "$CONTAINER_ID:/app/peerdrop-project/dist/" "$PROJECT_ROOT/dist-linux-x64/"
docker rm "$CONTAINER_ID"

# Package the artifacts for distribution
echo ""
echo "=== Zipping artifacts ==="
cd "$PROJECT_ROOT/dist-linux-x64"
rm -f dist.zip
zip -rq dist.zip dist/
cd "$PROJECT_ROOT"

echo ""
echo "=== Linux x86_64 build complete ==="
echo "Output: dist-linux-x64/"
ls -lh "$PROJECT_ROOT/dist-linux-x64/"
du -sh "$PROJECT_ROOT/dist-linux-x64/dist/"
