#!/bin/sh
#
# Startup script
#

# Function to find the real directory a program resides in.
# Feb. 17, 2000 - Sam Lantinga, Loki Entertainment Software

FindPath()
{
    fullpath="`echo $1 | grep /`"
    if [ "$fullpath" = "" ]; then
        oIFS="$IFS"
        IFS=:
        for path in $PATH
        do if [ -x "$path/$1" ]; then
               if [ "$path" = "" ]; then
                   path="."
               fi
               fullpath="$path/$1"
               break
           fi
        done
        IFS="$oIFS"
    fi
    if [ "$fullpath" = "" ]; then
        fullpath="$1"
    fi

    # Is the sed/ls magic portable?
    if [ -L "$fullpath" ]; then
        #fullpath="`ls -l "$fullpath" | awk '{print $11}'`"
        fullpath=`ls -l "$fullpath" |sed -e 's/.* -> //' |sed -e 's/\*//'`
    fi
    dirname $fullpath
}

RegisterScheme()
{
    desktopDirectory=$HOME/.local/share/applications
    desktopFile=$desktopDirectory/$1-handler.desktop
    pathExec=`realpath $2`
    # Creamos el esquema si no existe ya
    # Explicación de las diferentes propiedades en https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#recognized-keys
    if [ -d "$desktopDirectory" ]; then
        cat << EOF > "$desktopFile"
[Desktop Entry]
Name=$3
Type=Application
Exec=$pathExec.sh %u
MimeType=x-scheme-handler/$1
NoDisplay=true
StartupNotify=true
Terminal=false
EOF
        # Registramos el esquema
        xdg-mime default $1-handler.desktop x-scheme-handler/$1 2>/dev/null 1>&2
    fi
}

# Set the home if not already set.
if [ "${VELNEO_PATH}" = "" ]; then
    VELNEO_PATH="`FindPath $0`"
fi

LD_LIBRARY_PATH=.:${VELNEO_PATH}:${LD_LIBRARY_PATH}
export LD_LIBRARY_PATH

# Let's boogie!
if [ -x "${VELNEO_PATH}/vClient" ]
then
    # El nombre de la aplicación va sin tilde porque no consigo que muestre correctamente la tilde el diálogo que muestra Google Chrome
    RegisterScheme velneo-run "${VELNEO_PATH}/vClient" "Ejecucion de Velneo"
	cd "${VELNEO_PATH}/"
	exec "./vClient" "$@"
fi
echo "Couldn't run Velneo vClient V7"
exit 1
