#!/bin/bash
export PATH=$PATH:/opt/mips-mti-elf/2020.06-01/bin
COMPILE_VENDOR=$(basename $(dirname $(pwd)))
COMPLIE_BOARD=$(basename $(pwd))
DEBUG_VERSION=debug

VERSION="chp$(printf '\x01')$(printf '\xff')$(printf '\xff')$(printf '\xff')$(printf '\xff')$(printf '\xff')$(printf '\xff')$(printf '\xff')$(printf '\xff')"
DATE=`date +%Y%m%d`
CURPATH=.
ROOTPATH=../../..
OUTPATH=$ROOTPATH/out
PREBUILDPATH=./Prebuilds

BUILD_PROJECT_PATH=$ROOTPATH/build
TARGETOUTPATH=./out

SILICON_DATA_FILE=$OUTPATH/ddr-Monitor_SOC.bin
SILICON_DATA_DB_FILE=$OUTPATH/ddr-Monitor_SOC.bin-DB
BOOT_FILE=$OUTPATH/silicon_boot.bin
PM_FILE=pm.bin
SUPERBLK_FILE=super.bin

SILICON_DATA_FILE_COMPRESSED=ddr-Monitor_SOC_compressed.bin
SILICON_DATA_FILE_DB_COMPRESSED=ddr-Monitor_SOC_compressed.bin-DB

DATA_FILE_COMPRESSED=temp_data_compressed.bin

PROPERTY_CONFIG_FILE=$CURPATH/property.config
FLASH_CONFIG_FILE=$CURPATH/System/hv_comm_FlashConfig.h
PROJECT_CONFIG_FILE=$CURPATH/ProjectConfig.h

search_files_cal_call_check() {
    local dir="$1"
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            search_files_cal_call_check "$file"
        elif [ -f "$file" ] && [[ "$file" == *hv_cal_* ]] && [ -n "$(grep -l 'Hv_Drv_' "$file")" ]; then
            echo "$file has called func: Hv_Drv_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_cal_* ]] && [ -n "$(grep -l 'Hv_Mw_' "$file")" ]; then
            echo "$file has called func: Hv_Mw_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_cal_* ]] && [ -n "$(grep -l 'HvPlat_' "$file")" ]; then
            echo "$file has called func: HvPlat_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_cal_* ]] && [ -n "$(grep -l 'Hv_App_' "$file")" ]; then
            echo "$file has called func: Hv_App_"
            exit
        fi
    done
}

search_files_drv_call_check() {
    local dir="$1"
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            search_files_drv_call_check "$file"
        elif [ -f "$file" ] && [[ "$file" == *hv_drv_* ]] && [ -n "$(grep -l 'Hv_Mw_' "$file")" ]; then
            echo "$file has called func: Hv_Mw_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_drv_* ]] && [ -n "$(grep -l 'HvPlat_' "$file")" ]; then
            echo "$file has called func: HvPlat_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_drv_* ]] && [ -n "$(grep -l 'Hv_App_' "$file")" ]; then
            echo "$file has called func: Hv_App_"
            exit
        fi
    done
}
search_files_mw_call_check() {
    local dir="$1"
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            search_files_mw_call_check "$file"
        elif [ -f "$file" ] && [[ "$file" == *hv_mw_* ]] && [ -n "$(grep -l 'HvPlat_' "$file")" ]; then
            echo "$file has called func: HvPlat_"
            exit
        elif [ -f "$file" ] && [[ "$file" == *hv_mw_* ]] && [ -n "$(grep -l 'Hv_App_' "$file")" ]; then
            echo "$file has called func: Hv_App_"
            exit
        fi
    done
}
search_files_plat_file_check() {
    local dir="$1"
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            search_files_plat_file_check "$file"
        elif [ -f "$file" ] && [[ "$file" == *HvPlat* ]]; then
            echo "$file in sdk"
            exit
        fi
    done
}
search_files_plat_call_app() {
    local dir="$1"
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            search_files_plat_call_app "$file"
        elif [ -f "$file" ] && [[ "$file" == *HvPlat* ]] && [ -n "$(grep -l 'Hv_App_' "$file")" ]; then
            echo "$file has called func: Hv_App_"
            exit
        fi
    done
}
code_check(){
    cd $ROOTPATH/sdk/Driver
    search_files_cal_call_check "."
    search_files_drv_call_check "."
    search_files_mw_call_check "."
    search_files_plat_file_check  "."
    cd -
    search_files_cal_call_check "."
    search_files_drv_call_check "."
    search_files_mw_call_check "."
    search_files_plat_call_app "."
}

