#!/bin/bash
# RDP Launcher - Startet RDP-Verbindungen aus Profilen
# Speichere als: files/rdp-launcher.sh

CONFIG_FILE="$HOME/.config/rdp-profiles/profiles.ini"
PROFILE_NAME="$1"

# Funktion zum sicheren Starten des Profile Managers (ohne Doppelstart)
start_profile_manager() {
    # Prüfe ob Manager bereits läuft
    if pgrep -f "rdp-profile-manager.py" > /dev/null; then
        echo "Profile Manager is already running"
        return
    fi
    
    /usr/local/bin/rdp-profile-manager.py &
}

# Finde FreeRDP binary (Debian 12 = xfreerdp, Debian 13 = xfreerdp3)
# Prüfe ZUERST auf xfreerdp3, da es auch einen xfreerdp-Symlink geben könnte
if command -v xfreerdp3 &> /dev/null; then
    FREERDP_CMD="xfreerdp3"
    FREERDP_VERSION=3
elif command -v xfreerdp &> /dev/null; then
    FREERDP_CMD="xfreerdp"
    FREERDP_VERSION=2
else
    zenity --error --text="FreeRDP nicht gefunden! Bitte installieren." 2>/dev/null
    echo "ERROR: FreeRDP not found"
    exit 1
fi

echo "Using $FREERDP_CMD (Version $FREERDP_VERSION)"

