#!/bin/sh
# This script binds a MIME type to a Citrix Published Application.
#
# $Id$
#
#  Copyright 2015 Citrix Systems, Inc. All rights reserved.

if [ $HOME = "/root" ]; then
    echo "Are you running this command as a root user? Run this command without root privileges"
    return
fi
Usage="Usage: $0 [-p] example_file|MIME-type published-application [server|server-URI]"

# '-p' option means use pnabrowse rather than storebrowse.

[ "$1" = "-p" ] && { UsePNA=yes; shift; }

[ "$1" = "" -o "$2" = "" ] && { echo $Usage ; exit 1; }

# Determine ICAROOT

if [ "$ICAROOT" = "" ] ; then
    for i in $HOME/linuxx86 $HOME/linuxx64 $HOME/linuxarm64 $HOME/linuxarmhf /opt/Citrix /usr/lib
    do
	if [ -x $i/ICAClient/wfica ] ; then
	    ICAROOT=$i/ICAClient
	    break
	fi
    done
fi

if [ "$ICAROOT" = "" ] ; then
    echo Can not find Receiver installation.
    echo Please set ICAROOT environment variable and try again.
    exit 1
fi

#echo ICAROOT is $ICAROOT

# If the first argument is a file, try to get a MIME type.

if [ -f "$1" ] ; then
    Mime=`xdg-mime query filetype "$1"`
    [ $? -ne 0 -o -z "$Mime" ] && {
        echo "xdg-mime not installed or command not working as expected, please check!"
        echo "Can not determine MIME type of $1 correctly, falling back to file command" ;
	Mime=`file -b --mime-type "$1"`
	[ $? -ne 0 -o -z "$Mime" ] && {
		exit 2;
	}
    }
#   echo Mime type of $1 is: ${Mime}
else
#   echo Using Mime type: $1
    Mime=$1
fi

# Is there an existing icon for this MIME type?

UDesk=$HOME/.local/share/applications
Desk=/usr/share/applications


#Set the Icon key
Icon="Icon=$HOME/.ICAClient/cache/Icons/$2.png"
if [ ! -f "$HOME/.ICAClient/cache/Icons/$2.png" ] ; then
    echo "Is $2 a subscribed application?"
    echo "Exiting"
fi



# Now write a desktop file.

Name=`echo $Mime | tr '/' ':'`
File=$UDesk/${Name}.desktop
if [ -z "$UsePNA" ] ; then
    Launcher=storebrowse
else
    # pnabrowse usually needs a wrapper to pass user credentials.

    echo Session launch with pnabrowse may require a locally-configured launcher.
    Launcher=pnabrowse_launch
fi

#echo Creating $File

cat > $File <<EOF
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Name=Citrix Launcher for $Mime
StartupWMClass=Wfica
NoDisplay=true
MimeType=$Mime
$Icon
TryExec=/opt/Citrix/ICAClient/util/$Launcher
Exec=$ICAROOT/util/$Launcher -L "$2" -F %f "$3"
EOF

# Register as the Mime-type handler

xdg-mime default ${Name}.desktop $Mime
