# set +o posix

quiet_safe_cd() {
  cd "$1" >/dev/null 2>&1 || {
    echo "Error: failed to cd to $1" >&2
    exit 1
  }
}

absdir() {
  quiet_safe_cd "${1%/*}/" && pwd -P
}

dirbasepath() {
  dir="$1"
  base="${2##*/}"
  echo "${dir}/${base}"
}

realpath() {
  path="$1"
  dir
  dest

  dir="$(absdir "${path}")"
  path="$(dirbasepath "${dir}" "${path}")"

  while [ -L "${path}" ]; do
    dest="$(readlink "${path}")"
    # if [[ "${dest}" == "/"* ]]
    case "${dest}" in
      "/"*) path="${dest}" ;;
      *) path="${dir}/${dest}" ;;
    esac
    dir="$(absdir "${path}")"
    path="$(dirbasepath "${dir}" "${path}")"
  done

  echo "${path}"
}
