#!/bin/sh
# commands used:
# - column
# - pacman

init_variables() {
  COMMAND=${0##*/}

  TYPE=
}

show_usage() {
  cat <<- EOF
	usage: ${COMMAND} [<options>]

  Report the packages and plugins with different versions between the one installed on the
  system and the one listed in the docs

	Options:
	  -h    show this message only
	EOF
}

parse_command_line() {
  while getopts dh OPT; do
    case "${OPT}" in
      h) show_usage; exit 0 ;;
      ?) exit_error ;;
    esac
  done

  shift "$((OPTIND - 1))"
}

# shellcheck disable=SC2120
exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  echo "Try '${COMMAND} -h' for more information."
  exit 1
} >&2

docs_version() {
  ITEM="$1"

  sed -n "s#^| ${ITEM} .*| \[\(.*\)\].*#\1#p" "doc/${TYPE}.md"
}

pacman_version() {
  PACKAGE="$1"

  PACMAN_INFO=$(
    pacman -Qi "${PACKAGE}" 2> /dev/null
  )

  if [ -z "${PACMAN_INFO}" ]; then
    # try with -git suffix if package couldn't be found
    PACMAN_INFO=$(
      pacman -Qi "${PACKAGE}-git" 2> /dev/null
    )
  fi

  if [ -z "${PACMAN_INFO}" ]; then
    # try with -bin suffix if package couldn't be found
    PACMAN_INFO=$(
      pacman -Qi "${PACKAGE}-bin" 2> /dev/null
    )
  fi

  if [ -z "${PACMAN_INFO}" ]; then
    echo 'unknown'
    return
  fi

  # extract version without the release number
  echo "${PACMAN_INFO}" \
    | sed -n 's/^Version *: \(.*\)\-[0-9]*/\1/p'
}

report_item() {
  VERSION_INSTALLED=$( pacman_version "$1" )

  VERSION_DOCS=$( docs_version "$1" )

  if [ "${VERSION_INSTALLED}" = "${VERSION_DOCS}" ]; then
    return
  fi

  printf '%s %s %s\n' \
    "$1" \
    "${VERSION_DOCS}" \
    "${VERSION_INSTALLED}"
}

list_items() {
  sed -n 's#^| \([a-z][^ ]*\) .*#\1#p' "doc/${TYPE}.md"
}

report_all() {
  {
    for TYPE in PACKAGES PLUGINS; do
      list_items \
        | while read -r ITEM; do
            report_item "${ITEM}"
          done
    done
  } \
    | sort \
    | column -t
}

init_variables
parse_command_line "$@"

report_all
