#!/bin/bash
# TSID QR Display Wrapper - PAM-enabled TSID greeter
# This wrapper MUST be executed by LightDM greeter only, NOT from SSH/TTY

# Verify we're running in LightDM greeter context
if [ "$PAM_SERVICE" != "lightdm" ] && [ "$PAM_SERVICE" != "tsid-greeter" ]; then
    # Check if we're being called from LightDM by checking parent process
    PARENT_PID=$PPID
    PARENT_CMD=$(ps -p $PARENT_PID -o comm= 2>/dev/null)
    
    # If parent is not lightdm or lightdm-gtk-greeter, abort
    if [[ "$PARENT_CMD" != "lightdm"* ]]; then
        echo "[TSID ERROR] tsid-qr-display-wrapper must be executed by LightDM greeter only" >&2
        echo "[TSID ERROR] Current PAM_SERVICE=$PAM_SERVICE, Parent=$PARENT_CMD" >&2
        exit 1
    fi
fi

# LightDM greeter environment - use LightDM's X11 display
# LightDM sets DISPLAY in greeter environment, but we need to ensure it's correct
if [ -z "$DISPLAY" ]; then
    # LightDM should have set DISPLAY, but if not, detect it
    # Look for LightDM's X11 socket specifically (usually :0)
    for display_num in 0 1 2; do
        if [ -S "/tmp/.X11-unix/X$display_num" ]; then
            # Check if this display is owned by lightdm process
            DISPLAY_OWNER=$(ls -l "/tmp/.X11-unix/X$display_num" 2>/dev/null | awk '{print $3}')
            if [ "$DISPLAY_OWNER" = "lightdm" ] || [ "$DISPLAY_OWNER" = "root" ]; then
                export DISPLAY=":$display_num"
                echo "[TSID] Detected LightDM display: $DISPLAY (owner: $DISPLAY_OWNER)" >&2
                break
            fi
        fi
    done
    
    # Fallback to :0 if nothing found
    if [ -z "$DISPLAY" ]; then
        export DISPLAY=:0
        echo "[TSID] Using fallback display: $DISPLAY" >&2
    fi
fi

# Auto-detect XAUTHORITY dynamically (LightDM specific paths)
if [ -z "$XAUTHORITY" ]; then
    # Try LightDM-specific locations first
    for auth_file in \
        "/var/lib/lightdm/.Xauthority" \
        "/var/lib/lightdm/:0.Xauthority" \
        "/run/lightdm/:0.Xauthority" \
        "/run/user/$(id -u)/Xauthority"; do
        if [ -f "$auth_file" ]; then
            export XAUTHORITY="$auth_file"
            echo "[TSID] Using XAUTHORITY: $XAUTHORITY" >&2
            break
        fi
    done
    
    # If still not found, try to find it from lightdm user
    if [ -z "$XAUTHORITY" ]; then
        LIGHTDM_HOME=$(getent passwd lightdm | cut -d: -f6)
        if [ -f "$LIGHTDM_HOME/.Xauthority" ]; then
            export XAUTHORITY="$LIGHTDM_HOME/.Xauthority"
            echo "[TSID] Using XAUTHORITY from lightdm home: $XAUTHORITY" >&2
        fi
    fi
fi

echo "[TSID] Using DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY" >&2

# Set PAM environment variables for greeter
export PAM_SERVICE="tsid-greeter"
export PAM_TYPE="greeter"

# Disable Python output buffering to ensure logs appear immediately
export PYTHONUNBUFFERED=1

# Log file for debugging (use /tmp for write permission)
LOG_FILE="/tmp/tsid-qr-display.log"
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"
echo "[TSID] Logging to $LOG_FILE" >&2

# Start QR display immediately - tsid-qr-display will read company_code from file
echo "[TSID] Starting QR display for greeter authentication" >&2
echo "[TSID] Running as user: $(whoami)" >&2
exec /usr/bin/tsid-qr-display 2>>"$LOG_FILE"
