#!/bin/bash

#PASSWORD_PROMPT=""
APPNAME=""

print_help() {
cat <<EOF
This program wraps a bit of graphical fluff around xfreerdp using kdialog and notify-send to make it useable in a regular office context.

Usage: foxde-xfreerdp-gui [--ask-pass-prompt <remote-name>] <<xfreerdp-options>>
       foxde-xfreerdp-gui --help

	--ask-pass-prompt <remote-name> will trigger a ui wrapper that asks for a password before connecting.
		To detect some errors (currently just an unexpected certificate) a logfile will be written to \$TEMP/xfreerdp-gui-log.XXXXXXXXXX
		This log will be left behind if xfreerdp exits with an error code.
		
EXIT CODES:
	Usually returns what xfreerdp would return.

	77 Certificate mismatch for tofu mode
	   see ~/.config/freerdp/known_hosts2
EOF
}

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

    *) break;
  esac
done

DO_RETRY=""

if [ -z "$APPNAME" ] ; then
	xfreerdp "$@"
else
	LOGFILE="$(mktemp --tmpdir xfreerdp-gui-log.XXXXXXXXXX)"
	kdialog --version || exit 100
	RETCODE=131
	while [ "$RETCODE" -eq 131 ] || [ -n "$DO_RETRY" ] ; do
		DO_RETRY=""
		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="$?"
			printf "Freerdp exited with exit code: %d\n\n\n" "$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 77
			elif [ "$RETCODE" -eq 148 ] || grep -q "ERRCONNECT_PASSWORD_EXPIRED" "$LOGFILE"; then
				kdialog --error --title "(RDP) Passwort abgelaufen" "Dein Passwort für $APPNAME ist abgelaufen,\nbitte kontaktiere die IT-Abteilung.\n\nFehlercode: $RETCODE \n(sollte 131 oder 132 sein)"
				exit $RETCODE
			elif [ "$RETCODE" -eq 132 ] ; then
				notify-send "(RDP) Dein Passwort wurde abgelehnt." "Entweder hast du dich vertippt oder du hast keinen Zugang."
				DO_RETRY="y"
			fi

		fi
	done
	case "$RETCODE" in
		0|11|12)
			notify-send "(RDP) Verbindung beendet" "Die Verbindung zu $APPNAME wurde beendet."
			rm "$LOGFILE"
			exit 0 ;;
		*)
			notify-send  "(RDP) Verbindungsfehler: $RETCODE" "Die Verbindung zu $APPNAME wurde aufgrund eines Fehlers beendet. Felercode: $RETCODE"
			;;
	esac
	exit "$RETCODE"
fi
