#!/bin/bash
set -e

# ================= 用户可修改区域 =================

# 1. 要写入 config.txt 的 overlays
OVERLAYS=$(cat <<EOF
camera_auto_detect=0
#dtoverlay=isx031-gmsl-camera-a,sensor-type=ISX031C_GMSL2F_1CH
#dtoverlay=isx031-gmsl-camera-a,sensor-type=ISX031C_GMSL2F_2CH
#dtoverlay=isx031-gmsl-camera-b,sensor-type=ISX031C_GMSL2F_1CH
#dtoverlay=isx031-gmsl-camera-b,sensor-type=ISX031C_GMSL2F_2CH
 
EOF
)

# 2. 要拷贝到 /usr/bin 的脚本
BIN_SCRIPTS=("ws_camera_ctrl.sh" "ws_camera_preview.sh")
BIN_TARGET_DIR="/usr/bin"

# ==================================================

CONFIG_FILE="/boot/firmware/config.txt"
TMP_FILE="/tmp/config.txt"
BACKUP_FILE="/boot/firmware/config.txt.bak.$(date +%Y%m%d-%H%M%S)"

# ==================================================

echo "[INFO] 安装内核模块 ..."

KERNEL_VER="$(uname -r)"
SRC_MODULE_DIR="$(pwd)/modules/${KERNEL_VER}"
DST_MODULE_DIR="/lib/modules/${KERNEL_VER}"

if [ ! -d "$SRC_MODULE_DIR" ]; then
    echo "[ERROR] 未找到内核模块目录: $SRC_MODULE_DIR" >&2
    echo "        请确认 modules/${KERNEL_VER}/ 存在" >&2
    exit 1
fi

echo "[INFO] 当前内核版本: $KERNEL_VER"
echo "[INFO] 模块源目录: $SRC_MODULE_DIR"
echo "[INFO] 模块目标目录: $DST_MODULE_DIR"

sudo mkdir -p "$DST_MODULE_DIR"

# 拷贝 ko
sudo cp "$SRC_MODULE_DIR"/*.ko "$DST_MODULE_DIR/" || {
    echo "[ERROR] 拷贝 ko 失败" >&2
    exit 1
}

# 刷新模块依赖
echo "[INFO] 执行 depmod ..."
sudo depmod "$KERNEL_VER"

echo "[INFO] 内核模块安装完成"

# ==================================================

echo "[INFO] 拷贝 overlays..."
sudo cp dtbo/*.dtbo /boot/firmware/overlays/

echo "[INFO] 备份 config.txt -> $BACKUP_FILE"
sudo cp "$CONFIG_FILE" "$BACKUP_FILE"

echo "[INFO] 修改 config.txt ..."
echo "$OVERLAYS" > "$TMP_FILE"

echo "[INFO] 在 config.txt 末尾追加 overlays ..."

while IFS= read -r line; do
    # 跳过空行
    [ -z "$line" ] && continue
    # 如果 config.txt 已经包含这行，就跳过
    if grep -Fxq "$line" "$CONFIG_FILE"; then
        :
        # echo "[INFO] 已存在: $line"
    else
        echo "$line" | sudo tee -a "$CONFIG_FILE" >/dev/null
        # echo "[INFO] 添加: $line"
    fi
done < "$TMP_FILE"

rm -f "$TMP_FILE"

# ==================================================

echo "[INFO] 拷贝脚本到 $BIN_TARGET_DIR ..."
for s in "${BIN_SCRIPTS[@]}"; do
    src="script/$s"
    if [ -f "$src" ]; then
        sudo cp "$src" "$BIN_TARGET_DIR/"
        sudo chmod +x "$BIN_TARGET_DIR/$s"
        echo "[INFO] $s 已拷贝并设置可执行权限"
    else
        echo "[WARN] 找不到 $src，跳过"
    fi
done

# ==================================================

echo "[INFO] 完成 ✅"

