#!/bin/bash
# 2025-09-28 11:15 created by niujiuru

set -e
set -o pipefail

ver_num="1.0.0.1"
cur_dir="$(pwd)"
pre_dir="$(dirname "$cur_dir")"

pkgname="rtu_linux_modules"
pkg_dir="${cur_dir}/${pkgname}"
pkg_tar="${cur_dir}/${pkgname}_${ver_num}.tar.gz"

rm -rf "${pkg_dir}" "${pkg_tar}"
mkdir -p "${pkg_dir}"

echo "1, Creating config directory and copying config files..."
mkdir -p "${pkg_dir}/config"
cp -rf "${pre_dir}/baseapp/config.ini" "${pkg_dir}/config/"
cp -rf "${pre_dir}/sshd/server/sshd_cfg.ini" "${pkg_dir}/config/"

echo "2, Creating script directory and copying scripts..."
mkdir -p "${pkg_dir}/script"
cp -rf "${pre_dir}/scripts/"* "${pkg_dir}/script/"
chmod a+x "${pkg_dir}/script/"*

echo "3, Creating lib directory and copying library files..."
mkdir -p "${pkg_dir}/lib"
use_cam="all_supported"  # 使用海康相机: "hk_takephoto"; 使用大华相机: "dh_takephoto"; 同时使用所有: "all_supported"
if [ "$use_cam" = "all_supported" ] || [ "$use_cam" = "hk_takephoto" ]; then
  cam_dir="${pre_dir}/hk_takephoto"
  cp -rf "${cam_dir}/lib/armv7hf/"* "${pkg_dir}/lib/"
fi
if [ "$use_cam" = "all_supported" ] || [ "$use_cam" = "dh_takephoto" ]; then
  cam_dir="${pre_dir}/dh_takephoto"
  cp -rf "${cam_dir}/lib/armv7hf/"* "${pkg_dir}/lib/"
fi

echo "4, Building hkcam_reset..."
if [ "$use_cam" = "all_supported" ] || [ "$use_cam" = "hk_takephoto" ]; then
  cam_dir="${pre_dir}/hk_takephoto"
  make -C "${cam_dir}" clean
  make -C "${cam_dir}" target=armv7hf hkcam_reset.out
  cp -rf "${cam_dir}/hkcam_reset.out" "${pkg_dir}/"
  make -C "${cam_dir}" clean
else
  echo "  Skipping hkcam_reset build (not U-port camera)!"
fi

echo "5, Building ${pkgname}..."
cd ${pre_dir}
make -C "${pre_dir}" clean
make -C "${pre_dir}" target=armv7hf
cd ${cur_dir}
cp -rf "${pre_dir}/yfkj_sshd.out"  "${pkg_dir}/"
cp -rf "${pre_dir}/${pkgname}.out" "${pkg_dir}/"
make -C "${pre_dir}" clean

echo "6, Packaging into ${pkg_tar}..."
tar -czvf "${pkg_tar}" -C "${cur_dir}" "${pkg_dir##*/}"

# 清理临时目录
rm -rf "${pkg_dir}"

echo "✅ Package build completed successfully: ${pkg_tar}"
exit 0
