#!/bin/bash

# SkyLink ROS 2 机载端 - 快速编译脚本
# 用法: ./build.sh [release|debug]

#  加载git分支
# 如果是python分支，则加载python相关依赖
# 如果是cpp分支，则加载cpp相关依赖

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BUILD_TYPE="${1:-release}"

echo "========================================"
echo "SkyLink ROS 2 编译脚本"
echo "========================================"
echo "工作目录: $SCRIPT_DIR"
echo "编译类型: $BUILD_TYPE"
echo ""

# 检查 ROS 2 环境
if [ -z "$ROS_DISTRO" ]; then
    echo "❌ 错误：未检测到 ROS 2 环境"
    echo "请先运行: source /opt/ros/humble/setup.bash"
    exit 1
fi

echo "✓ ROS 2 发行版: $ROS_DISTRO"

# 检查依赖
echo ""
echo "正在检查系统依赖..."
if ! command -v colcon &> /dev/null; then
    echo "❌ 错误：未找到 colcon，请安装："
    echo "  sudo apt install -y python3-colcon-common"
    exit 1
fi

echo "✓ colcon 已安装"

# 清理旧编译（可选）
if [ -d "$SCRIPT_DIR/build" ] && [ "$BUILD_TYPE" = "clean" ]; then
    echo ""
    echo "清理旧编译产物..."
    rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/install" "$SCRIPT_DIR/log"
    echo "✓ 清理完成"
fi

# 编译
echo ""
echo "正在编译 skylink_bridge 包..."
echo ""

if [ "$BUILD_TYPE" = "debug" ]; then
    colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Debug
else
    colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Release
fi

echo ""
echo "========================================"
echo "✓ 编译成功！"
echo "========================================"
echo ""
echo "下一步："
echo "1. 加载 ROS 环境:"
echo "   source $SCRIPT_DIR/install/setup.bash"
echo ""
echo "2. 启动节点:"
echo "   ros2 launch skylink_bridge bridge.launch.py"
echo "python 版本节点启动命令:"
echo "   ros2 launch skylink_bridge_python bridge.launch.py"
echo ""
