#!/data/data/com.termux/files/usr/bin/bash
#===============================================================================
#  Termux 一键安装并开启 SSH 脚本
#  适用环境: Android Termux
#  使用方法:
#    1. 修改下方配置项（密码、端口等）
#    2. chmod +x termux-ssh-setup.sh
#    3. ./termux-ssh-setup.sh
#===============================================================================

set -e

#===============================================================================
#  ★★★ 在这里修改你的配置 ★★★
#===============================================================================

# SSH 登录密码（必改！设为你自己的密码）
SSH_PASSWORD="123456"

# SSH 监听端口（默认 8022，Termux 无法使用 1024 以下端口）
SSH_PORT=8022

# 是否更换为清华镜像源（国内用户推荐开启: true/false）
USE_TUNA_MIRROR=true

# 是否设置开机自启（true/false）
ENABLE_AUTOSTART=true

# 是否安装额外工具 nmap rsync netcat（true/false）
INSTALL_EXTRAS=false

#===============================================================================
#  ★★★ 配置结束，以下无需修改 ★★★
#===============================================================================

# ---------- 颜色定义 ----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'  # No Color

# ---------- 工具函数 ----------
info()    { echo -e "${CYAN}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*"; }

# ---------- 检测是否在 Termux 环境中运行 ----------
check_termux() {
    if [ -z "$TERMUX_VERSION" ] && [ ! -d "/data/data/com.termux" ]; then
        error "此脚本只能在 Termux 环境中运行！"
        exit 1
    fi
    success "检测到 Termux 环境"
}

# ---------- 更换国内镜像源 ----------
change_mirror() {
    echo ""
    if [ "$USE_TUNA_MIRROR" != "true" ]; then
        warn "跳过镜像源更换，将使用默认源"
        return
    fi

    info "正在更换为 TUNA 清华镜像源..."
    sed -i 's|^\(deb\s\+\)https://termux.dev/packages/termux-main|\1https://mirrors.tuna.tsinghua.edu.cn/termux/termux-main|g' /data/data/com.termux/files/usr/etc/apt/sources.list 2>/dev/null || \
    sed -i 's|^\(deb\s\+\)https://packages.termux.dev/apt/termux-main|\1https://mirrors.tuna.tsinghua.edu.cn/termux/termux-main|g' /data/data/com.termux/files/usr/etc/apt/sources.list 2>/dev/null || \
    echo "deb https://mirrors.tuna.tsinghua.edu.cn/termux/termux-main stable main" > /data/data/com.termux/files/usr/etc/apt/sources.list

    # 同时更换 game-repo 和 science-repo（如果存在）
    if [ -f /data/data/com.termux/files/usr/etc/apt/sources.list.d/game.list ]; then
        sed -i 's|https://termux.dev/packages/termux-game|https://mirrors.tuna.tsinghua.edu.cn/termux/termux-game|g' /data/data/com.termux/files/usr/etc/apt/sources.list.d/game.list 2>/dev/null
        sed -i 's|https://packages.termux.dev/apt/termux-game|https://mirrors.tuna.tsinghua.edu.cn/termux/termux-game|g' /data/data/com.termux/files/usr/etc/apt/sources.list.d/game.list 2>/dev/null
    fi
    if [ -f /data/data/com.termux/files/usr/etc/apt/sources.list.d/science.list ]; then
        sed -i 's|https://termux.dev/packages/termux-science|https://mirrors.tuna.tsinghua.edu.cn/termux/termux-science|g' /data/data/com.termux/files/usr/etc/apt/sources.list.d/science.list 2>/dev/null
        sed -i 's|https://packages.termux.dev/apt/termux-science|https://mirrors.tuna.tsinghua.edu.cn/termux/termux-science|g' /data/data/com.termux/files/usr/etc/apt/sources.list.d/science.list 2>/dev/null
    fi

    success "镜像源已更换为 TUNA 清华源"
}

# ---------- 更新软件包 ----------
update_packages() {
    info "正在更新软件包列表..."
    pkg update -y && pkg upgrade -y
    success "软件包已更新"
}

