#!/bin/bash
# Sabre Desktop Linux Installer & Auto-Updater Script v1.0.6

set -e

echo "=========================================================="
echo "🚀 Sabre Desktop Linux Installer & Dependency Setup v1.0.6"
echo "=========================================================="

# 1. Install System Dependencies if missing
if command -v apt-get &> /dev/null; then
    echo "📦 Checking and installing system packages (apt)..."
    sudo apt-get update -qq || true
    sudo apt-get install -y -qq python3 python3-pip python3-pyqt6 libxcb-cursor0 libxcb-xinerama0 libgl1 || true
fi

# 2. Ensure Python package dependencies are satisfied
echo "🐍 Verifying Python dependencies..."
python3 -m pip install --upgrade fdb requests urllib3 PyQt6 --break-system-packages 2>/dev/null || true

# 3. Target Installation Directory
INSTALL_DIR="$HOME/.local/share/SabreDesktop"
mkdir -p "$INSTALL_DIR"

echo "📂 Installing Sabre Desktop files into $INSTALL_DIR..."
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
if [ -d "$SCRIPT_DIR/SabreDesktop" ]; then
    cp -r "$SCRIPT_DIR/SabreDesktop/"* "$INSTALL_DIR/"
else
    cp -r "$SCRIPT_DIR/"* "$INSTALL_DIR/" 2>/dev/null || true
fi

# 4. Create Desktop & Launcher Shortcut
DESKTOP_FILE="$HOME/.local/share/applications/sabre-desktop.desktop"
mkdir -p "$HOME/.local/share/applications"

cat <<EOF > "$DESKTOP_FILE"
[Desktop Entry]
Version=1.0.6
Type=Application
Name=Sabre Desktop
Comment=Sabre Time & Attendance Management Platform
Exec=$INSTALL_DIR/SabreDesktop
Icon=$INSTALL_DIR/resources/sabre-logo.png
Terminal=false
Categories=Office;Business;
EOF

chmod +x "$DESKTOP_FILE"
chmod +x "$INSTALL_DIR/SabreDesktop" 2>/dev/null || true

echo "✅ Sabre Desktop Linux v1.0.6 installation completed successfully!"
echo "📍 Application installed to: $INSTALL_DIR"
echo "🖥️ Shortcut created in Applications menu."
