#!/usr/bin/env bash
set -e
BASE="$(pwd)"
APPDIR="$BASE/QET-Tools.AppDir"

# clean
rm -rf "$APPDIR"

# create structure
mkdir -p \
  "$APPDIR/usr/lib/QET-Tools" \
  "$APPDIR/usr/share/applications" \
  "$APPDIR/usr/share/icons/hicolor/256x256/apps" \
  "$APPDIR/usr/bin"

# copy code (keine Doppelungen)
cp GUI.py Kabelliste_csv.py Kabelliste_qet.py Klemmen.py Klemmplan_csv.py \
   Klemmenplan_qet.py Adern.py QET-Tools.spec Seiten_loeschen.py Nummerierung.py "$APPDIR/usr/lib/QET-Tools/"

# statt venv kopieren: venv neu erzeugen INSIDE AppDir (relocatable)
python3 -m venv "$APPDIR/usr/lib/QET-Tools/venv"
# Falls du requirements hast, installiere sie (falls nicht, entferne die Zeile)
# "$APPDIR/usr/lib/QET-Tools/venv/bin/pip" install -r requirements.txt

# icon
cp qet-tools.png "$APPDIR/usr/share/icons/hicolor/256x256/apps/qet-tools.png"
cp qet-tools.png "$APPDIR/qet-tools.png"

# AppRun
cat > "$APPDIR/AppRun" << 'EOF'
#!/bin/bash
HERE="$(dirname "$(readlink -f "$0")")"
export VIRTUAL_ENV="$HERE/usr/lib/QET-Tools/venv"
export PATH="$VIRTUAL_ENV/bin:$PATH"
exec python3 "$HERE/usr/lib/QET-Tools/GUI.py" "$@"
EOF
chmod +x "$APPDIR/AppRun"

# launcher symlink
ln -sf ../../AppRun "$APPDIR/usr/bin/qet-tools"
chmod +x "$APPDIR/usr/bin/qet-tools"

# desktop entry
cat > "$APPDIR/usr/share/applications/qet-tools.desktop" << 'EOF'
[Desktop Entry]
Type=Application
Name=QET Tools
Comment=QElectrotech Zusatzfunktionen GUI
Exec=qet-tools %U
Icon=qet-tools
Categories=Utility;
Terminal=false
EOF

cp "$APPDIR/usr/share/applications/qet-tools.desktop" "$APPDIR/"

# make appimagetool executable (falls nötig)
chmod +x "$BASE/appimagetool-x86_64.AppImage"

# build AppImage — ARCH setzen, damit appimagetool nicht raten muss
ARCH=x86_64 "$BASE/appimagetool-x86_64.AppImage" "$APPDIR" "$BASE/QET-Tools-x86_64.AppImage"
