#!/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




# shellcheck source=./common.bash
# shellcheck source=./compress.bash
include "${BASH_SOURCE[0]}" ./common.bash
include "${BASH_SOURCE[0]}" ./compress.bash


download_cached_as() {
  local url="$1"
  local dest_dir="$2"
  local filename="$3"
  local cache_filepath="$4"

  # 参数检查
  if [[ -z "$url" || -z "$dest_dir" || -z "$filename" || -z "$cache_filepath" ]]; then
    echo "[ERROR] 用法: download_cached_as <url> <dest_dir> <filename> <cache_filename>" >&2
    return 1
  fi

  # 检查全局缓存目录变量
  if [[ -z "${_wget_cache_dir_}" ]]; then
    echo "[ERROR] 全局缓存目录变量 _wget_cache_dir_ 未设置" >&2
    return 1
  fi

  # 创建目标目录
  mkdir -p "$dest_dir" || {
    echo "[ERROR] 创建目标目录失败: $dest_dir" >&2
    return 1
  }

  # 创建缓存目录
  mkdir -p "$_wget_cache_dir_" || {
    echo "[ERROR] 创建缓存目录失败: $_wget_cache_dir_" >&2
    return 1
  }

  # 目标文件路径
  local dest_file="${dest_dir%/}/$filename"

  # 缓存文件路径
  local cache_file="${_wget_cache_dir_%/}/$cache_filepath"
  local cache_dir="$(dirname "$cache_file")"
  check_and_create_dir "$cache_dir"

  # 如果目标文件已经存在，直接跳过
  if [[ -f "$dest_file" ]]; then
    echo "[CACHE] 目标文件已存在，跳过: $dest_file"
    return 0
  fi

  # 如果缓存文件不存在，则先下载到缓存目录
  if [[ ! -f "$cache_file" ]]; then
    echo "[DOWNLOAD] $url"
    echo "[CACHE TO] $cache_file"

    local tmp_cache_file="${cache_file}.tmp.$$"

    wget -O "$tmp_cache_file" "$url"
    local rc=$?

    if [[ $rc -ne 0 ]]; then
      echo "[ERROR] 下载失败: $url" >&2
      rm -f "$tmp_cache_file"
      return $rc
    fi

    mv -f "$tmp_cache_file" "$cache_file" || {
      echo "[ERROR] 缓存文件写入失败: $cache_file" >&2
      rm -f "$tmp_cache_file"
      return 1
    }

    echo "[OK] 已缓存: $cache_file"
  else
    echo "[CACHE] 命中缓存: $cache_file"
  fi

  # 从缓存复制到目标位置
  cp -f "$cache_file" "$dest_file" || {
    echo "[ERROR] 从缓存复制到目标失败: $cache_file -> $dest_file" >&2
    return 1
  }

  echo "[OK] 已复制到目标: $dest_file"
  return 0
}


get_src_from_wget(){
  if [ "$#" -ne 3 ]; then
    echo "用法: get_src_from_wget <ret_var> <dest_dir> <url>"
    echo "  <ret_var> - 存储返回路径的变量名"
    echo "  <build_dir> - 解压到的目标目录，也是用于构建的目录"
    echo "  <url> - 要下载的文件的URL"
    echo "示例："
    echo '  src_dir=""'
    echo '  get_src_from_wget src_dir $_build_dir $url'
    return 1
  fi

  local -n ret=$1
  local dest_dir=$2
  local url=$3
  local suffix
  get_suffix suffix "$url"
  local file_name=$(basename "$url")
  local name=$(basename "$url" .$suffix)
  local zip_file_path="${_wget_cache_dir_}/$file_name"
  ret="$dest_dir/$name"
  if [ -d $ret ]; then
     rm -rf $ret
  fi

  if [ ! -e "$zip_file_path" ]; then
    _network_status_=$?  # 获取 wget 命令的返回值
    if [ $_network_status_ -ne 0 ]; then
      # 如果 wget 命令失败，打印错误信息并要求用户手动下载
      echo "错误: 网络不通，放弃下载源码包，请手动下载源码包并放到以下路径："
      echo "路径: ${zip_file_path}"
      echo "请下载源码包并将其放置在该目录下，然后重新运行脚本。"
      exit 1  # 退出脚本
    fi
    exec_record_fast_fail "wget -P ${_wget_cache_dir_} $url"
  fi

#  if [ ! -e $zip_file_path ]; then
#     exec_record "wget -P ${_wget_cache_dir_} $url"
#  fi
  exec_record_fast_fail "extract $suffix $zip_file_path $dest_dir"
}






configure_gnu_ex() {
  if [ "$#" -lt 1 ]; then
    echo "用法: configure_gnu_ex <src_dir> \"<opts_string>\""
    return 1
  fi
  local src_dir="$1"
  local opts="$2"
  local build_dir="$src_dir/build"
  exec_record "rm -rf \"${src_dir}/build\""
  exec_record "mkdir -p \"$build_dir\""
  exec_record "cd \"$build_dir\""
  local print_opts
  print_opts="$(printf "%s" "$opts" | tr -s ' ' '\n')"
  log_info "【$(pwd)/configure"
  log_info "${print_opts}"
  log_info "】"
  exec_record_fast_fail "../configure ${opts}"


  if [ $? -ne 0 ]; then
    print_remain_args "src_dir:${src_dir} configure failed" "$opts"
    exit 1
  fi
}



configure_gnu() {
  if [ "$#" -lt 1 ]; then
    echo "用法: configure_gnu <src_dir> [additional configure options...]"
    return 1
  fi
  local src_dir="$1"
  shift
  local opts_string="$*"
  configure_gnu_ex "$src_dir" "$opts_string"
}



configure_gnu_zip_ex() {
  # 参数检查
  if [ "$#" -lt 1 ]; then
    echo "用法: configure_gnu_zip_ex <url> \"<opts_string>\""
    echo "  <url> - 要下载并构建的源代码的 URL"
    echo "  <opts_string> - 传递给 configure 的额外参数（字符串）"
    echo "示例："
    echo '  configure_gnu_zip_ex http://example.com/source.tar.gz "--prefix=/usr/local --enable-foo"'
    return 1
  fi
  local url="$1"
  local opts="$2"
  local src_dir=""
  get_src_from_wget src_dir "${_build_dir_}" "$url"
  log_info "$src_dir" "$opts"
  configure_gnu_ex "$src_dir" "$opts"
}

configure_gnu_zip() {
  if [ "$#" -lt 1 ]; then
    echo "用法: configure_gnu_zip <url> [additional build options...]"
    return 1
  fi
  local url="$1"
  shift
  local opts_string="$*"
  configure_gnu_zip_ex "$url" "$opts_string"
}







build_gnu_zip_ex() {
  if [ "$#" -lt 1 ]; then
    echo "用法: build_gnu_zip_ex <url> \"<opts_string>\""
    return 1
  fi
  local url="$1"
  local opts="$2"
  configure_gnu_zip_ex "$url" "$opts"
  exec_record_fast_fail "make -j $(nproc)"
  exec_record_fast_fail "make install -j $(nproc)"
}

build_gnu_zip() {
  if [ "$#" -lt 1 ]; then
    echo "用法: build_gnu_zip <url> [opts...]"
    return 1
  fi
  local url="$1"
  shift
  local opts_string="$*"
  build_gnu_zip_ex "$url" "$opts_string"
}




return 0