#!/bin/bash

# Script for gnome-shell
# Should return package name for given .desktop file (without \n)
# Exits non zero if fails to guess

# This is, in general, not intented to be run manually.
# So, silently exit if desktop file is not provided.
[ -z $1 ] && {
    # echo "No argument (.desktop file name)."
    exit 1
}

[ -f $1 ] || {
    # No such file - exiting
    exit 2
}

desktop=$1

# Special case - Telegram
if [ $desktop == "/usr/share/applications/org.telegram.desktop._bd9ccae75ce72a4ddb4260b3c0743e13.desktop" ]
then echo -n "telegram-desktop"
    exit 0
fi

# Check Flatpak case
echo $desktop | grep "var/lib/flatpak" 2>&1 > /dev/null ; codeFlat=$?
if [ $codeFlat -eq 0 ]
then # Working with Flatpak package
    packOne=`cat $desktop | grep -m 1 "X-Flatpak=" | awk -F\= '{print $NF}'`
else # Working with deb package
    # We try to guess the package from the given desktop file.
    # packOne - try to get it from the packages. This may not work
    # cause some desktops are generated or from $HOME/.local/share/applications
    packOne=`dpkg -S $desktop 2>&1 | grep -v "dpkg-query:" | awk -F\: '{print $1}'`

    # packTwo - try find out the origin the launched command (Exec in .desktop)
    exec=`cat $desktop | grep -v "TryExec=" | grep -m 1 "Exec=" | awk -F\= '{print $NF}' | awk '{print $1}'`
    path=`which $exec`
    packTwo=`dpkg -S $path 2>&1 | grep -v "dpkg-query:" | awk -F\: '{print $1}'`
fi

# Check if Exec contains sh or bash - we can assume that it is appImage
# Even if not an appImage, we can't determine the bin - do not show Uninstall.
if [ $exec == "bash" ] || [ $exec == "sh" ]
then exit 5
fi

# Check if Exec contains "flatpak run" & "bottles" - we can assume desktop is created by bottles
# We can't remove such app - do not show Uninstall.
cat $desktop | grep -v "TryExec=" | grep -m 1 "Exec=" | grep "flatpak run" | grep "com.usebottles.bottles" 2>&1 > /dev/null ; codeBottles=$?
if [ $codeBottles -eq 0 ]
then exit 6
fi

packResult=""
if [ -z $packOne ]
    then if [ -z $packTwo ]
            then exit 3
            else packResult="$packTwo"
        fi
    else packResult="$packOne"
fi

# Check blacklist: packs forbidden to delete
config="$HOME/.cache/uncominstall/config.json"
protected=`sed -n '/protected_packages/,$p' $config | sed -n '/\[/,/\]/p'`
echo $protected | grep "\"$packResult\"" 2>&1 > /dev/null ; codeProtected=$?
if [ $codeProtected -eq 0 ]
    then exit 4
    else echo -n $packResult
fi

exit 0