# ---------- 安装 OpenSSH ----------
install_openssh() {
    if command -v sshd &>/dev/null; then
        success "OpenSSH 已安装，跳过安装步骤"
    else
        info "正在安装 OpenSSH..."
        pkg install openssh -y
        success "OpenSSH 安装完成"
    fi
}

# ---------- 设置用户密码 ----------
set_password() {
    echo ""
    info "正在设置 SSH 登录密码..."

    local user_passwd="$SSH_PASSWORD"

    if [ -z "$user_passwd" ]; then
        error "密码未设置！请在脚本顶部 SSH_PASSWORD 处填写密码"
        exit 1
    fi

    # Termux 中设置当前用户密码
    echo "$user_passwd" | passwd root 2>/dev/null && success "root 用户密码已设置" || {
        echo "$user_passwd" | passwd "$(whoami)" 2>/dev/null && success "用户 $(whoami) 密码已设置" || {
            echo "$(whoami):$user_passwd" | chpasswd 2>/dev/null && success "用户 $(whoami) 密码已设置" || {
                error "密码设置失败，请手动执行: passwd"
                exit 1
            }
        }
    }
}

# ---------- 生成 SSH 主机密钥 ----------
generate_host_keys() {
    info "正在检查 SSH 主机密钥..."
    local key_dir="/data/data/com.termux/files/usr/etc/ssh"
    if [ ! -f "$key_dir/ssh_host_rsa_key" ]; then
        ssh-keygen -A
        success "SSH 主机密钥已生成"
    else
        success "SSH 主机密钥已存在，跳过生成"
    fi
}

# ---------- 配置 sshd ----------
configure_sshd() {
    local sshd_config="/data/data/com.termux/files/usr/etc/ssh/sshd_config"

    info "正在配置 sshd..."

    # 确保配置文件存在
    if [ ! -f "$sshd_config" ]; then
        cp "${sshd_config}.default" "$sshd_config" 2>/dev/null || true
    fi

    # 使用脚本顶部配置的端口
    local ssh_port="$SSH_PORT"

    # 修改配置项（如果已存在则替换，否则追加）
    local config_items=(
        "Port ${ssh_port}"
        "PasswordAuthentication yes"
        "PermitRootLogin yes"
    )

    for item in "${config_items[@]}"; do
        local key="${item%% *}"
        local value="${item#* }"
        if grep -q "^${key}" "$sshd_config" 2>/dev/null; then
            sed -i "s/^${key}.*/${key} ${value}/" "$sshd_config"
        elif grep -q "^#${key}" "$sshd_config" 2>/dev/null; then
            sed -i "s/^#${key}.*/${key} ${value}/" "$sshd_config"
        else
            echo "${key} ${value}" >> "$sshd_config"
        fi
    done

    success "sshd 配置完成 (端口: ${ssh_port})"
}

# ---------- 启动 sshd 服务 ----------
start_sshd() {
    info "正在启动 sshd 服务..."

    # 检查是否已经在运行
    if pgrep -f "sshd" >/dev/null 2>&1; then
        warn "sshd 已经在运行中，正在重启..."
        pkill sshd 2>/dev/null || true
        sleep 1
    fi

    sshd
    sleep 1

    if pgrep -f "sshd" >/dev/null 2>&1; then
        success "sshd 服务已启动"
    else
        error "sshd 启动失败，请检查配置"
        error "可手动运行 sshd -D 查看调试信息"
        exit 1
    fi
}

# ---------- 获取本机 IP 地址 ----------
get_ip_address() {
    local ip=""
    # 优先尝试 WiFi IP
    ip=$(ip addr show wlan0 2>/dev/null | grep 'inet ' | awk '{print $2}' | cut -d/ -f1)
    # 如果 wlan0 没获取到，尝试其他网络接口
    if [ -z "$ip" ]; then
        ip=$(ip addr show 2>/dev/null | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d/ -f1 | head -1)
    fi
    if [ -z "$ip" ]; then
        ip=$(ifconfig 2>/dev/null | grep 'inet addr' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d: -f2 | head -1)
    fi
    echo "${ip:-未知}"
}

