#!/bin/bash
# TSID Restore Greeter Configuration Script
# Removes autologin configuration to show QR greeter
# Called by: systemd on boot, or manually after logout

# Detect DM from config file
get_dm_service() {
    local config_file="/etc/tsid/os-config"
    
    # 1. Read from config file
    if [ -f "$config_file" ]; then
        local dm=$(grep "^TSID_DISPLAY_MANAGER=" "$config_file" | cut -d= -f2)
        echo "$dm"
        return
    fi
    
    # 2. Fallback: detect by OS version
    if [ -f /etc/rocky-release ]; then
        local rocky_version=$(grep -oE '[0-9]+' /etc/rocky-release | head -1)
        if [ "$rocky_version" -ge 10 ] 2>/dev/null; then
            echo "gdm"
        else
            echo "lightdm"
        fi
    elif [ -f /etc/debian_version ]; then
        echo "lightdm"
    else
        echo "lightdm"
    fi
}

DM_SERVICE=$(get_dm_service)

# GDM 설정 복구
if [ "$DM_SERVICE" = "gdm" ]; then
    GDM_CONF="/etc/gdm/custom.conf"
    [ -d /etc/gdm3 ] && GDM_CONF="/etc/gdm3/custom.conf"
    
    cat > "$GDM_CONF" << 'EOF'
# GDM configuration (managed by TSID)
[daemon]
AutomaticLoginEnable=True
AutomaticLogin=tsid-greeter
TimedLoginEnable=true
TimedLogin=tsid-greeter
TimedLoginDelay=0
WaylandEnable=true

[security]

[xdmcp]

[chooser]

[debug]
EOF
    logger "TSID: Restored GDM greeter configuration"
    
    # autostart 파일 제거 (중복 실행 방지)
    rm -f /home/tsid-greeter/.config/autostart/tsid-kiosk.desktop 2>/dev/null || true
    logger "TSID: Removed autostart file to prevent duplicate execution"
fi

# LightDM 설정 복구
if [ "$DM_SERVICE" = "lightdm" ]; then
    mkdir -p /etc/lightdm/lightdm.conf.d
    cat > /etc/lightdm/lightdm.conf.d/99-tsid-autologin.conf << 'EOF'
[Seat:*]
autologin-guest=false
autologin-user=
autologin-user-timeout=0
EOF
    logger "TSID: Restored LightDM greeter configuration"
fi

exit 0
