#!/bin/bash

# File:		ag_xauth
# Package:	Network configuration
# Summary:	Agent for reading|writing X11 authority information
# Authors:	Dan Vesely, Michal Svec <msvec@suse.cz>,
#		Werner Fink, Martin Vidner
# See:		xauth(1), X(7)
#
# $Id: ag_xauth 13266 2004-01-19 08:40:37Z mvidner $
#
# Add a key with a new hostname to $USER's XAUTHORITY
# via xauth and sux.
#
#    string tmpfile = SCR::Read(.xauth.key);
#    /* change hostname and other required stuff */
#    SCR::Write(.xauth.key, tmpfile);
#
# Note that now the script returns and expects a file name with
# the key data to avoid disclosing the key via ps.
# Old ycp code will still work.

# If there's no DISPLAY, xauth and sux complain
exec 2>/dev/null

# We want to parse English output
export LC_ALL=C

while true ; do
    IFS=
    read COMMAND || exit
    unset IFS
    # strip leading backquote introduced by NI
    COMMAND=${COMMAND#\`}

    case "$COMMAND" in
	"result ("*)
	    exit
	    ;;

	"Read (.key)")
	    tmp=$(mktemp /root/.Xauthority-XXXXXX)
	    chmod 0600 $tmp
	    X=:${DISPLAY##*:}
	    Y=$(hostname -f)$X

	    # Use autoconf-like replacement strings but escape them to
	    # guard againt possible future autoconfiscation of this script.
	    su - $USER --command="/usr/X11R6/bin/xauth list $X $Y" | sed \
		    -e "s/^$(cat /proc/sys/kernel/hostname)/add @HN\@/" \
		    -e "s/^$(hostname -f)/add @FQHN\@/"        > $tmp

	    echo '"'$tmp'"'
	    ;;

	"Write (.key,"*)
	    tmp=$(mktemp /root/.Xauthority-XXXXXX)
	    chmod 0600 $tmp
	    file=$(echo "$COMMAND" | sed 's/^Write (.key, *"\(.*\)")/\1/')

	    sed -e "s/@HN\@/$(cat /proc/sys/kernel/hostname)/" \
		-e "s/@FQHN\@/$(hostname -f)/" < $file > $tmp

	    /usr/X11R6/bin/xauth source $tmp
	    rm -f "$file" "$tmp"
	    sux -c exit - $USER
	    echo "true"
	    ;;

	*)
	    echo nil
    esac
done

# EOF
