#!/usr/bin/env bash
set -Eeuo pipefail

EASY_INSTALL_URL="${EASY_INSTALL_URL:-https://node.xboardnext.com/oo/dev/easy-install.sh}"
OLD_INSTALL_URL="https://raw.githubusercontent.com/cedar2025/xboard-node/dev/install.sh"

say() {
    if { printf '%s\n' "$*" > /dev/tty; } 2>/dev/null; then
        return
    fi
    printf '%s\n' "$*"
}

prompt() {
    if { printf '%s' "$*" > /dev/tty; } 2>/dev/null; then
        return
    fi
    printf '%s' "$*"
}

die() {
    say "错误: $*"
    exit 1
}

trim() {
    sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//'
}

normalize_command() {
    printf '%s' "$1" \
        | sed -E 's/\\[[:space:]]*/ /g' \
        | tr '\n' ' ' \
        | sed -E 's/[[:space:]]+/ /g' \
        | trim
}

read_from_tty_or_stdin() {
    local line
    if { exec 3< /dev/tty; } 2>/dev/null; then
        IFS= read -r line <&3 || true
        exec 3<&-
    else
        IFS= read -r line || true
    fi
    printf '%s' "${line:-}"
}

read_original_command() {
    if [ "$#" -gt 0 ]; then
        printf '%s\n' "$*"
        return
    fi

    say "请粘贴原作者安装命令，然后按 Enter："
    read_from_tty_or_stdin
}

extract_arg() {
    local name="$1"
    local cmd="$2"
    local value=""

    value="$(printf '%s' "$cmd" | sed -nE "s/.*--${name}=('[^']*'|\"[^\"]*\"|[^[:space:]]+).*/\1/p" | tail -n 1)"
    if [ -z "$value" ]; then
        value="$(printf '%s' "$cmd" | sed -nE "s/.*--${name}[[:space:]]+('[^']*'|\"[^\"]*\"|[^[:space:]]+).*/\1/p" | tail -n 1)"
    fi

    value="$(printf '%s' "$value" | sed -E "s/^'//; s/'$//; s/^\"//; s/\"$//")"
    printf '%s' "$value"
}

mask_token() {
    local token="$1"
    local len=${#token}
    if [ "$len" -le 8 ]; then
        printf '***'
        return
    fi
    printf '%s***%s' "${token:0:4}" "${token: -4}"
}

shell_quote() {
    printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

print_command() {
    local -a display_args=("$@")
    printf 'curl -fL %s | sudo bash -s --' "$(shell_quote "$EASY_INSTALL_URL")"
    local i
    for i in "${display_args[@]}"; do
        printf ' %s' "$(shell_quote "$i")"
    done
    printf '\n'
}

original_cmd="$(normalize_command "$(read_original_command "$@")")"
if [ -z "$original_cmd" ]; then
    die "没有读取到安装命令"
fi

if [[ "$original_cmd" != *"$OLD_INSTALL_URL"* ]]; then
    die "没有识别到原作者安装命令：${OLD_INSTALL_URL}"
fi

mode="$(extract_arg mode "$original_cmd")"
panel="$(extract_arg panel "$original_cmd")"
token="$(extract_arg token "$original_cmd")"
machine_id="$(extract_arg machine-id "$original_cmd")"
node_id="$(extract_arg node-id "$original_cmd")"
node_type="$(extract_arg node-type "$original_cmd")"

[ -n "$mode" ] || mode="machine"
[ -n "$panel" ] || die "原命令里没有找到 --panel"
[ -n "$token" ] || die "原命令里没有找到 --token"

case "$mode" in
    machine)
        [ -n "$machine_id" ] || die "machine 模式需要 --machine-id"
        ;;
    node)
        [ -n "$node_id" ] || die "node 模式需要 --node-id"
        ;;
    *)
        die "不支持的 --mode: $mode"
        ;;
esac

prompt "请输入节点域名（例如 jp2.oone.us）："
domain="$(read_from_tty_or_stdin | trim)"
[ -n "$domain" ] || die "节点域名不能为空"

args=(--mode "$mode" --panel "$panel" --token "$token")
display_args=(--mode "$mode" --panel "$panel" --token "$(mask_token "$token")")

if [ "$mode" = "machine" ]; then
    args+=(--machine-id "$machine_id")
    display_args+=(--machine-id "$machine_id")
else
    args+=(--node-id "$node_id")
    display_args+=(--node-id "$node_id")
    if [ -n "$node_type" ]; then
        args+=(--node-type "$node_type")
        display_args+=(--node-type "$node_type")
    fi
fi

args+=(--domain "$domain")
display_args+=(--domain "$domain")

say "将执行转换后的 easy-install 命令："
print_command "${display_args[@]}" | while IFS= read -r line; do say "$line"; done
say "提示：上面的 token 仅为显示时脱敏，实际执行会使用你粘贴命令中的原始 token。"

curl -fL "$EASY_INSTALL_URL" | sudo bash -s -- "${args[@]}"
