#!/bin/sh
# This script runs as uninstall.sh and as slack-uninstall.sh.

###############################################################################
# Generic pinstall.sh
# Copyright (C) step 2016, 2017
# GNU GPL v2 and MIT licenses apply
# Some code taken from PackIt v1.14 by SFR'2013-2016
###############################################################################

# Sections 'ROX SendTo/OpenWith' and 'Thunar custom action' removed, see also
# RStudio ROX-App puninstall.sh.

# Environment variable PKG_UNINSTALL_OPTIONS can be exported before
# uninstalling this package. It's a string of words as follows:
# say-yes : Answer yes to all questions, consequently do not block on GUI
#   prompts, terminals, etc.  This is probably what you want for a full
#   non-blocking uninstall. The default uninstall is normally full and blocking.
# say-no : Answer no to all prompts, no blocking. This sets up a minimal
#   non-blocking uninstall.
# Example: export PKG_UNINSTALL_OPTIONS="say-no"

# NOTE for Fatdog64-70x users: The package manager uninstall action doesn't
# run slack-uninstall.sh automatically. Save slack-uninstall.sh and run the
# saved copy after uninstalling from the package manager. Alternatively,
# right-click the ROX-App $RAPPDIR, and select 'Uninstall'.

# No change below
RAPPDIR=/usr/local/apps/RLanguage-3.4.2
RAPPDESKTOPFILE=/usr/share/applications/R.desktop
# Open issue: TEXTDOMAINDIR has already been deleted.
APPNAME=$(printf "$(gettext "%s Uninstall")" "${RAPPDIR##*/}")
PKGNAME=R
PKGVER=3.4.2
PKGARCH=x86_64
PKGBUILD=1

[ "`which realpath 2>/dev/null`" ] || alias realpath='readlink -f'

myfullpath=$(realpath "$0")
case $myfullpath in
  /tmp/*)
    : running as a copy: safe to continue ;;
  *)
    : restart as a self-copy
    mkdir -p "/tmp${myfullpath%/*}" &&
      cp -f "$myfullpath" "/tmp$myfullpath" &&
      chmod +x "$myfullpath" && exec "/tmp$myfullpath"
      # chmod will fail from inside SFS (ro file system)
      # and allow script to continue
    ;;
esac

# Continuing from /tmp or SFS...
if command -v : removepkg >/dev/null; then
  : assume OS is Fatdog64 coming from manual uninstall
  : removepkg $PKGNAME-$PKGVER-$PKGARCH-$PKGBUILD
elif [ -d /usr/local/petget ]; then
  : assume OS is Puppy Linux coming from manual uninstall

  TREE2=$PKGNAME-$PKGVER-$PKGARCH-$PKGBUILD
  TREE2=$TREE2 /usr/local/petget/removepreview.sh
  [ -e /root/.packages/$TREE2.files ] && exit # package wasn't removed
  # PPM is unreliable and very slow. It fails deleting /usr/lib64/R-$PKGVER
  # and its contents but it still reports it did! Tested on Slacko 6.0.3 VM.

  # PPM may fail deleting $RAPPDIR/* empty (sub)dir(s) - retry.
  find "$RAPPDIR" -type d -empty -delete
fi

# -----------------------------------------------------------------------------

# Retarget symbolic links to the highest earlier version, if any.
# Leave no dangling reference behind.
retarget() { # $1-ref [$2-tail-after-version-string]
  set +f
  local tgt
  if [ -L "$1" ]; then
    tgt=$(ls -1dv "${1%$2}-"*"$2" 2>/dev/null | tail -1)
    [ -e "$tgt" ] && ln -vsfT "${tgt##*/}" "$1"
    [ -n "$(readlink -e "$1")" ] || rm "$1"
  fi
}

# Match swap_in_new_version() in doinst.sh file.
printf "%s\n" "" "Adding links to older version:"
retarget "${RAPPDIR%-3.4.2}"
retarget "$RAPPDESKTOPFILE" .desktop
retarget /usr/bin/R
retarget /usr/bin/Rscript
retarget /usr/share/man/man1/R.1 .1
retarget /usr/share/man/man1/Rscript.1 .1
retarget /usr/lib64/pkgconfig/libR.pc .pc

# -----------------------------------------------------------------------------

# Remove icon from ROX pinboard and $HOME/Desktop
[ -e "$HOME/Choices/ROX-Filer/PuppyPin" ] &&
rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <PinboardRemove>
   <Path>$RAPPDIR</Path>
   <Label>${RAPPDIR##*/}</Label>
  </PinboardRemove>
 </env:Body>
</env:Envelope>
EOF
[ -d "$HOME/Desktop" ] && rm -f "$HOME/Desktop/${RAPPDESKTOPFILE##*/}"

# -----------------------------------------------------------------------------

# User-installed R packages are to be uninstalled separately.
library=/usr/lib64/R-$PKGVER/library
if [ -n "$(ls -A "$library/" 2>/dev/null)" ]; then
  if command -v gxmessage >/dev/null; then
    XMESSAGE="${XMESSAGE:-gxmessage}"
  else
    XMESSAGE="${XMESSAGE:-xmessage}"
  fi
  if [ "$PKG_UNINSTALL_OPTIONS" != "${PKG_UNINSTALL_OPTIONS#*say-}" ]; then
    : keep quiet
  else
    $XMESSAGE -buttons "$(gettext 'Yes'):100,$(gettext 'No'):101" \
      -center -title "$APPNAME" \
      "$(printf \
      "$(gettext '%s was uninstalled. User-installed packages remain\nin library '%s'.\nUninstall them manually.\n\nOpen folder? (will not block)')" \
        "$PKGNAME-$PKGVER" "$library")"
    if [ $? = 100 ]; then
      xdg-open "$library" || rox "$library"
    fi
  fi
fi

# =============================================================================
