#!/bin/sh

# Detect target architecture from environment or system
if [ -n "$TARGET_ARCH" ]; then
    echo "Using target architecture: $TARGET_ARCH"
elif [ "$(uname -m)" = "x86_64" ]; then
    TARGET_ARCH="x86_64"
    echo "Detected x86_64 architecture"
elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then
    TARGET_ARCH="aarch64"
    echo "Detected ARM64 architecture"
else
    TARGET_ARCH="x86_64"  # Default to x86_64 for compatibility
    echo "Defaulting to x86_64 architecture"
fi

# Export TARGET_ARCH for PyInstaller to use
export TARGET_ARCH

# Add platform-specific options
case "$(uname)" in
  "Darwin")
    PLATFORM_OPTS="--osx-bundle-identifier com.osa911.archimmich"
    PLATFORM_DEPS="--debug all"
    ;;
  "Linux")
    PLATFORM_OPTS=""
    PLATFORM_DEPS="--exclude-module PyQt5.Qt5"
    ;;
  *)  # Windows
    PLATFORM_OPTS="--version-file=src/resources/version.rc"
    PLATFORM_DEPS="--collect-all PyQt5 --collect-all requests --collect-binaries _internal"
    ;;
esac

# Use wine on Windows
if [ "$(uname)" != "Darwin" ] && [ "$(uname)" != "Linux" ]; then
  PYINSTALLER="wine python3 -m PyInstaller"
else
  # Try pyinstaller command first, fallback to python module
  if command -v pyinstaller >/dev/null 2>&1; then
    PYINSTALLER="pyinstaller"
  else
    PYINSTALLER="python3 -m PyInstaller"
  fi
fi

# Clean previous builds
rm -rf build dist

echo "Building for architecture: $TARGET_ARCH"
echo "PyInstaller command: $PYINSTALLER"
echo "Platform options: $PLATFORM_OPTS"

$PYINSTALLER \
  --onedir \
  --windowed \
  --optimize "2" \
  --icon="src/resources/favicon-180.png" \
  --add-data "src/resources:src/resources" \
  --add-data "version.txt:." \
  --paths="src" \
  --name "ArchImmich" \
  $PLATFORM_OPTS \
  $PLATFORM_DEPS \
  src/main.py;