#!/usr/bin/env bash
# Copyright (C) 2026 PRIMLOGiC
# SPDX-License-Identifier: AGPL-3.0-only
#
# ForeONE online installer bootstrap. See LICENSE for the full license text.

set -euo pipefail

RELEASE_VERSION="v2612.009"
DOWNLOAD_BASE_URL="${FOREONE_DOWNLOAD_BASE_URL:-https://www.primlogic.cn/deploy/releases/v2612.009-installer-v1.0.17}"
INSTALLER_SHA256="21ce1af34d452f5e6d77e1722447215c2d93aed72deaaa904ba00f490a2a324b"
INSTALLER_REVISION="v1.0.17"
INSTALLER_BASE_URL="https://www.primlogic.cn/deploy/installers/v1.0.17"
RELEASE_MANIFEST_SHA256="3acf9252b1bb4e11b9ecdac17eeb3a09cf1ee3d8d8282ce6b6cfc6e87dc83ac0"

red='\033[31m'
green='\033[32m'
yellow='\033[33m'
cyan='\033[36m'
bold='\033[1m'
reset='\033[0m'

language="${FOREONE_INSTALLER_LANG:-}"

text() {
    if [ "$language" = "en" ]; then
        printf '%s' "$2"
    else
        printf '%s' "$1"
    fi
}

fail() {
    echo -e "${red}$(text "错误" "Error")：$(text "$1" "${2:-$1}")${reset}" >&2
    exit 1
}

select_language() {
    case "$language" in
        zh|zh-CN|zh_CN) language="zh"; return 0 ;;
        en|en-US|en_US) language="en"; return 0 ;;
        "") ;;
        *) language="zh"; return 0 ;;
    esac

    if [ "$#" -eq 0 ] && { [ -t 0 ] || (: </dev/tty) 2>/dev/null; }; then
        echo ""
        echo "选择安装语言 / Select installer language"
        echo ""
        echo "1) 中文"
        echo "2) English"
        echo ""
        choice=""
        if [ -t 0 ]; then
            read -r -p "> " choice || choice=""
        else
            printf '> '
            read -r choice </dev/tty || choice=""
        fi
        case "$choice" in
            2|en|EN|English|english) language="en" ;;
            *) language="zh" ;;
        esac
    else
        case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
            en*|EN*) language="en" ;;
            *) language="zh" ;;
        esac
    fi
}

show_brand_rule() {
    local width="$1" index
    printf '%b' "$cyan"
    for ((index = 0; index < width; index++)); do
        printf '═'
    done
    printf '%b\n' "$reset"
}

show_brand() {
    local width=46 columns="${COLUMNS:-80}"
    [ "$language" = "en" ] && width=68
    if [[ "$columns" =~ ^[0-9]+$ ]] && [ "$columns" -gt 0 ] && [ $((columns - 2)) -lt "$width" ]; then
        width=$((columns - 2))
        [ "$width" -ge 8 ] || width=8
    fi
    echo ""
    show_brand_rule "$width"
    echo -e "${cyan}${bold}*** ForeONE ***${reset}"
    if [ "$language" = "en" ]; then
        echo "Intelligent operations and secure access platform"
    else
        echo "智能运维与安全访问平台"
    fi
    echo -e "\033[37mPowered by PRIMLOGiC${reset}"
    show_brand_rule "$width"
    echo ""
}

[ "$(id -u)" -eq 0 ] \
    || fail "请使用 root 权限运行 ForeONE 安装命令" "Run the ForeONE installation command with root privileges"

case "$(uname -s)/$(uname -m)" in
    Linux/x86_64|Linux/amd64) ;;
    *) fail "当前只支持 Linux x86_64" "Only Linux x86_64 is currently supported" ;;
esac

command -v curl >/dev/null 2>&1 \
    || fail "系统未安装 curl" "curl is not installed"
command -v sha256sum >/dev/null 2>&1 \
    || fail "系统未安装 sha256sum" "sha256sum is not installed"