# Funktion zum Auslesen von INI-Werten
get_ini_value() {
    local section="$1"
    local key="$2"
    local default="$3"
    
    value=$(awk -F ' *= *' -v section="$section" -v key="$key" '
        /^\[.*\]$/ {
            gsub(/^\[|\]$/, "", $0)
            current_section = $0
            next
        }
        current_section == section && $1 == key {
            # Remove leading/trailing whitespace from value
            gsub(/^[ \t]+|[ \t]+$/, "", $2)
            print $2
            exit
        }
    ' "$CONFIG_FILE")
    
    echo "${value:-$default}"
}

# Wenn kein Profil angegeben, starte Profile Manager
if [ -z "$PROFILE_NAME" ]; then
    # Check if profiles exist
    if [ ! -s "$CONFIG_FILE" ] || ! grep -q '^\[' "$CONFIG_FILE"; then
        # No profiles, start manager
        start_profile_manager
        exit 0
    fi
    
    # Suche nach Autostart-Profil
    PROFILE_NAME=$(awk -F'[][]' '
        /^\[/ { section=$2 }
        /^autostart[[:space:]]*=[[:space:]]*[Tt]rue/ && section { print section; exit }
    ' "$CONFIG_FILE")
    
    # Wenn kein Autostart-Profil gefunden, starte Manager
    if [ -z "$PROFILE_NAME" ]; then
        echo "No autostart profile found, starting Profile Manager..."
        start_profile_manager
        exit 0
    fi
    
    echo "Starting autostart profile: $PROFILE_NAME"
fi

# Funktion zum sicheren Starten des Profile Managers (ohne Doppelstart)
start_profile_manager() {
    # Prüfe ob Manager bereits läuft
    if pgrep -f "rdp-profile-manager.py" > /dev/null; then
        echo "Profile Manager is already running"
        return
    fi
    
    /usr/local/bin/rdp-profile-manager.py &
}

# Lese Profil-Konfiguration
SERVER=$(get_ini_value "$PROFILE_NAME" "server")
USERNAME=$(get_ini_value "$PROFILE_NAME" "username")
DOMAIN=$(get_ini_value "$PROFILE_NAME" "domain")
RESOLUTION=$(get_ini_value "$PROFILE_NAME" "resolution" "client")
MULTIMON=$(get_ini_value "$PROFILE_NAME" "multimon" "False")
REDIRECT_AUDIO=$(get_ini_value "$PROFILE_NAME" "redirect_audio" "True")
REDIRECT_MIC=$(get_ini_value "$PROFILE_NAME" "redirect_microphone" "True")
REDIRECT_USB=$(get_ini_value "$PROFILE_NAME" "redirect_usb" "True")
REDIRECT_SMARTCARD=$(get_ini_value "$PROFILE_NAME" "redirect_smartcard" "True")
REDIRECT_PRINTERS=$(get_ini_value "$PROFILE_NAME" "redirect_printers" "False")

if [ -z "$SERVER" ]; then
    zenity --error --text="Profil '$PROFILE_NAME' nicht gefunden!" 2>/dev/null || \
    echo "ERROR: Profile '$PROFILE_NAME' not found!"
    exit 1
fi

# Wenn kein Username hinterlegt, frage danach
if [ -z "$USERNAME" ]; then
    USERNAME=$(zenity --entry --title="Benutzername" --text="Benutzername für $SERVER:" 2>/dev/null)
    if [ -z "$USERNAME" ]; then
        echo "Aborted: No username provided"
        start_profile_manager
        exit 0
    fi
fi

# Baue FreeRDP-Befehl
CMD="$FREERDP_CMD"

# Server und Benutzer
CMD="$CMD /v:$SERVER"
CMD="$CMD /u:$USERNAME"

if [ -n "$DOMAIN" ]; then
    CMD="$CMD /d:$DOMAIN"
fi

# Auflösung
if [ "$RESOLUTION" = "client" ]; then
    CMD="$CMD /dynamic-resolution"
    # smart-sizing nur bei FreeRDP2
    if [ "$FREERDP_VERSION" -eq 2 ]; then
        CMD="$CMD /smart-sizing"
    fi
else
    CMD="$CMD /size:$RESOLUTION"
fi

# Multi-Monitor
if [ "$MULTIMON" = "True" ] || [ "$MULTIMON" = "true" ]; then
    CMD="$CMD /multimon"
    echo "Multi-Monitor mode enabled"
fi

# Audio
if [ "$REDIRECT_AUDIO" = "True" ]; then
    CMD="$CMD /audio-mode:0"
    CMD="$CMD /sound:sys:pulse"
else
    CMD="$CMD /audio-mode:2"
fi

# Mikrofon
if [ "$REDIRECT_MIC" = "True" ]; then
    CMD="$CMD /microphone:sys:pulse"
fi

# USB-Geräte
if [ "$REDIRECT_USB" = "True" ]; then
    if [ "$FREERDP_VERSION" -eq 3 ]; then
        # FreeRDP3 - USB-Geräte (Dongles, Smart Cards)
        CMD="$CMD /usb:auto"
        
        # USB-Sticks als Laufwerk durchreichen - FESTES Verzeichnis für Hotswap!
        echo "Redirecting USB media directory for hotswap support..."
        MEDIA_DIR="/media/rdpuser"
        
        # Erstelle Verzeichnis falls nicht vorhanden
        mkdir -p "$MEDIA_DIR"
        
        # Reiche das komplette media-Verzeichnis durch
        CMD="$CMD /drive:hotplug,*"
        echo "USB Hotswap enabled: $MEDIA_DIR"
    else
        # FreeRDP2
        CMD="$CMD /usb:id,dev:*"
        MEDIA_DIR="/media/rdpuser"
        mkdir -p "$MEDIA_DIR"
        CMD="$CMD /drive:USB-Media,$MEDIA_DIR"
    fi
fi

# Smart Cards
if [ "$REDIRECT_SMARTCARD" = "True" ]; then
    CMD="$CMD /smartcard"
fi

# Drucker
if [ "$REDIRECT_PRINTERS" = "True" ]; then
    CMD="$CMD /printer"
fi

# Zusätzliche Optionen
CMD="$CMD /cert:ignore"
CMD="$CMD /compression"
CMD="$CMD /clipboard"
CMD="$CMD /gfx:AVC444"
CMD="$CMD /network:auto"

# Zusätzliche Parameter nur für FreeRDP2
if [ "$FREERDP_VERSION" -eq 2 ]; then
    CMD="$CMD +fonts"
    CMD="$CMD +aero"
    CMD="$CMD +glyph-cache"
fi

# Vollbild
CMD="$CMD /f"

# Log
echo "Connecting to: $SERVER as $USERNAME"
echo "Command: $CMD"

# Frage nach Passwort
PASSWORD=$(zenity --password --title="RDP Verbindung zu $SERVER" 2>/dev/null)

if [ -z "$PASSWORD" ]; then
    echo "Aborted by user"
    start_profile_manager
    exit 0
fi

# Starte RDP-Verbindung
# FreeRDP3 hat Probleme mit /from-stdin, nutze /p: stattdessen
if [ "$FREERDP_VERSION" -eq 3 ]; then
    $CMD /p:"$PASSWORD"
else
    # FreeRDP2 mit stdin
    echo "$PASSWORD" | $CMD /from-stdin
fi

# Nach Beenden der Verbindung - zeige Profile Manager wieder
/usr/local/bin/rdp-profile-manager.py &
