#! /bin/sh
# This script integrates ftctxbr DLL to Citrix ICA Client

set -e

ICAROOT=${ICAROOT:-"/opt/Citrix/ICAClient"}
DLL_PATH=${DLL_PATH:-"/opt/ftplugins/lib"}
CONFIG_FILE=${CONFIG_FILE:-"$ICAROOT/config/module.ini"}
DLL_NAME="FTCTXBR.DLL"
SECTION_NAME="FTCtxBr"
LOG_LEVEL="2"
RETVAL=0

# Print message
print_msg () {
echo "$@" 1>&2
}

# Print script usage help
usage () {
print_msg "\
Usage: $(basename $0) -i|-u,
where:
        -i      - Install Citrix ICA support
        -u      - Uninstall Citrix ICA support
        -h      - Show help"
}

# Copy ftctxbr DLL to the Citrix installation directory
copy_dll () {
	cp -f "$DLL_PATH/$DLL_NAME" "$ICAROOT"
	if [ $? = 0 ]
	then
		echo "copied: $ICAROOT/$DLL_NAME"
	else
		echo "ERROR: unable to copy: $ICAROOT/$DLL_NAME"
		exit 1
	fi
}

# Remove ftctxbr DLL from the Citrix installation directory
remove_dll () {
	path="$ICAROOT/$DLL_NAME"
	if [ -h $path -o -f $path ]
	then
		rm $path
		if [ $? = 0 ]
		then
			echo "removed: $path"
		else
			echo "WARNING: unable to remove: $path"
		fi
	fi
}

# Remove ftctxbr DLL entries from the Citrix config file
disable_driver () {
sed \
-e '/^'"$SECTION_NAME"' *= *[Oo][Nn] *$/ d' \
-e 's/\(^VirtualDriver *= *.*\)\(, *'"$SECTION_NAME"'\)\(.*$\)/\1\3/' \
-e '/\['"$SECTION_NAME"'\]/,/^$/ d' \
"$1" > "$1".tmp
cat "$1".tmp > "$1"
rm -f "$1".tmp
}

# Insert ftctxbr DLL entries to the Citrix config file
enable_driver () {
sed \
-e 's/^VirtualDriver *= *.*$/&, '"$SECTION_NAME"'\
'"$SECTION_NAME"'=On/' \
-e '$ a\
\['"$SECTION_NAME"'\]\
DriverName='"$DLL_NAME"'\
LogLevel='"$LOG_LEVEL"'\
' \
"$1" > "$1".tmp
cat "$1".tmp > "$1"
rm -f "$1".tmp
}

# Check for Citrix installation
check_for_citrix () {
if [ ! -e "$ICAROOT" ]; then
print_msg "\
Directory $ICAROOT does not exists, probably, Citrix ICA Client not installed"
exit 0
fi

if [ ! -e "$CONFIG_FILE" ]; then
print_msg "\
Configuration file $CONFIG_FILE does not exists, probably, Citrix ICA Client not installed"
exit 0
fi
}

# Do job
check_for_citrix
case "$1" in
"-i")
	# In case of old installation
	disable_driver "$CONFIG_FILE"
	copy_dll
	enable_driver "$CONFIG_FILE"
	;;
"-u")
	remove_dll
	disable_driver "$CONFIG_FILE"
	;;
"-h")
	usage
	;;
*)
	usage
	;;
esac
