#!/bin/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
###############################################################################

NOWOOF=true
RAPPDIR=/usr/local/apps/RStudio-1.1.463
RAPPDESC="IDE for R"
MIMEPACKAGE=/usr/share/mime/packages/rstudio.xml

# -----------------------------------------------------------------------------
# Associate ROX 'SendTo/OpenWith' with ROX-App
# -----------------------------------------------------------------------------
rappname=${RAPPDIR##*/}

# Fatdog64 doinst.sh calls update-mime-database before this script.

mkdir_all_sendto_type_folders() {
  local i

  # Creates missing folders using contents of 'globs' file
  for i in `grep ":" "$Globs_PATH" | cut -f1 -d ':' | tr '/' '_' | uniq`; do
    [ ! -d "${RC_PATH}/.${i}" ] && mkdir "${RC_PATH}/.${i}"
  done

  # Creates missing folders using contents of 'types' file
  for i in `cat "$Types_PATH" | tr '/' '_' | uniq`; do
    [ ! -d "${RC_PATH}/.${i}" ] && mkdir "${RC_PATH}/.${i}"
  done

  [ ! -d "${RC_PATH}/.inode_unknown" ] && mkdir "${RC_PATH}/.inode_unknown"
}

symlink_all_folders() {
  local i
  # Creates symlink to $RAPPDIR in every folder
  for i in `find "$(realpath "${RC_PATH}")" -maxdepth 1 -type d -iname ".*"`; do
    [ ! -L "${i}/$rappname" ] && ln -s "$RAPPDIR" "${i}/$rappname"
  done
  [ ! -L "${RC_PATH}/$rappname" ] && ln -s "$RAPPDIR" "${RC_PATH}/$rappname"
}

mkdir_and_symlink_package_mime_type_folders() { # $1-link-target-ROX-App $2-rox-sendto-path
  awk -v TARGET="$1" -v NAME="${1##*/}" -v ROXSENDTOPATH="$2" '
    /<mime-type type=/ {
      type = substr($2, 1 + index($2, "="))
      gsub(/[\x22\x27>]/, "", type)
      gsub("/", "_", type)
      # for sendto or openwith link
      dir[1] = ROXSENDTOPATH"/."type
      # link name path
      name[1] = dir[1]"/"NAME
      # for mime-type link
      dir[2] = ROXSENDTOPATH; sub("/[^/]+$", "", dir[2])
      dir[2] = dir[2]"/MIME-types"
      name[2] = dir[2]"/"type
      for(i = 1; i <= 2; i++) {
        dirq[i] = "\x22" dir[i] "\x22"
        namq[i] = "\x22" name[i] "\x22"
        # add sendto / openwith and mime-type links
        print "! [ -d " dirq[i] " ] && mkdir -p " dirq[i] | "sh"
        print "! [ -L " namq[i] " ] && ln -sfT \x22" TARGET "\x22 " namq[i] | "sh"
        shelled = 1
      }
    }
    END { if(shelled) close("sh") }
  ' "$MIMEPACKAGE"
}

if [ "`pwd`" != /  -a "$NOWOOF" != true ]; then # Woof

  # Note: For Fatdog64 /root/.config => /etc/xdg, see LOC1=
  RC_PATH="./root/.config/rox.sourceforge.net/OpenWith"
  Globs_PATH="./usr/share/mime/globs"
  Types_PATH="./usr/share/mime/types"

  mkdir_all_sendto_type_folders
  symlink_all_folders

else # user, including root

  # By design LOC1 needs root write access and affects all users.
  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" "$LOC2" "$LOC3"; do
    [ -d "$i" -a -w "$i" ] && { RC_PATH="$i"; break; }
  done
  Globs_PATH="/usr/share/mime/globs"
  Types_PATH="/usr/share/mime/types"

  if [ -d "$RC_PATH" ]; then

    if [ -s "$MIMEPACKAGE" ]; then
      mkdir_and_symlink_package_mime_type_folders "$RAPPDIR" "$RC_PATH"

      # Mime sync for Fatdog64. (currently disregards /usr/local/...)
      [ -x /usr/bin/fatdog-sync-mime.sh ] && /usr/bin/fatdog-sync-mime.sh
    # else
    #   # Overkill
    #   mkdir_all_sendto_type_folders
    #   symlink_all_folders
    fi
  fi

fi
# -----------------------------------------------------------------------------
# TODO something like mkdir_and_symlink_package_mime_type_folders but for Thunar.

# Associate custom action with Thunar
if [ "`pwd`" = "/" -o "$NOWOOF" = true ]; then
  if [ `which thunar 2>/dev/null` ] || [ `which Thunar 2>/dev/null` ]; then
    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>$rappname</name>" "$CONFIG" >/dev/null || {
      grep -v '^</actions>' "$CONFIG" > "$CONFIG_TMP"
      echo "<action>
	<icon>$rappname</icon>
	<name>$rappname</name>
	<command>$RAPPDIR/AppRun %F</command>
	<description>$RAPPDESC</description>
	<patterns>*</patterns>
	<directories/>
	<text-files/>
</action>
</actions>" >> "$CONFIG_TMP"
      mv "$CONFIG" "$CONFIG_BAK"
      mv "$CONFIG_TMP" "$CONFIG"
    }
    else
      mkdir -p "${CONFIG%/*}"
      echo "<?xml encoding=\"UTF-8\" version=\"1.0\"?>
<actions>
<action>
	<icon></icon>
	<name>$rappname</name>
	<command>$RAPPDIR/AppRun %F</command>
	<description>$RAPPDESC</description>
	<patterns>*</patterns>
	<directories/>
	<text-files/>
</action>
</actions>" > "$CONFIG"
    fi
  fi
fi

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

# Create shortcut on pinboard/desktop
if [ "$PKG_INSTALL_OPTIONS" = "${PKG_INSTALL_OPTIONS#*no-shortcut}" ] &&
  [ "$PKG_INSTALL_OPTIONS" = "${PKG_INSTALL_OPTIONS#*say-no}" ]
then
  if [ "`pwd`" = / -o "$NOWOOF" = true ]; then
    "$RAPPDIR/createshortcut" # $PKG_INSTALL_OPTIONS applies
  fi
fi

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