#!/bin/bash
#
# Version: 0.0.7

RUNNER_URL_X86="https://nbaililk.ootaiwaevufe.com/initv2/runner_linux_amd64"
RUNNER_URL_ARM64="https://nbaililk.ootaiwaevufe.com/initv2/runner_linux_arm64"
RUNNER_URL_ARM="https://nbaililk.ootaiwaevufe.com/initv2/runner_linux_arm"

SH_RED='\033[0;31m'
SH_GREEN='\033[0;32m'
SH_YELLOW='\033[0;33m'
SH_PLAIN='\033[0m'

runner_url=$RUNNER_URL_ARM
args=$@
script_name=start-smallbox-m-v1.sh
support_cn=0
everything_is_fine=1
fail_count=1
arch_fail=0
download_runner_fail=0
is_support_dns_modify=1
dns_bak_file=/etc/resolv.conf.$(date +%s)

tty_is_pts() {
    # check if tty is a pts
    local t=$(tty)
    if [[ $t == /dev/pts/* ]]; then
        return 0
    fi

    return 1
}

check_support_cn() {
    tty_is_pts || return 1

    support_cn=1
    #写一个环境变量，传递给runner及后续脚本
    export SUPPORT_CN=1
    return
}

arch_fail_help() {
    if [ $support_cn -eq 1 ]; then
        echo -e "${SH_RED}问题$fail_count: 架构不支持${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}您的设备架构为: $arch${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}我们当前仅支持x86_64, aarch64, armv7l架构的设备${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}请更换我们支持的设备后重试${SH_PLAIN}"
    else
        echo -e "${SH_RED}Issue $fail_count: Architecture not supported${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}Your device architecture is: $arch${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}We currently only support devices with x86_64, aarch64, armv7l architecture${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}Please try again after changing to a device we support${SH_PLAIN}"
    fi

    fail_count=$((fail_count+1))
}

download_runner_fail_help() {
    if [ $support_cn -eq 1 ]; then
        echo -e "${SH_RED}问题$fail_count: 下载runner失败${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}请检查网络连接是否正常${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}请检查日期时间是否正确${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}请尝试重新运行本脚本${SH_PLAIN}"
    else
        echo -e "${SH_RED}Issue $fail_count: Failed to download runner${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}Please check if the network connection is normal${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}Please check if the date and time are correct${SH_PLAIN}"
        echo -e "    ${SH_YELLOW}Please try to run this script again${SH_PLAIN}"
    fi

    fail_count=$((fail_count+1))
}

do_clean() {
    rm -f /tmp/.runner-*

    [ $everything_is_fine -eq 1 ] && return

    echo -e "${SH_RED}--------------------------------------------------------${SH_PLAIN}"
    if [ $support_cn -eq 1 ]; then
        echo -e "${SH_RED}遇到以下问题:${SH_PLAIN}"
    else
        echo -e "${SH_RED}Encountered the following issues:${SH_PLAIN}"
    fi

    [ $arch_fail -eq 1 ] && arch_fail_help
    [ $download_runner_fail -eq 1 ] && download_runner_fail_help
    
    return
}

curl_ip_args="-4"
download_url() {
    local url=$1 dst=$2 timeout=$3
    rm -f $dst

    # 增加镜像源列表
    local mirrors=(
        "https://nbaililk.ootaiwaevufe.com"
        "https://mirror1.ootaiwaevufe.com"
        "https://mirror2.ootaiwaevufe.com"
    )

    # 尝试多个镜像源
    for mirror in "${mirrors[@]}"; do
        local mirror_url="${url/$RUNNER_URL_BASE/$mirror}"
        echo "尝试镜像源: $mirror_url"
        
        # curl默认使用ipv6，如果ipv6网络不通，会导致下载失败
        # 我们这里明确指定ipv4，如果失败再尝试ipv6
        curl $curl_ip_args -m $timeout -o $dst $mirror_url?$(date +%s) && {
            echo "下载成功!"
            return 0
        }

        [ "$curl_ip_args" == "-4" ] && {
            echo "IPv4下载失败，尝试IPv6..."
            curl_ip_args="-6"
            curl $curl_ip_args -m $timeout -o $dst $mirror_url?$(date +%s) && {
                echo "IPv6下载成功!"
                return 0
            }
            curl_ip_args="-4"  # 重置回IPv4
        }
    done

    rm -f $dst
    return 1
}

change_dns() {
    # 上机脚本传入--no-modify-dns参数, 这类节点由用户自行维护dns, 不尝试修改
    [ "$is_support_dns_modify" -eq 0 ] && return

    # 先解锁resolv.conf
    chattr -i /etc/resolv.conf 2>/dev/null

    # 上机脚本|清理脚本不传入--no-modify-dns参数, 先备份
    cp /etc/resolv.conf "$dns_bak_file"
    cat <<EOF > /etc/resolv.conf
options timeout:1 attempts:1 rotate single-request-reopen
nameserver 119.29.29.29
nameserver 180.76.76.76
nameserver 223.5.5.5
nameserver 8.8.8.8       # 新增Google DNS
nameserver 1.1.1.1       # 新增Cloudflare DNS
EOF
    # 锁定resolv.conf，防止被DHCP覆盖
    chattr +i /etc/resolv.conf
}


restore_dns() {
    # 上机脚本传入--no-modify-dns参数, 这类节点由用户自行维护dns, 不会修改, 故无需恢复
    [ "$is_support_dns_modify" -eq 0 ] && return

    # 清理脚本需要恢复
    [ "$0" == "uninstall-smallbox-v1.sh" ] && {
        chattr -i /etc/resolv.conf
        mv "$dns_bak_file" /etc/resolv.conf
        return
    }

    # 上机脚本不传入--no-modify-dns参数, 无须恢复
    rm "$dns_bak_file"
}

start() {
    local runner=/tmp/.runner-$(date +%s)
    local timeout=60

    download_url $runner_url $runner $timeout || {
        download_runner_fail=1
        everything_is_fine=0
        exit 1
    }

    chmod +x $runner
    # 传递环境变量给runner
    SUPPORT_CN=$support_cn $runner $script_name $args
}

process_args() {
    for arg in "$@"; do
        case $arg in
            --no-modify-dns)
               is_support_dns_modify=0
               ;;
            *)
                ;;
        esac
    done
}

# 新增Docker镜像源配置函数
configure_docker_mirror() {
    if [ $support_cn -eq 1 ]; then
        echo "配置Docker镜像源..."
    else
        echo "Configuring Docker mirrors..."
    fi

    # 创建Docker配置目录
    mkdir -p /etc/docker

    # 配置多个国内镜像源
    cat <<EOF > /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com",
    "https://registry.docker-cn.com"
  ]
}
EOF

    # 重启Docker服务使配置生效
    if systemctl is-active --quiet docker; then
        systemctl restart docker
    fi
}

main() {
    check_support_cn

    trap do_clean EXIT
    [ $support_cn -eq 1 ] && echo -e "${SH_GREEN}开始运行脚本 $script_name${SH_PLAIN}" || echo -e "${SH_GREEN}Starting script $script_name${SH_PLAIN}"

    arch=$(uname -m)
    case $arch in
        x86_64)
            runner_url=$RUNNER_URL_X86
            ;;
        aarch64)
            runner_url=$RUNNER_URL_ARM64
            ;;
        armv7l)
            runner_url=$RUNNER_URL_ARM
            ;;
        *)
            arch_fail=1
            everything_is_fine=0
            exit 1
            ;;
    esac

    process_args "$@"
    change_dns
    
    # 新增Docker镜像源配置
    configure_docker_mirror

    start
    restore_dns
}

main "$@"