if ! type "include" > /dev/null 2>&1; then
  include() {
  . "$(cd "$(dirname "$1")" && pwd)/${2}";
  };
fi
include "${BASH_SOURCE[0]}" ../../pragma_once.bash

if ! pragma_once ${BASH_SOURCE[0]}; then return 0;
  source ../../pragma_once.bash
fi


set -Eeo pipefail
#      -e	命令失败退出
#      -E	ERR trap 在函数中生效
#      -u	未定义变量报错
#      pipefail	pipeline 失败传播
#set -E



# -E 的作用是：让 ERR trap 在函数、子 shell 等上下文中也会触发

declare -gi G_PRINT_STACK_TRACE_COUNT=0

print_stack_trace() {

  printf "\n\n"
  local ret="${1}"
  local reason="${2}"

  G_Root="D:/proj/plant_sun_cat/build_script"


  local ts
  ts="$(TZ=Asia/Shanghai date '+%Y-%m-%d %H:%M:%S.%3N')"

  local pid="$$"
  local bashpid="${BASHPID:-}"
  local ppid="${PPID:-}"
  local pwd_now
  pwd_now="$(pwd 2>/dev/null || echo '<pwd-failed>')"

  local script_name="${BASH_SOURCE[1]:-${BASH_SOURCE[0]}}"
  local last_cmd="${BASH_COMMAND:-<unknown>}"

  local root_dir="${_library_root_dir_:-<empty>}"
  local g_root="D:/proj/plant_sun_cat/build_script"

  log_error "\n[#%d]【%s】ret=%d pid=%s bashpid=%s ppid=%s \npwd=%s \nscript=%s \ncmd=%s \nts=%s \nlibrary_root=%s" \
    "$G_PRINT_STACK_TRACE_COUNT" \
    "$reason" \
    "$ret" \
    "$pid" \
    "$bashpid" \
    "$ppid" \
    "$pwd_now" \
    "$script_name" \
    "$last_cmd" \
    "$ts" \
    "$root_dir"
    ((G_PRINT_STACK_TRACE_COUNT++)) || true




  local depth=${#FUNCNAME[@]}

  for ((i=0;i<depth;i++)); do
    local file="${BASH_SOURCE[$i]}"
    file="$(realpath "$file")"
    file="${file#${_library_root_dir_}}"
    file="${G_Root}/${file}"

    local func="${FUNCNAME[$i]}"

    if (( i == 0 )); then
      line="${BASH_LINENO[0]}"
    else
      line="${BASH_LINENO[$((i-1))]}"
    fi

    log_warn "  [%2d] [%s] file:///%s:%s" "$i" "$func" "$file" "$line"
  done

  exit 75
}

__on_err() {
  local ret="$1"
  local cmd="$2"
  local line="$3"

  print_stack_trace "$ret" "进程错误 cmd=$cmd line=$line"
}

trap '__on_err "$?" "$BASH_COMMAND" "$LINENO"' ERR

#trap 'print_stack_trace "进程错误"  ' ERR


#trap 'echo exit $? ' EXIT


