#!/bin/bash

PASSWORD_PROMPT=""
APPNAME=""
LOGFILE="$(mktemp --tmpdir xfreerdp-gui-log.XXXXXXXXXX)"

while [ "$#" -gt 0 ]; do
  case "$1" in
    --ask-pass-prompt) APPNAME="$2"; shift 2;;

    *) break;
  esac
done

if [ -z "$APPNAME" ] ; then
	xfreerdp "$@"
else
	kdialog --version || exit 100
	RETCODE=131
	while [ "$RETCODE" -eq 131 ] ; do
		PASSWORD="$(kdialog --password "Passwort für $APPNAME" --title "Remotedesktopverbindung")"
		if [ -z $PASSWORD ] ; then
			notify-send "(RDP) Abgebrochen" "Es wird keine Verbindung zu $APPNAME aufgebaut."
			exit
		else
			date +"%Y-%m-%d %H:%M:%S" > "$LOGFILE"
			xfreerdp "$@" /from-stdin:force >> "$LOGFILE" <<EOF
$PASSWORD
EOF
			RETCODE="$?"
			if grep -q "certificate does not match the certificate used for previous connections" "$LOGFILE" ; then
				kdialog --error "Der Server kann sich aktuell nicht ausweisen, weswegen die Verbindung beendet wurde.\nBitte kontaktiere die IT-Abteilung." --title "Verbindung fehlgeschlagen."
				exit 131
			fi

		fi
	done
	if [ "$RETCODE" -eq 0 ] || [ "$RETCODE" -eq 12 ] ; then
		notify-send "(RDP) Verbindung beendet" "Die Verbindung zu $APPNAME wurde beendet."
		rm "$LOGFILE"
		exit 0
	else
		notify-send  "(RDP) Verbindungsfehler: $RETCODE" "Die Verbindung zu $APPNAME wurde aufgrund eines Fehlers beendet. Felercode: $RETCODE"
	fi
	
	exit "$RETCODE"
fi
