#!/bin/bash 

# 启动二进制文件
function startbin(){
    echo "正在启动..."
    mkdir -p ./bin
    sys=$(get_system)
    if [ $sys == "Windows" ]; then
        ./bin/bin.exe
    else
        chmod +x ./bin/bin
        ./bin/bin
    fi
}

# 更新二进制文件
function updatebin(){
    echo "正在下载更新..."
    mkdir -p ./bin
    mkdir -p ./remote_bin
    sys=$(get_system)
    if [ $sys == "Windows" ]; then
        curl -L http://red.super1207.top/download/latest_${platform}.php -o ./remote_bin/bin.exe
        cp -f ./remote_bin/bin.exe ./bin/bin.exe
    else
        curl -L http://red.super1207.top/download/latest_${platform}.php -o ./remote_bin/bin
        cp -f ./remote_bin/bin ./bin/bin
        chmod +x ./bin/bin
    fi
    cp -f ./remote_bin/version.txt ./bin/version.txt
    echo "下载更新完成"
    # ./bin/bin.exe
}


# 获取远程版本 
function get_remote_version(){
    echo "正在获取远程版本号..."
    mkdir -p ./remote_bin
    remote_version=$(curl -L http://red.super1207.top/version/latest_version.php)
    [[ $remote_version =~ ([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}) ]]
    remote_version_num=$((${BASH_REMATCH[1]} * 1000000+${BASH_REMATCH[2]} * 1000+${BASH_REMATCH[3]}))
    echo $remote_version > ./remote_bin/version.txt
    echo "远程版本号:"$remote_version
    return $remote_version_num
}

# 获取本地版本
function get_local_version(){
    echo "正在获取本地版本号..."
    mkdir -p ./bin
    if [ -f "./bin/version.txt" ];then
        local_version=$(cat ./bin/version.txt)
        [[ $local_version =~ ([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}) ]]
        local_version_num=$((${BASH_REMATCH[1]} * 1000000+${BASH_REMATCH[2]} * 1000+${BASH_REMATCH[3]}))
        echo "本地版本号:"$local_version
        return $local_version_num
    else
    echo "0.0.0" > ./bin/version.txt
        echo "本地版本号:0.0.0"
        return 0
    fi   
}

# 获得操作系统
function get_system(){
    if [ -d "$PREFIX" ]; then
        echo "Android"
    elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
        echo "Linux"
    elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
        echo "Windows"
    elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then
        echo "Windows"
    fi
}

function get_plarform(){
    sys=$(get_system)
	arch=$(uname -m)
    if [ $sys == "Windows" ]; then
        echo "windows_i686"
    elif [ $sys == "Android" ]; then
        echo "android_aarch64"
    elif [ $sys == "Linux" ] && [ $arch == "aarch64" ]; then
        echo "linux_aarch64"
	elif [ $sys == "Linux" ]; then
        echo "linux_i686"
    fi
}


while [ 1 ]
do
    echo 欢迎使用红色问答启动器v0.0.3
    arch=$(uname -m)
    sys=$(get_system)

    echo 目标平台:${sys}_$arch | tr A-Z a-z

    platform=$(get_plarform)
    echo 下载文件平台:$platform

    # 获取版本
    get_remote_version
    remote_version=$?
    get_local_version
    local_version=$?

    # 更新文件
    if test $remote_version -gt $local_version
    then
        # 升级
        updatebin
    fi

    # 启动文件
    startbin

    echo 检测到异常崩溃，正在重启。。。

    sleep 5
done
