#!/bin/bash

# command line utility to find plugins using a specified shared folder

OMV_CONFIG_FILE="/etc/openmediavault/config.xml"

search="$1"

# Check for empty search string
if [ -z "${search}" ]; then
  echo "No search string"
  exit 1
fi

# Find sharedfolder uuid
uuid=$(xmlstarlet sel -t -m "/config/system/shares/sharedfolder[name='${search}']" -v "uuid" ${OMV_CONFIG_FILE})

# If no shared folders are found with the search term then exit
if [ -z "${uuid}" ]; then
  echo "No entry found for search string"
  exit 2
fi

# Search for uuid in all elements
elements=$(grep ${uuid} ${OMV_CONFIG_FILE} | awk -F'[<>]' '{print $2}' | uniq)

# Dump every element path in the document once; each iteration below only
# filters this cached list rather than re-parsing the whole config file.
alllocations=$(xmlstarlet el -u ${OMV_CONFIG_FILE})

show=""

# Check all elements for uuid
for element in $elements; do

  # Get list of all elements with element in location
  elementlist=$(echo "${alllocations}" | grep ${element} | uniq)

  # check all locations for uuid
  for searchelement in $elementlist; do

    # remove element from location
    parent=${searchelement%/$element}

    # search for uuid in config file using location
    plugin=$(xmlstarlet sel -t -m "/${parent}[${element}='${uuid}']" -v "${element}" ${OMV_CONFIG_FILE})

    # if found then add to display
    if [ -n "${plugin}" ]; then
      show="${show}${parent} "
    fi
  done
done

# Display unique results
unique=$(echo "${show}" | tr ' ' '\n' | sort -u | grep -v 'shares/sharedfolder' | sed 's/config\///' | sed 's/\//->/g')

for output in $unique; do
  if [ -n "${output}" ]; then
    echo ${output}
  fi
done

exit 0
