#!/bin/bash
# shellcheck disable=SC2155
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; fi
include "${BASH_SOURCE[0]}" ./global_rely/export.bash
# shellcheck source=./global_rely/export.bash


exec_record() {
  local cmd="$1"
  local start_time=$(date '+%Y-%m-%d %H:%M:%S.%3N')
  local start_ts=$(date +%s.%3N)
  log_info "[$(pwd)] exec: $cmd  "
  eval "$cmd"
  local ret=$?
  local end_time=$(date '+%Y-%m-%d %H:%M:%S.%3N')
  local end_ts=$(date +%s.%3N)
  local duration=$(awk "BEGIN {print $end_ts - $start_ts}")
  if [ $ret -ne 0 ]; then
    local pretty_cmd=$(printf '%s\n' "$cmd" | sed 's/ --/\n--/g')
    log_error "$(pwd):cmd failed: $pretty_cmd, duration ${duration}s"
  else
    log_info "ok duration ${duration}s"
  fi
  return $ret
}

exec_record_fast_fail() {
  local cmd="$1"
  local log_file="$LOG_PATH"
  local start_time
  local start_ts
  local end_time
  local end_ts
  local duration
  local ret
  local pretty_cmd

  start_time=$(date '+%Y-%m-%d %H:%M:%S.%3N')
  start_ts=$(date +%s.%3N)

  log_info "[$(pwd)] exec: $cmd"

  {
    echo "[CMD-BEGIN] $start_time"
    echo "[PWD] $(pwd)"
    echo "[CMD] $cmd"
    eval "$cmd"
    ret=$?
    echo "[CMD-END] ret=$ret"
    exit $ret
  } 2>&1 | tee -a "$log_file"

  ret=${PIPESTATUS[0]}

  end_time=$(date '+%Y-%m-%d %H:%M:%S.%3N')
  end_ts=$(date +%s.%3N)
  duration=$(awk "BEGIN {print $end_ts - $start_ts}")

  if [ $ret -ne 0 ]; then
    pretty_cmd=$(printf '%s\n' "$cmd" | sed 's/ --/\n--/g')
    log_error "$(pwd):cmd failed: $pretty_cmd, duration ${duration}s"
  else
    log_info "ok duration ${duration}s"
  fi

  return $ret
}


exec_record_fast_fail_no_log() {
  local cmd="$1"
  exec_record "$cmd"
  local ret=$?
  if [ $ret -ne 0 ]; then
    exit $ret
  fi
}


append_rpath() {
  if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: update_rpath <directory> <rpath_value>"
    return 1
  fi
  DIR_PATH="$1"
  RPATH_VALUE="$2"
  if [ ! -d "$DIR_PATH" ]; then
    echo "Error: Directory '$DIR_PATH' does not exist."
    return 1
  fi
  find "$DIR_PATH" -type f -exec file {} \; | grep -E 'ELF|shared object' | while read -r line; do
    #find "$DIR_PATH" -type f ! -name "*.o" | parallel file {} | grep -E 'ELF|shared object' | while read -r line; do
    FILE_PATH=$(echo "$line" | cut -d: -f1)
    RPATH=$(readelf -d "$FILE_PATH" | grep -i rpath)
    if [ ! -z "$RPATH" ]; then
      CURRENT_RPATH=$(readelf -d "$FILE_PATH" | grep -i rpath | awk '{print $2}' | tr -d '[]')
      NEW_RPATH="$CURRENT_RPATH:$RPATH_VALUE"
    else
      NEW_RPATH="$RPATH_VALUE"
    fi
    patchelf --set-rpath "$NEW_RPATH" "$FILE_PATH"
    # 验证修改是否成功
    if [ $? -eq 0 ]; then
      echo "Updated rpath for: $FILE_PATH"
    else
      echo "Error: Failed to update rpath for $FILE_PATH"
    fi
  done
}


merge_args(){
    local -n ret=$1
    local t=$2
    local list=""
    shift 2
    for param in "$@"; do
        list="${list}${list:+$t}$param"
    done
    ret="$list"
}



#load_toolchain() {
#  p=$1 # 工具链根路径
#  n=$2 # 工具链架构名三元组
#  local d="${p}/${n}"
#  local d2="${p}/${n}/usr"
#
#  local libs="$d2/lib:$d2/lib64:${p}/lib:${p}/lib64"
#  # exe运行时查找库的路径
#  export LD_LIBRARY_PATH="$libs${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
#  export LIBRARY_PATH="$libs${LIBRARY_PATH:+:$LIBRARY_PATH}"
#  # exe查找路径
#  export PATH="${p}/bin${PATH:+:$PATH}"
#}

load_toolchain() {
  local p="$1" # 工具链根路径（prefix）
  local n="$2" # 三元组目录名
  local d="${p}/${n}"

  log_info "load_toolchain path: ${p}  三元组: ${n}"
  # 兼容两种布局：
  # 1) prefix/<triplet>/usr/...
  # 2) prefix/<triplet>/sysroot/usr/...
  local d2="${d}/usr"
  if [[ ! -d "$d2" && -d "${d}/sysroot/usr" ]]; then
    d2="${d}/sysroot/usr"
  fi

  # 如果还是不存在，就直接跳过
  local libs
  if [[ ! -d "$d2" ]]; then
    log_warn "skip load_toolchain: no usr found under ${d2}"
    libs="${p}/lib:${p}/lib64"
  else
    libs="${d2}/lib:${d2}/lib64:${p}/lib:${p}/lib64"
  fi


  export LD_LIBRARY_PATH="${libs}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
  export LIBRARY_PATH="${libs}${LIBRARY_PATH:+:$LIBRARY_PATH}"
  export PATH="${p}/bin${PATH:+:$PATH}"

}

return 0