#!/bin/bash

BOARD_CONFIG_DIR=longan/device/config/chips/
BOARD_CONFIG_FILE=longan/device/.BoardConfig.mk

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}"

       source $BOARD_CONFIG_FILE
       longan/build/mkcommon.sh autoconfig -i a133 -o android -b c3
}

if [ "x$1" == "xlunch" ];then
    build_lunch && exit 0
else
    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 && cd -
      if [ $? -eq 0 ]; then
        echo "Build uboot ok!"
      else
        echo "Build uboot failed!"
        exit 1
      fi
    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 && cd -
      if [ $? -eq 0 ]; then
        echo "Build kernel ok!"
      else
        echo "Build kernel failed!"
        exit 1
      fi
    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
      cd -
    fi

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

fi