#!/bin/sh
#
# get_xauth shell script to make and screenshot with scrot
#               and save it in /var/www
# Copyright (C) 2006-2011  mariodebian at gmail
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#


export DISPLAY=:0

user=$(/usr/lib/tcos/tcos-last --user 2>/dev/null)
home=$(getent passwd ${user} | head -1 | awk -F":" '{print $6}')
if [ "$user" = "root" ]; then echo -n "error: root not allowed"; exit 1; fi
# test if file exists and not empty
if [ -s "${home}/.Xauthority" ]; then
   XAUTHORITY=$home/.Xauthority
else
   XAUTHORITY=$(find /tmp/ -name ".gdm*" -user ${user} 2>/dev/null | head -1)
   [ -z $XAUTHORITY ] && XAUTHORITY=$(xauth info 2>/dev/null | awk '/^Authority/ {print $3}')
   [ -z $XAUTHORITY ] && [ "$XAUTHORITY" != "/root/.Xauthority" ] && XAUTHORITY="$(find /var/run/gdm*/ -name auth-for-* -user ${user} 2>/dev/null | head -1)/database"
fi

# standalone GDM login
if [ "$user" = "" ] && [ -e "/var/lib/gdm/:0.Xauth" ]; then
  XAUTHORITY="/var/lib/gdm/:0.Xauth"
fi

# standalone GDM3 login
if [ "$user" = "" ] && find /var/run/gdm3/ -type f 2>/dev/null| grep -q "auth-for-Debian-gdm" ; then
  XAUTHORITY=$(find /var/run/gdm3/ -type f 2>/dev/null| grep "auth-for-Debian-gdm")
fi

# standalone KDM login
if [ "$user" = "" ] && [ -e "/usr/bin/kdm" ]; then
  XAUTHORITY=$(find /var/run/xauth -type f | tail -1)
fi

echo -n "${XAUTHORITY}"

exit 0
