#!/usr/bin/env bash

# ==================== 工具箱模板（双模式） ====================
# 模式 1: 仅安装基础编译工具（含进度条）
# 模式 2: 部署小龙虾（依赖检测 + 安装 openclaw）
# 修复：将 read -p 改为 printf + read，兼容 Zsh/Bash

# 颜色定义
CLAW_ORANGE='\033[38;5;202m'
RED="$CLAW_ORANGE"
GREEN='\033[32m'
YELLOW="$CLAW_ORANGE"
CYAN="$CLAW_ORANGE"
WHITE='\033[1;37m'
ERR_COLOR='\033[31m'
YANSE="\033[1;31m"
NC='\033[0m'

# 居中显示白色 banner
clear
read -r -d '' BANNER_TEXT << 'BANNER'
 ___    _      _____  _       _  ___    _____  _    _
(  _`\ ( )    (  _  )( )  _  ( )(  _`\ (  _  )( )  ( )
| ( (_)| |    | (_) || | ( ) | || (_) )| ( ) |`\`\/'/'
| |  _ | |  _ |  _  || | | | | ||  _ <'| | | |  >  <
| (_( )| |_( )| | | || (_/ \_) || (_) )| (_) | /'/\`\
(____/'(____/'(_) (_)`\___x___/'(____/'(_____)(_)  (_)

作者 𝑩𝑨𝑳𝑪𝑲𝑬𝑹 版本 v最新版
BANNER

show_banner() {
    local cols=${COLUMNS:-$(tput cols 2>/dev/null || echo 80)}
    local line padding
    while IFS= read -r line; do
        padding=$(( (cols - ${#line}) / 2 ))
        [[ $padding -lt 0 ]] && padding=0
        printf "${WHITE}%*s%s${NC}\n" "$padding" "" "$line"
    done <<< "$BANNER_TEXT"
}

is_termux() {
    [[ -n "$PREFIX" && -d "$PREFIX" ]]
}

countdown() {
    local t="$1"
    for ((i = t; i >= 1; i--)); do
        echo -ne "\r${RED} $i s${NC}"
        sleep 1
    done
    echo -e "\r${RED}   ${NC}"
}

# ---------- 包安装进度条 ----------
show_pkg_progress() {
    local idx=$1 total=$2 pkg=$3
    local percent=$(( idx * 100 / total ))
    local bar_len=30
    local filled=$(( percent * bar_len / 100 ))
    local bar empty

    bar=$(printf "%${filled}s" | tr ' ' '=')
    empty=$(printf "%$(( bar_len - filled ))s" | tr ' ' ' ')

    printf "\r${GREEN}[%s%s] %3d%% 正在安装: %-15s${NC}" "$bar" "$empty" "$percent" "$pkg"
}

# ---------- 安装编译工具 ----------
step2_install_build_tools() {
    clear
    echo -e "\n${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]🔴正在安装全部所需依赖编译工具${NC}"

    if ! is_termux; then
        echo -e "${YANSE}✘错误当前环境不是Termux无法自动安装依赖${NC}"
        exit 1
    fi

    UPDATE_CMD="pkg update && pkg upgrade -y"
    INSTALL_CMD="pkg install -y"

    local DEPS=(wget curl git python3 build-essential tar xz-utils cmake nginx openssh tur-repo nodejs-22 runit jq)
    local total=$(( ${#DEPS[@]} + 1 ))   # 包含更新软件源步骤

    # 第一步：更新软件源（进度条显示）
    show_pkg_progress 1 "$total" "更新软件源"
    if ! $UPDATE_CMD > /dev/null 2>&1; then
        echo -e "\n${YANSE}警告⚠️软件源更新失败继续尝试安装${NC}"
    fi

    # 后续步骤：逐个安装包
    for i in "${!DEPS[@]}"; do
        local pkg="${DEPS[$i]}"
        local idx=$((i + 2))
        show_pkg_progress "$idx" "$total" "$pkg"
        if ! $INSTALL_CMD "$pkg" > /dev/null 2>&1; then
            echo -e "\n${ERR_COLOR}❌错误安装 $pkg 失败正在退出❗${NC}"
            exit 1
        fi
    done
    echo ""   # 完成进度条后换行

    # 创建 node/npm 软链接
    local node_dir="$PREFIX/opt/nodejs-22/bin"
    if [[ -d "$node_dir" ]]; then
        ln -sf "$node_dir/node"      "$PREFIX/bin/node"
        ln -sf "$node_dir/npm"       "$PREFIX/bin/npm"
        ln -sf "$node_dir/npx"       "$PREFIX/bin/npx"
        ln -sf "$node_dir/corepack"  "$PREFIX/bin/corepack"
    else
        echo -e "${RED}⚠️未找到 nodejs-22 目录，请手动生成软链接${NC}"
    fi

    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')]🔍正在验证依赖是否安装成功${NC}"
    if command -v node &>/dev/null && command -v npm &>/dev/null; then
        echo -e "${GREEN}✅依赖已安装${NC}"
    else
        echo -e "${YANSE}❌Node.js或npm未安装请检查${NC}"
    fi
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]🟢编译与依赖全部已安装完成${NC}"
}

# ---------- 菜单 ----------
draw_menu_box() {
    local dash=$(printf '─%.0s' {1..65})
    echo -e "${RED}╭${dash}╮${NC}"
    echo -e "${RED}│                  🦞Termux一键部署小龙虾                         │${NC}"
    echo -e "${RED}├${dash}┤${NC}"
    echo -e "${RED}│                                                                 │${NC}"
    echo -e "${RED}│ (1) 一键安装编译依赖                                            │${NC}"
    echo -e "${RED}│ (2) 一键部署AI小龙虾                                            │${NC}"
    echo -e "${RED}│ (3) 一键启动修改配置                                            │${NC}"
    echo -e "${RED}│ (4) 小龙虾的命令大全                                            │${NC}"
    echo -e "${RED}│ (0) 退出当前程序菜单                                            │${NC}"
    echo -e "${RED}│                                                                 │${NC}"
    echo -e "${RED}╰${dash}╯${NC}"
}

# ---------- 主流程 ----------
while true; do
    show_banner
    echo
    draw_menu_box

    # 原: read -p "$(echo -e '\033[38;5;208m请输入选项 [1-4] : \033[0m')" mode
    printf '\033[38;5;208m请输入选项 [1-4] : \033[0m'
    read mode

    case $mode in
        1)
            step2_install_build_tools
            echo -e "${RED}请等待5秒后返回主菜单${NC}"
            echo -e "${RED}倒计时⏰${NC}"
            countdown 5
            clear
            echo -e "${RED}👋欢迎回来${NC}"
            echo ""
            echo "💬$(curl -s https://v1.hitokoto.cn | jq -r '.hitokoto')"
            echo ""
            echo ""
            sleep 1
            ;;
        2)
            clear
            echo -e "\n${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] 📍开始自动化部署小龙虾${NC}"

            if ! command -v node &>/dev/null || ! command -v npm &>/dev/null; then
                echo -e "${ERR_COLOR}部署失败系统未检测到node.js与npm请重新安装❗${NC}"
                sleep 2
                continue
            fi

            echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] 📥 正在拉取npm国内镜像源${NC}"
            if npm config set registry https://registry.npmmirror.com; then
                echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]✅国内源切换成功${NC}"
            else
                echo -e "${YANSE}⚠警告切换镜像源失败即将使用默认源!${NC}"
            fi

            echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] 🔗 当前NPM镜像源: $(npm config get registry)${NC}"

            echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] 🔴 开始安装小龙虾${NC}"
            export GYP_DEFINES="android_ndk_path=$PREFIX" 2>/dev/null || true

            if npm install -g openclaw; then
                echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] ✅ 安装成功${NC}"
                echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] 🔎 正在验证${NC}"
                if ! command -v openclaw &>/dev/null; then
                    echo -e "${ERR_COLOR}❌错误安装后系统未找到小龙虾启动命令${NC}"
                    clear
                    sleep 5
                    continue
                fi

                echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]🎉恭喜小龙虾已部署完成${NC}"
                echo -e "${RED}请等待5秒后返回主菜单${NC}"
                echo -e "${RED}倒计时 ⏰${NC}"
                countdown 5
                clear
                echo -e "${RED} 👋 欢迎回来${NC}"
                echo ""
                echo "💬$(curl -s https://v1.hitokoto.cn | jq -r '.hitokoto')"
                echo ""
                echo ""
                sleep 1
            else
                echo -e "${ERR_COLOR}❌安装失败${NC}"
                echo -e "${RED}🧹正在清理安装痕迹${NC}"
                npm uninstall -g openclaw >/dev/null 2>&1
                npm cache clean --force
                echo -e "${RED} 🗑️清理完成${NC}"
                echo -e "${RED} ◀️正在返回主菜单${NC}"
                sleep 2
                clear
                continue
            fi
            ;;
        3)
            clear
            echo -e "${RED}🦞修改配置与启动${NC}"
            echo -e "${GREEN}🎯正在进入配置界面预计5秒${NC}"
            if command -v openclaw &>/dev/null; then
                if ! command -v jq &>/dev/null; then
                    echo -e "${YANSE}⚠缺少jq正在自动安装...${NC}"
                    pkg install -y jq || { echo -e "${ERR_COLOR}❌jq安装失败无法读取配置${NC}"; printf "◀ 按回车键返回"; read _; clear; continue; }
                fi

                # 运行 onboard 确保配置文件存在
                openclaw onboard

                # 读取端口与 token
                PORT=$(jq -r .gateway.port ~/.openclaw/openclaw.json 2>/dev/null)
                if [[ -z "$PORT" || "$PORT" == "null" ]]; then
                    PORT=18789   # 默认端口
                fi
                TOKEN=$(jq -r .gateway.auth.token ~/.openclaw/openclaw.json 2>/dev/null)

                echo -e "${RED}📊信息专区${NC}"
                echo -e "${GREEN}🔍当前端口: $PORT${NC}"
                echo -e "${GREEN}🌐你的内网小龙虾地址${NC}"
                echo -e "\033[31mhttp://127.0.0.1:$PORT\033[0m"
                echo -e "${GREEN}📝你的Token: ${TOKEN:-未设置}${NC}"
                echo -e "${GREEN}🕹复制打开小龙虾贴一贴连接即可${NC}"

                # ---------- 新增：tmux 嵌套检测 ----------
                if [[ -n "$TMUX" ]]; then
                    echo -e "${YELLOW}⚠检测到当前已在tmux会话内${NC}"
                    echo -e "${YELLOW}直接创建新会话可能导致嵌套问题${NC}"
                    printf "是否允许嵌套创建(Y/N) "
                    read nested_yn
                    if [[ "$nested_yn" =~ ^[Yy]$ ]]; then
                        echo -e "${YELLOW}🔓已取消TMUX 环境变量将强制创建新会话。${NC}"
                        unset TMUX
                    else
                        echo -e "${RED}❌已取消启动请退出 tmux 后重新运行脚本。${NC}"
                        printf "◀ 按回车键返回主菜单"
                        read _
                        clear
                        continue
                    fi
                fi

                SESSION_NAME="openclaw-gateway"

                # 如果已有同名会话，先询问是否重建
                if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
                    echo -e "${YELLOW}⚠️检测到已有网关会话 ($SESSION_NAME) 正在运行${NC}"
                    printf "是否重新启动(Y/N) "
                    read yn
                    if [[ "$yn" =~ ^[Yy]$ ]]; then
                        tmux kill-session -t "$SESSION_NAME"
                    else
                        echo -e "${GREEN}保持现有会话尝试attach${NC}"
                        # 不创建新会话，直接 attach
                        tmux attach-session -t "$SESSION_NAME"
                        # attach 返回后继续
                        echo -e "${GREEN}已从网关会话分离返回菜单${NC}"
                        printf "◀ 按回车键返回主菜单"
                        read _
                        clear
                        continue
                    fi
                fi

                # 清理可能残留的同名会话
                tmux kill-session -t "$SESSION_NAME" 2>/dev/null

                # 创建新的后台 tmux 会话，运行网关
                tmux new-session -d -s "$SESSION_NAME" \
                    "echo '🦞小龙虾网关启动中'; openclaw gateway --bind lan --port $PORT; echo '网关进程已退出，会话即将关闭'; sleep 2"

                echo -e "${GREEN}🔹 小龙虾网关已在后台会话 [${SESSION_NAME}] 中启动${NC}"
                echo -e "${YELLOW}==============================================${NC}"
                echo -e "${YELLOW}  🚀 即将进入网关监控界面${NC}"
                echo -e "${YELLOW}  💬 按下Ctrl+B然后按D即可安全分离${NC}"
                echo -e "${YELLOW}  💬 请勿直接按Ctrl+C否则会终止网关进程${NC}"
                echo -e "${YELLOW}==============================================${NC}"
                sleep 2

                # 确保没有残留的 SIGINT 陷阱（避免意外清屏退出）
                trap - SIGINT

                # 附加到会话，脚本在此阻塞直到用户分离 (Ctrl+B D)
                tmux attach-session -t "$SESSION_NAME"

                # 从 tmux 返回后，恢复提示
                echo -e "\n${GREEN}✅已从网关会话分离网关仍在后台运行${NC}"
            else
                echo -e "${ERR_COLOR}未检测到 openclaw 命令，请先执行「一键部署AI小龙虾」${NC}"
            fi
            printf "◀ 按回车键返回主菜单"
            read dummy
            clear
            ;;
        4)
            clear
            echo -e "${RED}小龙虾命令大全${NC}"
            echo -e "${RED}———————————————————————${NC}"
            echo -e "${RED}
