#!/bin/sh
#

PROG="${0##*/}"

if [ ${#} -ne 2 ] || [ "${1}" = "-H" ]; then
   echo "usage: ${PROG} mime-type file"
   echo "Start freedesktop.org-configured viewer for given mime type"
   exit 1
fi

if [ -x /usr/bin/xdg-open ]; then
   exec /usr/bin/xdg-open "${2}"
fi

# The following logic attempts to find a viewer manually.

DT=

if [ -z "${DT}" ] \
   && [ -r "${HOME}"/.local/share/applications/defaults.list ]; then
   DT=$(grep -E "^${1}=" "${HOME}"/.local/share/applications/defaults.list)
   DT="${DT#*=}"
fi

if [ -z "${DT}" ] && [ -r /usr/share/applications/defaults.list ]; then
   DT=$(grep -E "^${1}=" /usr/share/applications/defaults.list)
   DT="${DT#*=}"
fi

if [ -z "${DT}" ] && [ -r /usr/share/applications/mimeinfo.cache ]; then
   DT=$(grep -E "^${1}=" /usr/share/applications/mimeinfo.cache)
   DT="${DT#*=}"
   DT="${DT%%;*}"
fi
   
EXEC=
if [ -n "${DT}" ]; then
   if [ -z "${EXEC}" ] \
      && [ -r "${HOME}"/.local/share/applications/"${DT}" ]; then
      EXEC=$(grep -E '^Exec=' "${HOME}"/.local/share/applications/"${DT}")
      EXEC="${EXEC#Exec=}"
   fi
   if [ -z "${EXEC}" ] && [ -r /usr/share/applications/"${DT}" ]; then
      EXEC=$(grep -E '^Exec=' /usr/share/applications/"${DT}")
      EXEC="${EXEC#Exec=}"
   fi
fi

if [ -z "${EXEC}" ]; then
   case "${1}" in
      application/pdf ) 
         if [ -x /bin/evince ]; then
            EXEC='/bin/evince %F'
         elif [ -x /usr/bin/gpdf ]; then
            EXEC='/usr/bin/gpdf %F'
         elif [ -x /usr/bin/acroread ]; then
            EXEC='/usr/bin/acroread %F'
         elif [ -x /usr/bin/xpdf ]; then
            EXEC='/usr/bin/xpdf %F'
         fi;;
   esac
fi

if [ -z "${EXEC}" ]; then
   echo "${PROG}: unable to find program to handle mime type ${1}" >&2
   exit 1
fi

if [ "${EXEC%\%*}" != "${EXEC}" ]; then
   # This won't always work right if %% sequences are used.  But it's as close
   # as I can get to correctness without writing an actual parser.
   function replace {
      str="${1}"
      while [ "${str%${2}*}" != "${str}" ]; do
         str="${str%${2}*}${3}${str##*${2}}"
      done
      echo "${str}"
   }

   EXEC=$(replace "${EXEC}" '%f' "${2}")
   EXEC=$(replace "${EXEC}" '%F' "${2}")
   EXEC=$(replace "${EXEC}" '%u' "${2}")
   EXEC=$(replace "${EXEC}" '%U' "${2}")
   if [ "${1%/*}" != "${1}" ]; then
      EXEC=$(replace "${EXEC}" '%d' "${2%/*}")
      EXEC=$(replace "${EXEC}" '%D' "${2%/*}")
      EXEC=$(replace "${EXEC}" '%n' "${2##*/}")
      EXEC=$(replace "${EXEC}" '%N' "${2##*/}")
   else
      EXEC=$(replace "${EXEC}" '%d' ".")
      EXEC=$(replace "${EXEC}" '%D' ".")
      EXEC=$(replace "${EXEC}" '%n' "${2}")
      EXEC=$(replace "${EXEC}" '%N' "${2}")
   fi

   # This won't always work right if %% sequences are used.  But it's as close
   # as I can get to correctness without writing an actual parser.
   function unimp {
      str="${1}"
      if [ "${str%${3}*}" != "${str}" ]; then
         echo "${PROG}: unimplemented ${3} parameter in ${1} from ${2}" >&2
         exit 1
      fi
   }

   unimp "${EXEC}" "${DT}" '%i'
   unimp "${EXEC}" "${DT}" '%c'
   unimp "${EXEC}" "${DT}" '%k'
   unimp "${EXEC}" "${DT}" '%v'
else
   # This doesn't seem to be legal, but I see some *.desktop files that don't
   # have any Exec parameter variables even though clearly should.  Workaround
   # it.
   EXEC="${EXEC} ${2}"
fi

shopt -s execfail

eval exec "${EXEC}"
exec 2>&1 # bash trashes fd 2 on failed exec; resurrect it
xmessage -buttons Close "NUU: mimeviewer: failed to execute command:
    ${EXEC}
Check \"Open With\" settings for \"PDF document\" on any PDF file using nautilus."
