#!/bin/bash


patchlist=""
packagelist=""
type="patch"

while [ -n "$1" ]; do

	case "$1" in
		"--patch")
		type="patch"
		;;

		"--package")
		type="package"
		;;

	*)
		if [ $type == "patch" ]; then
			patchlist="$patchlist \"$1\""
		fi

		if [ $type == "package" ]; then
			packagelist="$packagelist \"$1\""
		fi

		;;
	esac

	shift
done


tempdir=`mktemp -d /tmp/kupdateapplet.XXXXXXXXXX`
if [ $? != 0 ];
then	
	echo "Unable to create temp dir"
	exit 1
fi

out=${tempdir}/kupdateapplet_out
err=${tempdir}/kupdateapplet_err

patchlistfile=${tempdir}/kupdateapplet_patch
packagelistfile=${tempdir}/kupdateapplet_package

patchcommand="xargs zypper --no-cd -x --non-interactive in -l -t patch --name < $patchlistfile"
packagecommand="xargs zypper --no-cd -x --non-interactive in -l -t package --name < $packagelistfile"

mkfifo $out || { echo "can't mkfifo $out" >&2 ; exit 1 ; }
mkfifo $err || { echo "can't mkfifo $err" >&2 ; exit 1 ; }
echo $patchlist > $patchlistfile || { echo "can't create $patchlistfile" >&2 ; exit 1 ; }
echo $packagelist > $packagelistfile || { echo "can't create $packagelistfile" >&2 ; exit 1 ; }




retval=0

cat $err >&2 &
cat $out &

command="true"

if [ -n "$patchlist" ] && [ -n "$packagelist" ]; then
  command="$patchcommand ; $packagecommand"
fi

if [ -n "$patchlist" ] && [ -z "$packagelist" ]; then
  command="$patchcommand"
fi

if [ -z "$patchlist" ] && [ -n "$packagelist" ]; then
  command="$packagecommand"
fi


kdesu --noignorebutton -d -c "( $command ) > $out 2> $err "
retval=$?

rm -rf ${tempdir}

exit $retval