cmake_project(){

    cd $BUILD_PROJECT_PATH
    bash project_config.sh $COMPILE_VENDOR  $COMPLIE_BOARD ht7315
    make clean
    make $DEBUG_VERSION -j
    cd -

    if [ ! -f $SILICON_TEXT_RO_FILE ]; then
        echo "APP build fail, NO APP FILE-${SILICON_TEXT_RO_FILE}!"
        exit
    fi
    if [ ! -f $SILICON_DATA_FILE ]; then
        echo "APP build fail, NO APP FILE-${SILICON_DATA_FILE}!"
        exit
    fi
    return 0
}

get_git_revision(){
    GITREV=`git rev-parse --short HEAD`
    echo "GIT revision: $GITREV"
}

compressed_file_size(){
    FILE_SIZE=`wc -c < $1`
    echo "$1 size: $FILE_SIZE"
    echo "HIVIEW!" > hiview.bin
    echo $FILE_SIZE > size.bin
    cat hiview.bin size.bin > ${1}_size
    dd if=${1}_size of=${1}_size_aline32 ibs=32 conv=sync
}


pad_file(){
    echo "padding file"
    input_size=$(wc -c < $1)
	if [ "$input_size" -gt "$2" ]; then
		echo "Error: Input file ($input_size bytes) is larger than target size ($2 bytes)"
		exit 1
	fi
    cp $1 $1_temp
    echo $input_size
    padding_size=$(($2-$input_size))
    cat $1_temp > $3
    echo $padding_size
    dd if=/dev/zero bs=1 count=$padding_size|tr "\000" "\377" >> $3
}