# ---------- 输出连接信息 ----------
print_connection_info() {
    local ip
    ip=$(get_ip_address)
    local user
    user=$(whoami)

    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}          ${BOLD}SSH 服务已成功启动！${NC}                       ${GREEN}║${NC}"
    echo -e "${GREEN}╠══════════════════════════════════════════════════════╣${NC}"
    echo -e "${GREEN}║${NC}                                                      ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  ${CYAN}连接命令:${NC}                                        ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  ${BOLD}ssh ${user}@${ip} -p ${SSH_PORT}${NC}                    ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                      ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  ${CYAN}连接信息:${NC}                                        ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    用户名: ${BOLD}${user}${NC}                                ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    IP 地址: ${BOLD}${ip}${NC}                            ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    端  口: ${BOLD}${SSH_PORT}${NC}                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    密  码: ${BOLD}${SSH_PASSWORD}${NC}                            ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                      ${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${YELLOW}提示:${NC}"
    echo -e "  1. 确保手机和电脑在同一局域网内"
    echo -e "  2. 如果无法连接，检查手机防火墙/热点设置"
    echo -e "  3. 每次重启 Termux 后需要重新运行 ${CYAN}sshd${NC} 启动服务"
    echo -e "  4. 停止 SSH 服务: ${CYAN}pkill sshd${NC}"
    echo -e "  5. 查看 SSH 服务状态: ${CYAN}pgrep -l sshd${NC}"
    echo ""
}

# ---------- 可选: 设置开机自启 ----------
setup_autostart() {
    echo ""
    if [ "$ENABLE_AUTOSTART" != "true" ]; then
        info "跳过开机自启设置"
        return
    fi

    local bashrc="/data/data/com.termux/files/home/.bashrc"
    local profile="/data/data/com.termux/files/home/.profile"
    local marker="# >>> termux-ssh-autostart >>>"

    # 检查是否已添加
    if grep -q "termux-ssh-autostart" "$bashrc" 2>/dev/null || \
       grep -q "termux-ssh-autostart" "$profile" 2>/dev/null; then
        warn "自启动配置已存在，跳过"
        return
    fi

    # 优先写入 .bashrc
    local target_file="$bashrc"
    if [ ! -f "$target_file" ]; then
        target_file="$profile"
    fi

    {
        echo ""
        echo "$marker"
        echo "# 自动启动 SSH 服务"
        echo "if ! pgrep -x sshd >/dev/null 2>&1; then"
        echo "    sshd >/dev/null 2>&1"
        echo "fi"
        echo "# <<< termux-ssh-autostart <<<"
    } >> "$target_file"

    success "已设置 SSH 开机自启 (写入 $target_file)"
}

# ---------- 可选: 安装额外实用工具 ----------
install_extras() {
    echo ""
    if [ "$INSTALL_EXTRAS" != "true" ]; then
        info "跳过额外工具安装"
        return
    fi

    info "正在安装额外工具..."
    pkg install -y nmap rsync netcat-openbsd
    success "额外工具安装完成"
}

#===============================================================================
#  主流程
#===============================================================================
main() {
    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}      ${BOLD}Termux SSH 一键安装配置脚本${NC}                     ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}      ${CYAN}One-Click SSH Setup for Termux${NC}                 ${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "  密码: ${BOLD}${SSH_PASSWORD}${NC}  端口: ${BOLD}${SSH_PORT}${NC}  镜像源: ${BOLD}${USE_TUNA_MIRROR}${NC}  自启: ${BOLD}${ENABLE_AUTOSTART}${NC}"
    echo ""

    # Step 1: 环境检测
    check_termux

    # Step 2: 镜像源
    change_mirror

    # Step 3: 更新软件包
    update_packages

    # Step 4: 安装 OpenSSH
    install_openssh

    # Step 5: 设置密码
    set_password

    # Step 6: 生成主机密钥
    generate_host_keys

    # Step 7: 配置 sshd
    configure_sshd

    # Step 8: 启动 sshd
    start_sshd

    # Step 9: 输出连接信息
    print_connection_info

    # Step 10: 开机自启
    setup_autostart

    # Step 11: 额外工具
    install_extras

    echo ""
    success "全部配置完成！现在可以通过 SSH 连接到你的手机了"
}

# 运行主函数
main
