#!/bin/bash
# This script only helps to update applications that have already been installed by the user,
# but that are not found in software repositories.

# Package information
package_name="navicat"
latest_package_version="16"
package_installation_directory="/opt/$package_name"
package_download_name="$package_name-$latest_package_version-mysql-en.AppImage"
download_link="http://download3.navicat.com/download/$package_name$latest_package_version-mysql-en.AppImage"
installed_package_version=$(find $package_installation_directory -name "$package_name-*-mysql-en.AppImage" | cut -d"-" -f 2- | cut -d"-" -f -1)

# If necessary, update the application installation
function update_app() {
    #Get the app
    mkdir -p "$package_installation_directory/"
    wget --no-check-certificate -O "$package_installation_directory/$package_download_name" "$download_link"
    chmod 777 "$package_installation_directory/$package_download_name"

    #Create desktop shortcut
    if test ! -e "/usr/share/applications/navicat.desktop" ; then
cat > "/usr/share/applications/navicat.desktop" << EOM
[Desktop Entry]
Type=Application
Name=Navicat 16 for MySQL
GenericName=Database Development Tool
Icon=navicat-icon
Exec=navicat
Categories=Development;
Keywords=database;sql;
EOM
    fi

    #Create desktop shortcut
    if test ! -e "/usr/bin/navicat" ; then
        echo "#!/bin/bash" > "/usr/bin/navicat"
        echo "" >> "/usr/bin/navicat"
        echo "env DESKTOPINTEGRATION=1 $package_installation_directory/$package_download_name" >> "/usr/bin/navicat"
        chmod 777 "/usr/bin/navicat"
    fi
}

# Check the package version
#Check the main version of the application
if [ $latest_package_version -gt $installed_package_version ]
then
    echo "Updating app"
    update_app
elif [ -z $installed_package_version ]
then
    echo "Updating app"
    update_app
else
    echo "App version: $latest_package_version. The application appears to be updated. Nothing to do."
fi