invoke_manager() {
    local executable="$1"
    shift
    local args=("$@")
    if [ "${#args[@]}" -eq 0 ] && [ ! -t 0 ]; then
        if (: </dev/tty) 2>/dev/null; then
            FOREONE_MANAGER_BOOTSTRAPPED=1 "$executable" </dev/tty
            return $?
        fi
        args=(install -y)
    fi
    FOREONE_MANAGER_BOOTSTRAPPED=1 "$executable" "${args[@]}"
}

select_language "$@"
export FOREONE_INSTALLER_LANG="$language"

# Once downloaded and verified, the manager is persisted locally. Reuse it
# only when its bytes match this bootstrap's manager checksum, so
# routine updates and opening the menu do not download an unchanged manager.
# This entry supplies the product descriptor even when the binary is reused.
manager_install_path="${FOREONE_MANAGER_INSTALL_PATH:-/usr/local/bin/foreone}"
local_manager="${FOREONE_MANAGER_COMMAND:-$manager_install_path}"
show_brand
if [ -n "$INSTALLER_REVISION" ]; then
    export FOREONE_INSTALLER_PRODUCT_VERSION="$RELEASE_VERSION"
    export FOREONE_INSTALLER_MANIFEST_SHA256="$RELEASE_MANIFEST_SHA256"
    export FOREONE_INSTALLER_RELEASE_BASE_URL="${DOWNLOAD_BASE_URL%/}"
else
    unset FOREONE_INSTALLER_PRODUCT_VERSION FOREONE_INSTALLER_MANIFEST_SHA256 FOREONE_INSTALLER_RELEASE_BASE_URL
fi
if [ -x "$local_manager" ] \
    && [ "$(sha256sum "$local_manager" 2>/dev/null | awk '{print $1}')" = "$INSTALLER_SHA256" ]; then
    echo -e "${yellow}$(text "正在校验安装文件…" "Verifying installation files...")${reset}"
    echo -e "${green}$(text "安装文件校验通过" "Installation files verified")${reset}"
    invoke_manager "$local_manager" "$@"
    exit $?
fi

umask 077
work_dir="$(mktemp -d /tmp/foreone-manager.XXXXXX)"
manager="$work_dir/foreone"
manager_install_tmp=""
cleanup() {
    rm -rf -- "$work_dir"
    [ -z "$manager_install_tmp" ] || rm -f -- "$manager_install_tmp"
}
trap cleanup EXIT HUP INT TERM

echo -e "${yellow}$(text "正在下载安装器中……" "Downloading the installer...")${reset}"

curl_args=(
    --proto '=https' --tlsv1.2 --fail --location
    --retry 3 --connect-timeout 10
)
if [ -t 2 ]; then
    curl_args+=(--progress-bar)
else
    curl_args+=(--silent --show-error)
fi
curl "${curl_args[@]}" \
    --output "$manager" \
    "${INSTALLER_BASE_URL:-${DOWNLOAD_BASE_URL%/}}/foreone-installer-amd64" \
    || fail \
        "下载安装器失败，已停止本次操作。请检查网络、系统时间和 TLS 证书后，从原可信发布来源重试。" \
        "Failed to download the installer. This operation has stopped. Check the network, system time, and TLS certificate, then retry from the original trusted release source."

echo -e "${yellow}$(text "正在校验安装文件…" "Verifying installation files...")${reset}"
actual_sha256="$(sha256sum "$manager" | awk '{print $1}')"
[ "$actual_sha256" = "$INSTALLER_SHA256" ] \
    || fail \
        "安装文件校验失败：部署管理器摘要不一致。已停止本次操作。请从原可信发布来源重新下载后重试；仍失败时，请保留错误信息并联系维护人员。" \
        "Installation file verification failed: the deployment manager checksum does not match. This operation has stopped. Download it again from the original trusted release source and retry. If the problem persists, keep the error details and contact the maintainer."
echo -e "${green}$(text "安装文件校验通过" "Installation files verified")${reset}"
manager_install_tmp="${manager_install_path}.tmp.$$"
install -m 0755 "$manager" "$manager_install_tmp"
mv -f "$manager_install_tmp" "$manager_install_path"
manager_install_tmp=""
manager="$manager_install_path"

invoke_manager "$manager" "$@"
