#!/usr/bin/env bash
# Baut WuerthVPN.app via py2app (Menuebar-Only, kein Dock-Icon via LSUIElement),
# installiert nach ~/Applications, raeumt die Build-Ausgabe weg (sonst doppelt
# im Launchpad) und legt einen LaunchAgent fuer optionalen Autostart bereit.
set -euo pipefail

PY="/Library/Developer/CommandLineTools/usr/bin/python3"
APPS="$HOME/apps"
APP="$HOME/Applications/WuerthVPN.app"
BID="com.wuerth.vpntray"
LSREG=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister

cd "$APPS"

# --- 1. Bauen ---
rm -rf build dist
"$PY" setup.py py2app >/tmp/wuerth_py2app.log 2>&1 || { tail -20 /tmp/wuerth_py2app.log; exit 1; }

# --- 2. Nach ~/Applications uebernehmen ---
pkill -f "WuerthVPN.app/Contents/MacOS/WuerthVPN" 2>/dev/null || true
rm -rf "$APP"
cp -R "$APPS/dist/WuerthVPN.app" "$APP"

# --- 2b. Ausduennen: nur QtCore/Gui/Widgets + Abhaengigkeiten behalten ---
QT="$APP/Contents/Resources/lib/python3.9/PyQt6/Qt6"
KEEP="QtCore QtGui QtWidgets QtDBus QtNetwork QtPrintSupport QtSvg QtSvgWidgets"
for fw in "$QT/lib"/*.framework; do
  name="$(basename "$fw" .framework)"
  echo " $KEEP " | grep -q " $name " || rm -rf "$fw"
done
rm -rf "$QT/qml" "$QT/translations" "$QT/qsci"
if [ -d "$QT/plugins" ]; then
  for d in "$QT/plugins"/*/; do
    case "$(basename "$d")" in
      platforms|styles|imageformats|iconengines) ;;
      *) rm -rf "$d";;
    esac
  done
fi

# uebrige PyQt6-Bindings der entfernten Qt-Module loeschen
PYQT="$APP/Contents/Resources/lib/python3.9/PyQt6"
for m in QtQml QtQuick QtQuick3D QtQuickWidgets QtPdf QtPdfWidgets QtDesigner \
         QtMultimedia QtMultimediaWidgets Qt3DCore QtCharts QtDataVisualization \
         QtSql QtTest QtBluetooth QtPositioning QtSensors QtWebChannel \
         QtWebSockets QtNfc QtSpatialAudio QtShaderTools QtOpenGL QtOpenGLWidgets; do
  find "$PYQT" -maxdepth 1 -name "${m}.*so" -delete 2>/dev/null || true
done

# universale Mach-O auf arm64 thinnen
while IFS= read -r f; do
  archs="$(lipo -archs "$f" 2>/dev/null || true)"
  if [[ "$archs" == *x86_64* && "$archs" == *arm64* ]]; then
    lipo "$f" -thin arm64 -output "$f" 2>/dev/null || true
  fi
done < <(find "$APP" -type f \( -name "*.so" -o -name "*.dylib" -o -perm -u+x \))

# Symbole strippen
find "$APP" -type f \( -name "*.so" -o -name "*.dylib" \) -exec strip -x {} \; 2>/dev/null || true

# Bundle-Siegel nach allen Aenderungen erneuern (sonst -10669/Gatekeeper)
codesign --force --deep -s - "$APP" >/dev/null 2>&1

# --- 3. Build-Ausgabe entfernen (sonst zweite App im Launchpad) ---
"$LSREG" -u "$APPS/dist/WuerthVPN.app" 2>/dev/null || true
rm -rf build dist

# --- 4. App registrieren ---
"$LSREG" -f "$APP"

# --- 5. LaunchAgent fuer Autostart bereitlegen (nicht automatisch geladen) ---
LA="$HOME/Library/LaunchAgents/$BID.plist"
mkdir -p "$HOME/Library/LaunchAgents"
cat >"$LA" <<AGENT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$BID</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/open</string>
    <string>-a</string>
    <string>$APP</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><false/>
</dict>
</plist>
AGENT

echo "Fertig: $APP"
echo "Autostart aktivieren:    launchctl load $LA"
echo "Autostart deaktivieren:  launchctl unload $LA"
