#!/usr/bin/env bash
set -euo pipefail

PKG_NAME="controller"
PKG_VERSION="$(date +%Y%m%d%H%M)"
ARCH="arm64"
MAINTAINER="LYQ<liyq@ntiov.com>"
DESCRIPTION="Binary package of remote controller nodes for robot (ROS2 Humble)."
INSTALL_DIR="/opt/${PKG_NAME}"
WORKDIR="$(pwd)/deb_build"
INSTALL_SRC="$(pwd)/install"

rm -rf "${WORKDIR}"
mkdir -p "${WORKDIR}/${INSTALL_DIR}"
mkdir -p "${WORKDIR}/DEBIAN"

cp -a "${INSTALL_SRC}/." "${WORKDIR}/${INSTALL_DIR}/"

# control 文件
cat > "${WORKDIR}/DEBIAN/control" <<EOF
Package: ${PKG_NAME}
Version: ${PKG_VERSION}
Section: misc
Priority: optional
Architecture: ${ARCH}
Essential: no
Maintainer: ${MAINTAINER}
Depends: ros-humble-ros-base, libc6 (>= 2.34)
Description: ${DESCRIPTION}
EOF

# 创建 start_all.sh
cat > "${WORKDIR}/${INSTALL_DIR}/start_all.sh" <<EOF
#!/bin/bash
set -e

# 加载 ROS2 系统环境
source /opt/ros/humble/setup.bash

# 加载打包的工作空间环境
source ${INSTALL_DIR}/local_setup.bash

# 启动多个节点
ros2 run radio_ctrl radio_ctrl_node &
ros2 run mc mc_node &
ros2 run ctrl_arbiter ctrl_arbiter_node &
ros2 run mqtt_report mqtt_report_node &
ros2 run rtk rtk_node &
ros2 run pub_gps pub_gps_node &

wait
EOF
chmod +x "${WORKDIR}/${INSTALL_DIR}/start_all.sh"

# systemd 服务文件
mkdir -p "${WORKDIR}/etc/systemd/system"
cat > "${WORKDIR}/etc/systemd/system/${PKG_NAME}.service" <<EOF
[Unit]
Description=Remote Controller Nodes
After=network.target

[Service]
Type=simple
User=root
Environment="ROS_DISTRO=humble"
ExecStart=${INSTALL_DIR}/start_all.sh
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF

# postinst 脚本（安装后执行）
cat > "${WORKDIR}/DEBIAN/postinst" <<EOF
#!/bin/bash
set -e

systemctl daemon-reload
systemctl enable ${PKG_NAME}.service

exit 0
EOF
chmod 755 "${WORKDIR}/DEBIAN/postinst"

# postrm 脚本（卸载时执行）
cat > "${WORKDIR}/DEBIAN/postrm" <<EOF
#!/bin/bash
set -e

systemctl stop ${PKG_NAME}.service || true
systemctl disable ${PKG_NAME}.service || true
systemctl daemon-reload

exit 0
EOF
chmod 755 "${WORKDIR}/DEBIAN/postrm"

# 打包
dpkg-deb --build "${WORKDIR}" "${PKG_NAME}_${PKG_VERSION}_${ARCH}.deb"

echo "生成 ${PKG_NAME}_${PKG_VERSION}_${ARCH}.deb"
