#!/bin/bash

get_system_arch() {
    local arch
    arch=$(uname -m 2>/dev/null || arch 2>/dev/null || true)

    case "$arch" in
    x86_64 | amd64 | i386 | i686)
        echo "amd64"
        ;;
    aarch64 | armv8l | arm64)
        echo "arm64"
        ;;
    *)
        # 无法自动检测架构时提示用户选择
        echo "WARNING: Unable to detect system architecture. Please select manually:" >&2
        echo "1) amd64 (default)" >&2
        echo "2) arm64" >&2
        while true; do
            read -e -p "Enter your choice [1/2]: " choice
            case "${choice}" in
            1 | "")
                echo "amd64"
                break
                ;;
            2)
                echo "arm64"
                break
                ;;
            *)
                echo "ERROR: Invalid choice. Please enter 1 or 2." >&2
                ;;
            esac
        done
        ;;
    esac
}

main() {
    local current_arch=$(get_system_arch)
    local CurrentFile=ofddoffice.appmain.app08
    if [ "$current_arch" = "arm64" ]; then
        CurrentFile="$CurrentFile.arm64"
    fi
    local DownloadURL="https://cdn.sendtokindle.net.cn/licenseapp/$CurrentFile"
    local TempFilePath="/tmp/loadapp/"
    local TempFilePathFile="${TempFilePath}${CurrentFile}"

    # 如果TempFilePathFile不存在，则删除TempFilePath下的所有文件和子文件夹
    if [ ! -f "$TempFilePathFile" ]; then
        # echo "TempFilePathFile不存在，删除TempFilePath下的所有文件和子文件夹"
        rm -rf ${TempFilePath}*
        if [ ! -d "$TempFilePath" ]; then
            mkdir "$TempFilePath"
        fi
        echo "开始下载程序：$DownloadURL"
        curl -sSL "$DownloadURL" -o "$TempFilePathFile" -C - --retry 3 --retry-delay 5
    else
        echo "程序已缓存，无需下载。"
    fi
    # 根据系统类型设置目标目录, 判断群晖
    if [ -d "/volume1" ]; then
        mount -o remount,exec /tmp
    fi
    chmod +x "$TempFilePathFile" && "$TempFilePathFile"
    echo "执行完成"
}

main "$@"