superblkOffset=$(printf "%d" 0)
TEMP_CRC=$(printf "%x" 0)
add_super_blk(){
    echo  $1 $2 $3
    if [ "$3" = "0" ]; then
        echo "no padding for $2"
        cp $2 $2_padded;
    else
        echo "padding for $2"
        pad_file $2 $3 $2_padded
    fi

    echo -n "SBLK" >> $SUPERBLK_FILE

    string=$1
    result=0
    substring=${string:0:4}
    # 将每个字符转换为ASCII码值并拼接成32位的数
    for ((i=0; i<${#substring}; i++)); do
        char_code=$(printf "%d" "'${substring:i:1}")
        result=$(( (result << 8) | char_code ))
    done
    hex=$(printf "%08X" $result)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $SUPERBLK_FILE

    length=`wc -c < $2`
    hex=$(printf "%08X" $length)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $SUPERBLK_FILE

    hex=$(printf "%08X" $superblkOffset)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $SUPERBLK_FILE
    length=`wc -c < $2_padded`
    superblkOffset=$(($superblkOffset+$length))

    echo -n $VERSION >> $SUPERBLK_FILE

    crc=$(cksum $2 | cut -f1 -d' ')
    hex=$(printf "%08X" $crc)
    TEMP_CRC=${hex}
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $SUPERBLK_FILE
}

pqOffset=$(printf "%d" 4096)
add_pq_bin(){
    echo $1 $2 $3 $4

    echo  "HEAD:add file $1"
    echo -n "HEAD" >> $TARGETOUTPATH/header.bin

    hex=$(printf "%04X" $3)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}"  >> $TARGETOUTPATH/header.bin

    hex=$(printf "%04X" $4)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}"  >> $TARGETOUTPATH/header.bin

    size=$(stat -c%s $PREBUILDPATH/$1)
    echo $size
    hex=$(printf "%08X" $size)
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $TARGETOUTPATH/header.bin


    echo $pqOffset
    hex=$(printf "%08X" $pqOffset)
    echo $hex
    echo -n -e "\x${hex:0:2}\x${hex:2:2}\x${hex:4:2}\x${hex:6:2}"  >> $TARGETOUTPATH/header.bin

    offset=$((($size + 511) / 512 * 512))
    echo $offset
    hex=$(printf "%08X" $offset)
    echo $hex
    cp $PREBUILDPATH/$1 $TARGETOUTPATH/$1
    pad_file $TARGETOUTPATH/$1 $offset $TARGETOUTPATH/$1_pad

    pqOffset=$(($pqOffset+$offset))

    dd if=$TARGETOUTPATH/$1_pad of=$2 conv=notrunc oflag=append
}

find_multy_bin(){
    rm -rf $TARGETOUTPATH/$1.bin
    for ((i=1; i<=10; i++))
    do
        if [ -e $PREBUILDPATH/$1_$i.bin ]; then
            add_pq_bin $1_$i.bin  $2 $3 $i
        else
            break
        fi
    done
}

find_pq_bin(){
    if [ -e $PREBUILDPATH/$1.bin ]; then
        echo  "file $1"
        rm -rf $TARGETOUTPATH/$1.bin
        add_pq_bin $1.bin  $2 $3 1
    elif [ -e $PREBUILDPATH/$1_1.bin ]; then
        echo " multy file $1"
        find_multy_bin $1 $2 $3
    else
        echo "no file $1"
        return;
    fi

    nodeOffset=$(($nodeOffset+16))
}



if [ "$1" = "nocompile" ]; then
    echo "$1"

    cd $BUILD_PROJECT_PATH
    bash project_config.sh $COMPILE_VENDOR  $COMPLIE_BOARD ht7315
    cd -
    exit -1
fi

echo "vendor: $COMPILE_VENDOR"
echo "board: $COMPLIE_BOARD"
echo "date: $DATE"
get_git_revision
rm -rf $OUTPATH/Monitor_SOC_*.bin
echo "code check******************************"
code_check
echo "Complie Bin*****************************"
cmake_project
if [ ! -x "$TARGETOUTPATH" ];then
    echo "$TARGETOUTPATH"
    mkdir $TARGETOUTPATH
fi

echo "Merge PQData*****************************"
rm -rf $TARGETOUTPATH/temp_pq.bin
rm -rf $TARGETOUTPATH/header.bin
find_pq_bin pq_init_reg $TARGETOUTPATH/temp_pq.bin 1
find_pq_bin dither $TARGETOUTPATH/temp_pq.bin 2
find_pq_bin scl $TARGETOUTPATH/temp_pq.bin 3
find_pq_bin ldc $TARGETOUTPATH/temp_pq.bin 4
find_pq_bin od $TARGETOUTPATH/temp_pq.bin 5
find_pq_bin contrast $TARGETOUTPATH/temp_pq.bin 6
find_pq_bin yccm $TARGETOUTPATH/temp_pq.bin 7
find_pq_bin sharpness $TARGETOUTPATH/temp_pq.bin 8
find_pq_bin contrast_para $TARGETOUTPATH/temp_pq.bin 9
find_pq_bin sharpness_para $TARGETOUTPATH/temp_pq.bin 10
find_pq_bin gamma_t $TARGETOUTPATH/temp_pq.bin 11
find_pq_bin gamma_d $TARGETOUTPATH/temp_pq.bin 12
find_pq_bin osd_gmd $TARGETOUTPATH/temp_pq.bin 13
find_pq_bin osd_gmi $TARGETOUTPATH/temp_pq.bin 14
find_pq_bin wcg_cm $TARGETOUTPATH/temp_pq.bin 15
find_pq_bin wcg_gmd $TARGETOUTPATH/temp_pq.bin 16
find_pq_bin wcg_gmi $TARGETOUTPATH/temp_pq.bin 17
find_pq_bin hdr $TARGETOUTPATH/temp_pq.bin 18
find_pq_bin demura $TARGETOUTPATH/temp_pq.bin 19
pad_file $TARGETOUTPATH/header.bin 4096 $TARGETOUTPATH/pad_header.bin
cat  $TARGETOUTPATH/pad_header.bin $TARGETOUTPATH/temp_pq.bin > $TARGETOUTPATH/temp_header_pq.bin
echo "Merge PQData over*************************"

echo "compress bin******************************"
$PREBUILDPATH/LZSS e $SILICON_DATA_DB_FILE $TARGETOUTPATH/$SILICON_DATA_FILE_DB_COMPRESSED
echo "compress bin"
$PREBUILDPATH/LZSS e $SILICON_DATA_FILE $TARGETOUTPATH/$SILICON_DATA_FILE_COMPRESSED
echo "compress bin"
$PREBUILDPATH/LZSS e $TARGETOUTPATH/temp_header_pq.bin $TARGETOUTPATH/$DATA_FILE_COMPRESSED
echo "compress bin over*************************"

echo "Merge ALLBin*****************************"

CODE_PARTITION_SIZE=$(grep -w 'HV_FLASH_CONFIG_CODE_PART_SIZE' $FLASH_CONFIG_FILE | head -n 1 | awk -F' ' '{gsub(/[(]/,""); gsub(/[)]/,""); print $3}' | sed 's/\r$//' | tr -d '\r' | bc)
LOGO_PARTITION_SIZE=$(grep -w 'HV_FLASH_CONFIG_LOGO_PART_SIZE' $FLASH_CONFIG_FILE | head -n 1 | awk -F' ' '{gsub(/[(]/,""); gsub(/[)]/,""); print $3}' | sed 's/\r$//' | tr -d '\r' | bc)
PQDA_PARTITION_SIZE=$(grep -w 'HV_FLASH_CONFIG_PQ_DATA_PART_SIZE' $FLASH_CONFIG_FILE | head -n 1 | awk -F' ' '{gsub(/[(]/,""); gsub(/[)]/,""); print $3}' | sed 's/\r$//' | tr -d '\r' | bc)
RESV_PARTITION_SIZE=$(grep -w 'HV_FLASH_CONFIG_SECOND_PART_SIZE' $FLASH_CONFIG_FILE | head -n 1 | awk -F' ' '{gsub(/[(]/,""); gsub(/[)]/,""); print $3}' | sed 's/\r$//' | tr -d '\r' | bc)
echo "CODE_PARTITION_SIZE: $CODE_PARTITION_SIZE"
echo "LOGO_PARTITION_SIZE: $LOGO_PARTITION_SIZE"
echo "PQDA_PARTITION_SIZE: $PQDA_PARTITION_SIZE"
echo "RESV_PARTITION_SIZE: $RESV_PARTITION_SIZE"

cp $OUTPATH/*.bin $TARGETOUTPATH/
cp $OUTPATH/*.bin-DB $TARGETOUTPATH/
cd $TARGETOUTPATH/


compressed_file_size $SILICON_DATA_FILE_COMPRESSED
compressed_file_size $SILICON_DATA_FILE_DB_COMPRESSED
compressed_file_size $DATA_FILE_COMPRESSED

pad_file $PM_FILE 32768 temp_pm.bin_padded
cp temp_pm.bin_padded $SUPERBLK_FILE


cat  ${SILICON_DATA_FILE_COMPRESSED}_size_aline32 $SILICON_DATA_FILE_COMPRESSED > temp_silicon_data.bin

echo d >> pmsb.bin
pad_file pmsb.bin 36864 pmsb.bin_padded
add_super_blk PMSB pmsb.bin_padded 36864
add_super_blk BOOT silicon_boot.bin 61440
add_super_blk BTBK silicon_boot.bin-DB 61440
add_super_blk CODE temp_silicon_data.bin $CODE_PARTITION_SIZE
CODE_CRC=${TEMP_CRC}
SHORT_CRC=${CODE_CRC: -4}
touch null.bin
pad_file null.bin 4096 fire.bin
add_super_blk FIRE fire.bin 4096

LOGO_BIN_NAME=$(grep -w 'HV_PROJECT_CONFIG_LOGO_BIN_NAME' ../ProjectConfig.h | head -n 1 | awk -F' ' '{gsub(/[(]/,""); gsub(/[)]/,""); print $3}' | sed 's/\r$//' | tr -d '\r' | tr -d '"')
if [ "$LOGO_BIN_NAME" = "" ]; then
  LOGO_BIN_NAME=Logo.bin
fi
if [ -e ../Prebuilds/${LOGO_BIN_NAME} ]; then
    echo $LOGO_BIN_NAME
else
    echo ERROR:no $LOGO_BIN_NAME
    exit
fi
cp ../Prebuilds/${LOGO_BIN_NAME} ./Logo.bin
add_super_blk LOGO Logo.bin $LOGO_PARTITION_SIZE

cat ${DATA_FILE_COMPRESSED}_size_aline32 $DATA_FILE_COMPRESSED > temp_pq_data.bin
add_super_blk PQDA temp_pq_data.bin $PQDA_PARTITION_SIZE

if grep -Eq 'CONFIG_USER_FLASH_DB\s*\?=\s*FLASH_DB_ON' ../property.config; then
    pad_file null.bin 4096 back4k.bin;add_super_blk BACK back4k.bin $RESV_PARTITION_SIZE
fi

pad_file null.bin 4096 temp4kdata.bin
pad_file null.bin 8192 temp8kdata.bin
pad_file null.bin 16384 temp16kdata.bin
pad_file null.bin 40960 temp40kdata.bin
pad_file null.bin 65536 temp64kdata.bin
add_super_blk TIME temp4kdata.bin 0
add_super_blk USER temp4kdata.bin 0
add_super_blk USBK temp4kdata.bin 0
add_super_blk SYSM temp4kdata.bin 0
add_super_blk FACT temp4kdata.bin 0
add_super_blk PANL temp4kdata.bin 0
add_super_blk GAMA temp16kdata.bin 0
add_super_blk EDID temp16kdata.bin 0
add_super_blk HDCP temp8kdata.bin 0

pad_file ${SUPERBLK_FILE} 36864 ${SUPERBLK_FILE}_ota_padded
add_super_blk FULL null.bin 0
pad_file ${SUPERBLK_FILE} 36864 ${SUPERBLK_FILE}_full_padded

cat ${SUPERBLK_FILE}_ota_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded > ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_Reduce.bin
cat ${SUPERBLK_FILE}_ota_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded fire.bin_padded Logo.bin_padded temp_pq_data.bin_padded> ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_Reduce_PQ.bin

if grep -Eq 'CONFIG_USER_FLASH_DB\s*\?=\s*FLASH_DB_ON' ../property.config; then
    cat ${SUPERBLK_FILE}_ota_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded fire.bin_padded Logo.bin_padded temp_pq_data.bin_padded  back4k.bin_padded temp40kdata.bin> ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_Reduce_CFG.bin
    cat ${SUPERBLK_FILE}_full_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded fire.bin_padded Logo.bin_padded temp_pq_data.bin_padded  back4k.bin_padded temp64kdata.bin> ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_FULL.bin
else
    cat ${SUPERBLK_FILE}_ota_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded fire.bin_padded Logo.bin_padded temp_pq_data.bin_padded temp40kdata.bin> ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_Reduce_CFG.bin
    cat ${SUPERBLK_FILE}_full_padded silicon_boot.bin_padded silicon_boot.bin-DB_padded temp_silicon_data.bin_padded fire.bin_padded Logo.bin_padded temp_pq_data.bin_padded temp64kdata.bin> ../Monitor_SOC_${COMPILE_VENDOR}_${COMPLIE_BOARD}_${DATE}_GIT${GITREV}_FULL.bin
fi

echo ${CODE_CRC}
cd -

mv Monitor_SOC_* $OUTPATH/
mv out $OUTPATH/compressed

echo "Merge Bin Finish**********************"

