#!/bin/bash
# 此文件记录了交叉编译构建gdb的过程
export BASE_DIR=$(pwd)
export SYSROOT=/opt/rootfs
export CC=/opt/pkg/tools/Xilinx/Vitis/2022.2/gnu/aarch32/lin/gcc-arm-linux-gnueabi/bin/arm-linux-gnueabihf-gcc
export CXX=/opt/pkg/tools/Xilinx/Vitis/2022.2/gnu/aarch32/lin/gcc-arm-linux-gnueabi/bin/arm-linux-gnueabihf-g++
export AR=/opt/pkg/tools/Xilinx/Vitis/2022.2/gnu/aarch32/lin/gcc-arm-linux-gnueabi/bin/arm-linux-gnueabihf-ar

export gmp_ver="6.3.0"
export mpfr_ver="4.2.2"
export expat_ver="2.6.0"
export expat_url="https://github.com/libexpat/libexpat/releases/download/R_2_6_0/expat-2.6.0.tar.gz"
export gdb_ver="11.2"
export INSTALL_ROOT_DIR="$(pwd)/sysroot"

# 浮点数运算库源码
cd "$BASE_DIR" || exit
wget -N "https://mirrors.kernel.org/gnu/gmp/gmp-$gmp_ver.tar.xz"
tar -xf "$BASE_DIR/gmp-$gmp_ver.tar.xz"
cd "$BASE_DIR/gmp-$gmp_ver" || exit
./configure \
  --prefix="$BASE_DIR/install/gmp" \
  --host=arm-linux-gnueabihf \
  --with-sysroot="$SYSROOT"
make -j$(nproc)
make install

# 多精度浮点数运算库源码
cd "$BASE_DIR" || exit
wget -N "https://mirrors.kernel.org/gnu/mpfr/mpfr-$mpfr_ver.tar.xz"
tar -xf "$BASE_DIR/mpfr-$mpfr_ver.tar.xz"
cd "$BASE_DIR/mpfr-$mpfr_ver" || exit

./configure \
  --prefix="$BASE_DIR/install/mpfr" \
  --host=arm-linux-gnueabihf \
  --with-gmp="$BASE_DIR/install/gmp" \
  --with-sysroot="$SYSROOT"
make -j$(nproc)
make install

# xml解析库
cd "$BASE_DIR" || exit
wget -N "$expat_url"
tar -xf "$BASE_DIR/expat-$expat_ver.tar.gz"
cd "$BASE_DIR/expat-$expat_ver" || exit

./configure \
  --host=arm-linux-gnueabihf \
  --prefix="$BASE_DIR/install/expat" \
  --enable-shared \
  --enable-static \
  --with-sysroot="$SYSROOT"

make -j$(nproc)
make install

# gdb
cd "$BASE_DIR" || exit
wget -N "https://mirrors.kernel.org/gnu/gdb/gdb-$gdb_ver.tar.xz"
tar -xf "$BASE_DIR/gdb-$gdb_ver.tar.xz"

cd "$BASE_DIR/gdb-$gdb_ver" || exit
./configure \
  --prefix="$BASE_DIR/install/gdb" \
  --with-gmp="$BASE_DIR/install/gmp" \
  --with-mpfr="$BASE_DIR/install/mpfr" \
  --with-expat="$BASE_DIR/install/expat" \
  --enable-targets=all \
  --enable-gdbserver \
  --host=arm-linux-gnueabihf \
  --with-sysroot="$SYSROOT" \
  --disable-sim \
  CFLAGS="-I$BASE_DIR/install/gmp/include -L$BASE_DIR/install/gmp/lib" \
  CXXFLAGS="-I$BASE_DIR/install/gmp/include -L$BASE_DIR/install/gmp/lib"

# 编译和安装
make -j$(nproc)
make install

mkdir $INSTALL_ROOT_DIR
cp -r "$BASE_DIR/install/gdb/"* "$INSTALL_ROOT_DIR"
cp -r "$BASE_DIR/install/gmp/"* "$INSTALL_ROOT_DIR"
cp -r "$BASE_DIR/install/mpfr/"* "$INSTALL_ROOT_DIR"
cp -r "$BASE_DIR/install/expat/"* "$INSTALL_ROOT_DIR"

#export LD_LIBRARY_PATH=/home/root/sysroot/lib:$LD_LIBRARY_PATH
#sudo cp -a sysroot/* /