==== 📚 版本/使用帮助 ====
openclaw --version
openclaw --help
openclaw help
==== 📦安装/初始化 ====
openclaw setup
openclaw onboard
openclaw onboard --install-daemon
openclaw onboard --uninstall-daemon
==== 🔧配置 ====
openclaw configure
openclaw config
openclaw config get <path>
openclaw config set <path> <value>
openclaw config unset <path>
==== ◀服务启停 ====
openclaw start
openclaw stop
openclaw restart
openclaw status
openclaw health
openclaw daemon
openclaw daemon start
openclaw daemon stop
openclaw daemon restart
==== 🌐网关 ====
openclaw gateway
openclaw gateway start
openclaw gateway stop
openclaw gateway restart
==== 📈面板/界面 ====
openclaw dashboard
openclaw dashboard --no-open
openclaw tui
openclaw browser
==== 🔁更新/重装/卸载 ====
openclaw update
openclaw reinstall
openclaw reset
openclaw uninstall
==== 📄日志 ====
openclaw logs
openclaw logs --limit N
openclaw logs --json
openclaw logs --plain
==== 🔍诊断/修复 ====
openclaw doctor
openclaw doctor --deep
==== 🔒备份 ====
openclaw backup
openclaw backup create
openclaw backup list
openclaw backup restore <file>
==== 🖥系统/环境 ====
openclaw system
openclaw system info
openclaw system clean
openclaw system prune
==== 🤖模型 ====
openclaw models
openclaw models list
openclaw models add
openclaw models remove
openclaw models test
==== 🧠记忆 ====
openclaw memory
openclaw memory list
openclaw memory add
openclaw memory clear
==== 🕹Agent/机器人 ====
openclaw agent
openclaw agents
openclaw agents list
openclaw agents create
openclaw agents delete
openclaw agents start
openclaw agents stop
==== 🔤ACP/MCP ====
openclaw acp
openclaw mcp
==== 📝会话 ====
openclaw sessions
openclaw sessions list
openclaw sessions kill <id>
==== 📂目录/节点/设备 ====
openclaw directory
openclaw nodes
openclaw node
openclaw devices
==== ⚡渠道（channels） ====
openclaw channels
openclaw channels list
openclaw channels add
openclaw channels remove
openclaw channels login
openclaw channels logout
openclaw channels status
openclaw channels logs
==== 💬消息（message） ====
openclaw message
openclaw message thread
openclaw message channel
openclaw message member
openclaw message role
openclaw message permissions
openclaw message ban
openclaw message kick
openclaw message timeout
openclaw message sticker
openclaw message emoji
openclaw message event
openclaw message voice
==== 🛡安全/密钥 ====
openclaw security
openclaw secrets
openclaw secrets set
openclaw secrets get
openclaw secrets unset
==== 🎯插件（plugins） ====
openclaw plugins
openclaw plugins list
openclaw plugins info <name>
openclaw plugins install <spec>
openclaw plugins install clawhub:<pkg>
openclaw plugins install /path
openclaw plugins install --force
openclaw plugins update
openclaw plugins update --all
openclaw plugins enable <name>
openclaw plugins disable <name>
openclaw plugins uninstall <name>
==== 📍技能（skills） ====
openclaw skills
openclaw skills list
openclaw skills install
openclaw skills uninstall
==== ⏰定时/任务/流程 ====
openclaw cron
openclaw tasks
openclaw flows
==== 📶DNS ====
openclaw dns
==== 🔌Webhook/Hook ====
openclaw hooks
openclaw webhooks
==== 配对/QR ====
openclaw pairing
openclaw qr
==== 🧰沙箱/审批 ====
openclaw sandbox
openclaw approvals
==== 📜文档 ====
openclaw docs
==== 🔤命令补全 ====
openclaw completion
==== 📖旧别名（兼容） ====
openclaw clawbot
openclaw voicecall
————————————————————————${NC}"
            printf "◀ 按回车键返回主菜单"
            read dummy
            clear
            ;;
        0)
            echo ""
            echo -e "${RED}✋ Goodbye朋友!${NC}"
            echo ""
            exit 0
            ;;
        *)
            echo -e "${ERR_COLOR}[$(date '+%Y-%m-%d %H:%M:%S')]✘输入为空或者输入错误请重新输入${NC}"
            sleep 1
            clear
            ;;
    esac
done