#!/usr/bin/env bash
set -e

APP_DIR="$(cd "$(dirname "$0")" && pwd)"
EXEC="python3 $APP_DIR/main.py"
ICON_DIR="$HOME/.local/share/icons"
DESKTOP_DIR="$HOME/.local/share/applications"
ICON_PATH="$ICON_DIR/gizerbridge.png"
DESKTOP_FILE="$DESKTOP_DIR/gizerbridge.desktop"

export APP_DIR ICON_PATH

echo "=== GizerBridge – Installation ==="
echo ""

# ── Python dependencies ────────────────────────────────────────────────────
echo "[1/5] Installiere Python-Abhängigkeiten..."
pip install -r "$APP_DIR/requirements.txt" --user --quiet
echo "      Fertig."

# ── App icon ───────────────────────────────────────────────────────────────
echo "[2/5] Kopiere App-Icon..."
mkdir -p "$ICON_DIR"
cp "$APP_DIR/icon.png" "$ICON_PATH"
echo "      Icon gespeichert: $ICON_PATH"

# ── .desktop file ──────────────────────────────────────────────────────────
echo "[3/5] Erstelle Desktop-Eintrag..."
mkdir -p "$DESKTOP_DIR"
cat > "$DESKTOP_FILE" <<DESKTOP
[Desktop Entry]
Name=GizerBridge
Comment=Sierra Chart → Tralgo Analytics
Exec=$EXEC
Icon=gizerbridge
Terminal=false
Type=Application
Categories=Office;Finance;
StartupNotify=false
DESKTOP
chmod +x "$DESKTOP_FILE"
echo "      Gespeichert: $DESKTOP_FILE"

# ── Remove old desktop entries ─────────────────────────────────────────────
echo "[4/5] Entferne alte Desktop-Einträge..."
rm -f "$DESKTOP_DIR"/*tralgo*.desktop "$DESKTOP_DIR"/*analytics*.desktop 2>/dev/null || true
echo "      Fertig."

# ── Update desktop database ────────────────────────────────────────────────
echo "[5/5] Aktualisiere App-Datenbank..."
if command -v update-desktop-database &>/dev/null; then
    update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true
fi
if command -v gtk-update-icon-cache &>/dev/null; then
    gtk-update-icon-cache -f "$ICON_DIR" 2>/dev/null || true
fi

echo ""
echo "✓ GizerBridge wurde installiert."
echo "  Suche ihn im App-Menü unter 'GizerBridge'."
echo "  Oder direkt starten: python3 $APP_DIR/main.py"
