#!/usr/bin/env bash
set -e

APP_NAME="SysUpdate"
DESKTOP_NAME="com.bytesbreadbbq.sysupdate.desktop"

INSTALL_DIR="$HOME/.local/bin"
DESKTOP_DIR="$HOME/.local/share/applications"
ICON_DIR="$HOME/.local/share/icons/hicolor/256x256/apps"

APPIMAGE_TARGET="$INSTALL_DIR/SysUpdate.AppImage"
DESKTOP_TARGET="$DESKTOP_DIR/$DESKTOP_NAME"
ICON_TARGET="$ICON_DIR/sysupdate.png"

LEGACY_BIN="/usr/local/bin/sysupdate-gui"
LEGACY_DESKTOP="/usr/local/share/applications/com.bytesbreadbbq.sysupdate.desktop"
LEGACY_ICON="/usr/local/share/pixmaps/com.bytesbreadbbq.sysupdate.png"

prompt_remove_legacy() {
    if [ -f "$LEGACY_BIN" ] || [ -f "$LEGACY_DESKTOP" ] || [ -f "$LEGACY_ICON" ]; then
        echo
        echo "A legacy system-wide SysUpdate install was also found."
        echo "Removing it requires administrator permission because it is under /usr/local."
        echo
        read -r -p "Remove legacy system-wide files too? [y/N] " reply
        case "$reply" in
            [yY]|[yY][eE][sS])
                sudo rm -f "$LEGACY_BIN" "$LEGACY_DESKTOP" "$LEGACY_ICON"
                if command -v update-desktop-database >/dev/null 2>&1; then
                    sudo update-desktop-database /usr/local/share/applications >/dev/null 2>&1 || true
                fi
                ;;
            *)
                echo
                echo "Skipped legacy system-wide cleanup."
                echo "To remove it later, run:"
                echo "  sudo rm -f \"$LEGACY_BIN\" \"$LEGACY_DESKTOP\" \"$LEGACY_ICON\""
                ;;
        esac
    fi
}

refresh_user_desktop() {
    if command -v update-desktop-database >/dev/null 2>&1; then
        update-desktop-database "$DESKTOP_DIR" >/dev/null 2>&1 || true
    fi

    if command -v gtk-update-icon-cache >/dev/null 2>&1; then
        gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" >/dev/null 2>&1 || true
    fi
}

echo "Uninstalling $APP_NAME..."

rm -f "$APPIMAGE_TARGET" "$DESKTOP_TARGET" "$ICON_TARGET"

refresh_user_desktop
prompt_remove_legacy

echo
echo "$APP_NAME uninstalled."