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

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

# 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
NOWOOF=true # NOT USED
RAPPDIR=/usr/local/apps/RStudio-1.1.463
RAPPDESKTOPFILE=/usr/share/applications/rstudio.desktop
# Open issue: TEXTDOMAINDIR has already been deleted.
APPNAME=$(printf "$(gettext "%s Uninstall")" "${RAPPDIR##*/}")
PKGNAME=rstudio
PKGVER=1.1.463
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
  # FIXME coming from PPM uninstall TEXTDOMAIN isn't set.

  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 other version:"
retarget "${RAPPDIR%-1.1.463}"
retarget "$RAPPDESKTOPFILE" .desktop
retarget /usr/bin/rstudio
retarget /usr/lib/rstudio

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

# Delete all broken symlinks after uninstallation
LOC1="/etc/xdg/rox.sourceforge.net/SendTo"
LOC2="$HOME/.config/rox.sourceforge.net/SendTo"
LOC3="$HOME/.config/rox.sourceforge.net/OpenWith"
for i in "$LOC1" "$LOC1_mimetypes" "$LOC2" "$LOC3"; do
  if [ -d "$i" ]; then
    find "$(realpath "$i")" -type l -name "${RAPPDIR##*/}" |
    while read linkpath; do
      # Delete the sendto link and its dir, if empty.
      rm "$linkpath"
      dirpath=${linkpath%/*}
      >&2 rmdir "$dirpath"
      # Delete the mime-type link, if any
      dirname=${dirpath##*/}
      dirpath=${dirpath%/*}
      mimelinkpath="${dirpath%/*}/MIME-types/${dirname#.}"
      [ -L "$mimelinkpath" ] && rm "$mimelinkpath"
    done
  fi
done

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

# 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##*/}"

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

# Delete ROX-App action from Thunar
CONFIG="$HOME/.config/Thunar/uca.xml"
CONFIG_BAK="$HOME/.config/Thunar/uca.xml.bak"
CONFIG_TMP=/tmp/uca.xml

if [ -f "$CONFIG" ]; then
  grep "<name>${RAPPDIR##*/}/name>" "$CONFIG" >/dev/null && {
  LINE_NO=`grep -n "<name>${RAPPDIR##*/}</name>" "$CONFIG" | cut -f1 -d ':'`

  LINE_TMP=$LINE_NO
  i=0; while [ $i -le 99 ]; do
    awk 'NR=='${LINE_TMP}' {if ($0 == "<action>") {print $1}}' "$CONFIG" | grep '<action>' >/dev/null && break
    LINE_TMP=$(($LINE_TMP-1))
    i=$((i + 1))
  done
  LINE_TOP=$LINE_TMP

  LINE_TMP=$LINE_NO
  i=0; while [ $i -le 99 ]; do
    awk 'NR=='${LINE_TMP}' {if ($0 == "</action>") {print $1}}' "$CONFIG" | grep '</action>' >/dev/null && break
    LINE_TMP=$(($LINE_TMP+1))
    i=$((i + 1))
  done
  LINE_BOT=$LINE_TMP

  sed -e ''${LINE_TOP}','${LINE_BOT}'d' "$CONFIG" > "$CONFIG_TMP"
  mv "$CONFIG" "$CONFIG_BAK"
  mv "$CONFIG_TMP" "$CONFIG"
  }
fi

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