#!/bin/bash

# thisroot.* scripts should not be used to
# configure ROOT on Arch. Notify user and
# return an error

# default behaviour
__THIS_ROOT_ERROR_AS_WARNING__=0
__THIS_ROOT_RETURNCODE__=1
__THIS_ROOT_MESSAGE__='ERROR'
__THIS_ROOT_REGEX_TEST__='^(no|n|0|off)$'


function fail {
    printf '%s\n' "$1" >&2
    return "${2:-$1}"
}

# [FS#71639](https://bugs.archlinux.org/task/71639)
if [[ ! -z "${THIS_ROOT_ERROR_AS_WARNING}" ]]; then
  THIS_ROOT_ERROR_AS_WARNING=$(echo "${THIS_ROOT_ERROR_AS_WARNING}" | tr '[:upper:]' '[:lower:]')
  if [[ ! ${THIS_ROOT_ERROR_AS_WARNING} =~ ${__THIS_ROOT_REGEX_TEST__} ]]; then
    __THIS_ROOT_ERROR_AS_WARNING__=1
  fi
fi

if [[ ${__THIS_ROOT_ERROR_AS_WARNING__} -eq 1 ]]; then
  __THIS_ROOT_RETURNCODE__=0
  __THIS_ROOT_MESSAGE__='WARNING'
fi

__THIS_ROOT_CORE_MESSAGE__="""${__THIS_ROOT_MESSAGE__}: thisroot.sh type scripts are no longer supported.
They should never be used! This includes their other forms: thisroot.csh, thisroot.fish, etc."""

__THIS_ROOT_ERROR_EXTRA_MESSAGE__="""If you would prefer to see this error as a warning, please use the
environment variable 'THIS_ROOT_ERROR_AS_WARNING'.
For example, you may run your original command like so:
  THIS_ROOT_ERROR_AS_WARNING=1 mycommand
or even:
  THIS_ROOT_ERROR_AS_WARNING=ON mycommand"""

if [[ ${__THIS_ROOT_ERROR_AS_WARNING__} -eq 1 ]]; then
  __THIS_ROOT_FINAL_MESSAGE__="${__THIS_ROOT_CORE_MESSAGE__}"
else
  __THIS_ROOT_FINAL_MESSAGE__="""${__THIS_ROOT_CORE_MESSAGE__}
${__THIS_ROOT_ERROR_EXTRA_MESSAGE__=}"""
fi

fail "${__THIS_ROOT_FINAL_MESSAGE__}" ${__THIS_ROOT_RETURNCODE__}
