#!/bin/bash

# IRIS_FODIS 项目打包脚本
# 打包成 Debian 包

VERSION=1.1
PROJECT_NAME="iris-fodis"
PACKAGE_NAME="${PROJECT_NAME}_V${VERSION}.deb"
BUILD_DIR="build"
DEB_DIR="Debpack_iris_fodis"

# 检查是否在正确目录
if [ ! -f "CMakeLists.txt" ]; then
    echo "错误：请在项目根目录运行此脚本"
    exit 1
fi

echo "========================================="
echo "IRIS_FODIS 打包脚本 v${VERSION}"
echo "========================================="

# 1. 构建项目
echo ""
echo "[1/5] 开始构建项目..."

# 清理旧的 build 目录并重新创建
#rm -rf $BUILD_DIR
mkdir -p $BUILD_DIR

cd $BUILD_DIR
cmake ..
#if [ $? -ne 0 ]; then
#    echo "错误：cmake 配置失败"
#    exit 1
#fi

# 执行 make
make -j$(nproc)
if [ $? -ne 0 ]; then
    echo "错误：构建失败"
    exit 1
fi
cd ..

# 检查构建产物
if [ ! -f "${BUILD_DIR}/IRIS_FODIS" ]; then
    echo "错误：构建产物不存在"
    exit 1
fi
echo "构建完成"

# 2. 创建打包目录
echo ""
echo "[2/5] 创建打包目录..."
rm -rf $DEB_DIR
mkdir -p $DEB_DIR

# 3. 复制可执行文件和脚本文件
echo ""
echo "[3/5] 复制文件..."
mkdir -p ${DEB_DIR}/home/pi/bin
cp ${BUILD_DIR}/IRIS_FODIS ${DEB_DIR}/home/pi/bin/
chmod +x ${DEB_DIR}/home/pi/bin/IRIS_FODIS

# 复制启动脚本和配置文件到 /root/
mkdir -p ${DEB_DIR}/root
cp root/start.sh ${DEB_DIR}/root/
cp Settings/DeviceSettings.ini ${DEB_DIR}/root/
cp root/DCTable.txt ${DEB_DIR}/root/
cp README.md ${DEB_DIR}/root/机顶辐照度使用说明书.md
chmod +x ${DEB_DIR}/root/start.sh

# 4. 创建 DEBIAN 目录和配置文件
echo ""
echo "[4/5] 创建 DEBIAN 配置..."
mkdir -p ${DEB_DIR}/DEBIAN

# 创建 control 文件
cat > ${DEB_DIR}/DEBIAN/control <<EOF
Package: iris-fodis
Version: ${VERSION}
Architecture: armhf
Maintainer: iris-fodis Team
Description: IRIS Fiber Optic Spectrometer Data Acquisition System
EOF

# 创建 postinst 脚本（安装后执行）
cat > ${DEB_DIR}/DEBIAN/postinst <<EOF
#!/bin/bash
echo "IRIS_FODIS v${VERSION} installed"
chmod +x /home/pi/bin/IRIS_FODIS
chmod +x /root/start.sh

# 确保 SD 卡挂载后再写入 version
mkdir -p /home/data
if [ -b /dev/mmcblk1p1 ]; then
    if ! mount | grep -q "/dev/mmcblk1p1 on /home/data"; then
        mount /dev/mmcblk1p1 /home/data
    fi
    if mount | grep -q "/dev/mmcblk1p1 on /home/data"; then
        echo "V${VERSION}" > /home/data/version
    fi
fi
exit 0
EOF

# 创建 prerm 脚本（删除前执行）
cat > ${DEB_DIR}/DEBIAN/prerm <<EOF
#!/bin/bash
exit 0
EOF

chmod +x ${DEB_DIR}/DEBIAN/postinst
chmod +x ${DEB_DIR}/DEBIAN/prerm

# 5. 打包
echo ""
echo "[5/5] 打包成 deb 文件..."
sudo dpkg -b $DEB_DIR $PACKAGE_NAME

if [ $? -eq 0 ]; then
    echo ""
    echo "========================================="
    echo "打包成功: ${PACKAGE_NAME}"
    echo "========================================="

    # 移动到 DEB 目录
    mkdir -p DEB
    mv $PACKAGE_NAME DEB/
    echo "已移动到: DEB/${PACKAGE_NAME}"

    # 清理临时目录
    rm -rf $DEB_DIR
else
    echo "错误：打包失败"
    exit 1
fi