#!/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 foxy)."
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"

# 复制 ROS2 install 文件
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-foxy-ros-base, logrotate
Description: ${DESCRIPTION}
EOF

# ============================
# 创建 can.sh (root 执行)
# ============================
cat > "${WORKDIR}/${INSTALL_DIR}/can.sh" <<'EOF'
#!/bin/bash
# Script: can.sh
# Description: Configures CAN interface can0 on startup

if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root"
    exit 1
fi

if ip link show can0 &> /dev/null; then
    ip link set can0 down
fi

modprobe can
modprobe can_raw
modprobe mttcan

ip link set can0 type can bitrate 500000
ip link set up can0

if [[ $? -ne 0 ]]; then
    echo "Error configuring CAN interface can0"
    exit 1
fi

echo "CAN interface can0 configured successfully"
exit 0
EOF

chmod +x "${WORKDIR}/${INSTALL_DIR}/can.sh"

# ============================
# 创建 start_all.sh (aiec 用户执行)
# ============================
cat > "${WORKDIR}/${INSTALL_DIR}/start_all.sh" <<EOF
#!/bin/bash
set -e

# 加载 ROS2 系统环境
source /opt/ros/foxy/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"

# CAN 配置服务 (root 执行)
cat > "${WORKDIR}/etc/systemd/system/${PKG_NAME}-can.service" <<EOF
[Unit]
Description=Configure CAN interface can0
After=network.target

[Service]
Type=oneshot
ExecStart=${INSTALL_DIR}/can.sh
RemainAfterExit=yes
User=root

[Install]
WantedBy=multi-user.target
EOF

# ROS2 节点服务 (aiec 用户执行，日志写文件)
cat > "${WORKDIR}/etc/systemd/system/${PKG_NAME}.service" <<EOF
[Unit]
Description=Remote Controller Nodes
After=network.target ${PKG_NAME}-can.service
Requires=${PKG_NAME}-can.service

[Service]
Type=simple
User=aiec
Environment="ROS_DISTRO=foxy"
ExecStart=${INSTALL_DIR}/start_all.sh
Restart=on-failure
RestartSec=2
StandardOutput=append:/var/log/${PKG_NAME}/${PKG_NAME}.log
StandardError=append:/var/log/${PKG_NAME}/${PKG_NAME}.log

[Install]
WantedBy=multi-user.target
EOF

# ============================
# logrotate 配置
# ============================
mkdir -p "${WORKDIR}/etc/logrotate.d"
cat > "${WORKDIR}/etc/logrotate.d/${PKG_NAME}" <<EOF
/var/log/${PKG_NAME}/${PKG_NAME}.log {
    daily
    rotate 14
    compress
    missingok
    notifempty
    copytruncate
    dateext
    dateformat -%Y%m%d
}
EOF

# ============================
# postinst 启用服务
# ============================
cat > "${WORKDIR}/DEBIAN/postinst" <<EOF
#!/bin/bash
set -e

# 创建日志目录
mkdir -p /var/log/${PKG_NAME}
chown aiec:aiec /var/log/${PKG_NAME}

systemctl daemon-reload
systemctl enable ${PKG_NAME}-can.service
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 stop ${PKG_NAME}-can.service || true
systemctl disable ${PKG_NAME}-can.service || true
systemctl daemon-reload

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

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

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