#!/bin/bash
#
# pcmanfm-bookmarks-cleaner.sh
#
declare -r PCMANFM_BOOKMARKS_FILE=~/.config/gtk-3.0/bookmarks

function urldecode {
  # urldecode <string>
  local -r url_encoded="${1//+/ }"

  printf '%b' "${url_encoded//%/\\x}"
}

function rebuild_pcmanfm_bookmarks_file {
  local -r content="$1"

  local entry=
  local dir=
  while read -r entry ; do
    if [[ "${entry}" == 'file://'* ]] ; then
      dir="$( urldecode "${entry:7}" | cut -d' ' -f1 )" || return $?
      if [ -d "${dir}" ] ; then
        echo "OK: ${dir}" >&2
        echo "${entry}"
      else
        echo "REMOVE: ${dir}" >&2
      fi
    else
      echo "KEEP: ${entry}" >&2
      echo "${entry}"
    fi
  done <<<"${content}"
}

function pcmanfm_bookmarks_cleaner {
  local content=
  content="$( <"${PCMANFM_BOOKMARKS_FILE}" )" || return $?

  local newcontent=
  if newcontent="$( rebuild_pcmanfm_bookmarks_file "${content}" )" ; then
    if [ "${content}" = "${newcontent}" ] ; then
      echo "* OKAY: Configuration file already ok"
    else
      echo "* INFO: Fix configuration file"
      echo "${newcontent}" >"${PCMANFM_BOOKMARKS_FILE}"
    fi
  else
    echo "*** ERROR: While parsing configuration file." >&2
    return 100
  fi
}

pcmanfm_bookmarks_cleaner || exit $?

