#!/bin/bash
SCRIPT_PATH="$(pwd)"
echo "$SCRIPT_PATH"

# 进入某个路径，如果文件夹不存在，创建
function cd_dir {
    local dir_path=$1

    # 检查目录是否存在
    if [ ! -d "$dir_path" ]; then
        echo "Directory $dir_path does not exist. Creating..."
        mkdir -p "$dir_path"
    fi
    cd "$dir_path" || exit
}

# 安装包检测
function check_and_install {
    for package_name in "$@"
    do
        if ! dpkg -l $package_name &> /dev/null
        then
            echo "$package_name not found. Installing..."
            sudo apt-get update
            sudo apt-get install $package_name -y
        else
            echo "$package_name already installed."
        fi
    done
}

# 克隆代码
function git_clone {
    local repo_url=$1
    local target_dir=$2
    local max_attempts=3

    echo "Cloning $repo_url to $target_dir..."

    # 初始化计数器
    attempt=1

    # 循环尝试克隆
    while [ $attempt -le $max_attempts ]; do
        # 如果目标目录存在，则删除它
        if [ -d "$target_dir" ]; then
            echo "Clone successful!"
            return
        fi

        # 克隆代码
        git clone "$repo_url" "$target_dir"

        # 检查克隆是否成功
        if [ $? -eq 0 ]; then
            echo "Clone successful!"
            # 如果克隆成功，则退出循环
            break
        else
            rm -rf "$target_dir"
            echo "Clone attempt $attempt failed."
            attempt=$((attempt+1))
            if [ $attempt -gt $max_attempts ]; then
                echo "Max attempts reached. Continue..."
            else
                echo "Retrying in 5 seconds..."
                sleep 5
            fi
        fi
    done
}

# install env
cd "$SCRIPT_PATH" || exit

cd_dir build

cmake ..

max_retries=3   # 设置最大尝试次数为 3 次
retry_count=0

while [ $retry_count -lt $max_retries ]
do
    sudo make install
    if [ $? -eq 0 ]   # 判断 make 命令的返回值是否为 0，即成功
    then
        echo "Build succeeded!"
        exit 0
    else
        echo "Build failed! Retrying in 3 seconds..."
        retry_count=$((retry_count+1))
        sleep 3   # 等待 3 秒再次尝试编译
    fi
done

echo "Failed to build after $max_retries retries."
exit 1

