#!/bin/bash

BOARD_CONFIG_DIR=longan/device/config/chips/
BOARD_CONFIG_FILE=longan/device/.BoardConfig.mk
DTS_DIR=$BOARD_CONFIG_DIR/a133/configs/c3

LCD_DTS=(
  "lcd-lvds-7-1024-600.dtsi"
  "lcd-lvds-21-1920-1080.dtsi"
  "lcd-mipi-10-800-1280-v1.dtsi"
  "lcd-mipi-10-800-1280-v2.dtsi"
  "lcd-mipi-8-800-1280.dtsi"
  "lcd-mipi-5-720-1280.dtsi"
)

function build_lunch() {
    TARGET_BOARD_PATH_ARRAY=($(find $BOARD_CONFIG_DIR -name "BoardConfig-a133*.mk" | sort))
    TARGET_BOARD_ARRAY=($(find $BOARD_CONFIG_DIR -name "BoardConfig-a133*.mk" | sed 's#.*/##' | sort))
    echo "======you are building a133 android======"
    echo "${TARGET_BOARD_ARRAY[@]}" | xargs -n 1 | sed "=" | sed "N;s/\n/. /"

    while true; do
        read -p "which board would you like (1-${#TARGET_BOARD_ARRAY[@]}): " INDEX
        if [[ "$INDEX" =~ ^[0-9]+$ ]] && ((INDEX >= 1 && INDEX <= ${#TARGET_BOARD_ARRAY[@]})); then
            INDEX=$(($INDEX - 1))
            BUILD_TARGET_BOARD="${TARGET_BOARD_PATH_ARRAY[$INDEX]}"

            break
        else
            echo "Invalid input. Please enter a number between 1 and ${#TARGET_BOARD_ARRAY[@]}."
        fi
    done

    cp -f $BUILD_TARGET_BOARD $BOARD_CONFIG_FILE

    echo -e "build target board configuration: $BUILD_TARGET_BOARD\n"
    #select partition table
    source $BOARD_CONFIG_FILE
    echo "you board is ${DTS_NAME}"

    ln -rsf "${DTS_DIR}/${DTS_NAME}.fex" "${DTS_DIR}/sys_config.fex"
    echo "Start clean kerenl"

    cd longan/kernel/linux-4.9 && make clean -j32 && cd -
    source $BOARD_CONFIG_FILE
    longan/build/mkcommon.sh autoconfig -i a133 -o android -b c3
}

function build() {
    DTS_FILE=${DTS_DIR}/${DTS_NAME}.dts
    for config in "${LCD_DTS[@]}"; do
      # 检查未被注释的配置行（支持行首空格）
      if grep -q -E "^[[:space:]]*#include \"${config}\"" "$DTS_FILE"; then
        # 提取 lcd- 之后 .dtsi 之前的内容（去除头尾字符）
        LCD_NAME=$(echo "$config" | sed 's/^lcd-\(.*\)\.dtsi$/\1/')
        break
      fi
    done


sed -i -E "
/^[[:space:]]*export LCD_NAME=/ {
  s|^(export LCD_NAME=).*$|\1${LCD_NAME}|
  h
  \$!{x;b};x
  b done
}

1 i export LCD_NAME=${LCD_NAME}

:done
" "${BOARD_CONFIG_FILE}"


    source $BOARD_CONFIG_FILE

    if [ x"$1" == "xuboot" ] || [ x"$1" == "xu" ] || [ x"$1" == "x" ]; then
        echo "Start build uboot"
        cd longan/brandy/brandy-2.0
        ./build.sh -p sun50iw10p1
        if [ $? -eq 0 ]; then
            echo "Build uboot ok!"
        else
            echo "Build uboot failed!"
            cd -
            exit 1
        fi
        cd -
    fi

    if [ x"$1" == "xkernel" ] || [ x"$1" == "xk" ] || [ x"$1" == "x" ]; then
        echo "Start build kernel"
        cd longan
        ./build.sh autoconfig -o android -i a133 -b c3
        ./build.sh
        if [ $? -eq 0 ]; then
            echo "Build kernel ok!"
        else
            echo "Build kernel failed!"
            cd -
            exit 1
        fi
        cd -
    fi

    # android envsetup
    cd android
    . ./build/envsetup.sh
    lunch ceres_c3-userdebug
    extract-bsp
    cd -

    if [ x"$1" == "xandroid" ] || [ x"$1" == "xa" ] || [ x"$1" == "x" ]; then
        echo "Start build Android"
        cd android
        make installclean
        make BUILD_NUMBER=ido-a133 -j32
        if [ $? -eq 0 ]; then
            echo "Build android ok!"
        else
            echo "Build android failed!"
            cd -
            exit 1
        fi
        cd -
    fi

    # pack image
    echo "Start pack image"
    cd android
    pack
    cd -


}

if [ "x$1" == "xlunch" ]; then
    build_lunch && exit 0
else
    source $BOARD_CONFIG_FILE
    if [ "x$1" == "xall" ]; then
        for config in "${LCD_DTS[@]}"; do
            echo "正在切换设备树: $config"
            # Step 1: 注释所有 LCD 相关行（无论原始是否已注释）
            sed -i -E '/#include "lcd-/s|^([[:space:]]*)(//)?|\1//|' "$DTS_DIR/$DTS_NAME.dts"

            # Step 2: 解除目标配置的注释
            sed -i -E "s|^([[:space:]]*)//#include \"$config\"|\1#include \"$config\"|" "$DTS_DIR/$DTS_NAME.dts"

            # # 提取 lcd- 之后 .dtsi 之前的内容（去除头尾字符）
            # LCD_DTS_FILE=$(echo "$config" | sed 's/^lcd-\(.*\)\.dtsi$/\1/')

            # 执行编译
            echo "开始编译..."
            build
        done
    else
        build $@  && exit 0
    fi

fi
