#!/bin/bash

echo "========== FRP客户端部署脚本（仅SSH端口转发）=========="
echo "服务端地址: v4-vpn.lizhiyun.top:27000"
echo "======================================================"

# 配置参数
SERVER_ADDR="v4-vpn.lizhiyun.top"
SERVER_PORT="27000"
AUTH_TOKEN="1qaz@WSX"
CLIENT_USER="frpc"
LOG_DIR="/var/log/frp"
INSTALL_DIR="/usr/local/frp"
CONFIG_FILE="/usr/local/frp/frpc.toml"
SERVICE_NAME="frpc"

# 获取用户输入
echo "请输入以下信息配置SSH端口转发："
read -p "客户端名称（建议使用字母、数字、短横线，如my-server-ssh）: " CLIENT_NAME_INPUT
read -p "远程端口号（6000-6999之间，如6001）: " REMOTE_PORT_INPUT
read -p "本地SSH端口 [默认: 22]: " LOCAL_PORT_INPUT

# 设置默认值
LOCAL_PORT=${LOCAL_PORT_INPUT:-22}
CLIENT_NAME=${CLIENT_NAME_INPUT:-"ssh-$(hostname -s)"}
REMOTE_PORT=${REMOTE_PORT_INPUT:-6001}

# 验证远程端口号是否在6000-6999范围内
if [[ $REMOTE_PORT -lt 6000 ]] || [[ $REMOTE_PORT -gt 6999 ]]; then
    echo "错误: 远程端口号 $REMOTE_PORT 不在允许范围 6000-6999 内"
    echo "请重新运行脚本并输入正确的端口号"
    exit 1
fi

echo -e "\n配置信息确认："
echo "客户端名称: $CLIENT_NAME"
echo "本地SSH端口: $LOCAL_PORT"
echo "远程端口号: $REMOTE_PORT"
echo "服务端地址: $SERVER_ADDR:$SERVER_PORT"
read -p "确认配置是否正确？[Y/n]: " CONFIRM

if [[ $CONFIRM =~ [Nn] ]]; then
    echo "取消部署，请重新运行脚本"
    exit 0
fi

# 1. 下载和安装FRP.

# 安装必要工具
echo "安装必要工具..."
yum install -y wget tar vim net-tools firewalld

echo "步骤1: 下载和安装FRP客户端..."
cd /tmp

FRP_PACKAGE="frp_0.52.3_linux_amd64.tar.gz"
DOWNLOAD_URL="https://download.lizhiyun.top/${FRP_PACKAGE}"

echo "从 ${DOWNLOAD_URL} 下载FRP..."
if wget --timeout=30 --tries=3 "${DOWNLOAD_URL}"; then
    echo "下载成功"
else
    echo "错误: FRP下载失败，请检查网络"
    exit 1
fi

# 解压
tar -zxvf "$FRP_PACKAGE"

# 创建安装目录
sudo mkdir -p $INSTALL_DIR
sudo cp frp_0.52.3_linux_amd64/frpc $INSTALL_DIR/
sudo cp frp_0.52.3_linux_amd64/frpc.toml $INSTALL_DIR/

# 2. 创建frpc用户（如果不存在）
echo "步骤2: 创建frpc用户..."
if ! id "$CLIENT_USER" &>/dev/null; then
    sudo useradd -r -s /sbin/nologin "$CLIENT_USER"
    echo "用户 $CLIENT_USER 创建成功"
fi

# 3. 配置FRP客户端
echo "步骤3: 配置FRP客户端..."

# 创建配置文件
cat > /tmp/frpc.toml << EOF
serverAddr = "$SERVER_ADDR"
serverPort = $SERVER_PORT
auth.method = "token"
auth.token = "$AUTH_TOKEN"

# 日志配置
log.to = "$LOG_DIR/frpc.log"
log.level = "info"
log.maxDays = 3

# 连接池配置
transport.tcpMux = true
transport.maxPoolCount = 5
transport.heartbeatInterval = 10
transport.heartbeatTimeout = 90

# 客户端元数据
metadatas.hostname = "$(hostname)"
metadatas.client_name = "$CLIENT_NAME"

# SSH端口转发配置
[[proxies]]
name = "$CLIENT_NAME"
type = "tcp"
localIP = "127.0.0.1"
localPort = $LOCAL_PORT
remotePort = $REMOTE_PORT
EOF

# 移动配置文件到安装目录
sudo mv /tmp/frpc.toml $CONFIG_FILE

# 4. 创建日志目录和设置权限
echo "步骤4: 设置目录权限..."
sudo mkdir -p $LOG_DIR
sudo chown -R $CLIENT_USER:$CLIENT_USER $LOG_DIR
sudo chmod 755 $LOG_DIR

sudo chown -R $CLIENT_USER:$CLIENT_USER $INSTALL_DIR
sudo chmod 755 $INSTALL_DIR
sudo chmod 755 $INSTALL_DIR/frpc

# 5. 创建systemd服务
echo "步骤5: 创建systemd服务..."
cat > /tmp/frpc.service << EOF
[Unit]
Description=Frp Client Service
After=network.target
Wants=network.target

[Service]
Type=simple
User=$CLIENT_USER
Group=$CLIENT_USER
Restart=on-failure
RestartSec=5s
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/frpc -c $CONFIG_FILE
ExecReload=/bin/kill -HUP \$MAINPID
LimitNOFILE=1048576

# 设置日志目录权限
PermissionsStartOnly=true
ExecStartPre=/bin/mkdir -p $LOG_DIR
ExecStartPre=/bin/chown $CLIENT_USER:$CLIENT_USER $LOG_DIR
ExecStartPre=/bin/chmod 755 $LOG_DIR

StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

sudo mv /tmp/frpc.service /etc/systemd/system/$SERVICE_NAME.service

# 6. 启动FRP客户端服务
echo "步骤6: 启动FRP客户端服务..."
sudo systemctl daemon-reload
sudo systemctl enable $SERVICE_NAME
sudo systemctl start $SERVICE_NAME

# 7. 验证服务
echo "步骤7: 验证服务运行状态..."
sleep 3

echo -e "\n检查服务状态:"
if sudo systemctl status $SERVICE_NAME --no-pager -l; then
    echo "✓ FRP客户端服务已启动"
else
    echo "✗ FRP客户端服务启动失败"
    echo "查看详细日志: sudo journalctl -u $SERVICE_NAME -n 30 --no-pager"
fi

echo -e "\n检查进程:"
ps aux | grep frpc | grep -v grep

# 8. 测试连接信息
echo -e "\n========== SSH连接信息 =========="
echo "客户端名称: $CLIENT_NAME"
echo "服务器地址: $SERVER_ADDR"
echo "远程端口号: $REMOTE_PORT"
echo "本地SSH端口: $LOCAL_PORT"
echo "=================================="

# 显示配置摘要
echo -e "\n当前代理配置摘要:"
cat << EOF
客户端名称 = $CLIENT_NAME
代理类型 = tcp
本地IP = 127.0.0.1
本地端口 = $LOCAL_PORT
远程端口 = $REMOTE_PORT
EOF

# 10. 检查防火墙
echo -e "\n========== 防火墙检查 =========="
if command -v firewall-cmd &> /dev/null; then
    echo "检测到firewalld，检查本地SSH端口是否开放..."
    if sudo firewall-cmd --query-port=${LOCAL_PORT}/tcp | grep -q "yes"; then
        echo "✓ 本地SSH端口 $LOCAL_PORT/tcp 已开放"
    else
        echo "⚠ 本地SSH端口 $LOCAL_PORT/tcp 未开放"
        read -p "是否开放本地SSH端口 $LOCAL_PORT/tcp？[Y/n]: " OPEN_FIREWALL
        if [[ ! $OPEN_FIREWALL =~ [Nn] ]]; then
            sudo firewall-cmd --permanent --add-port=${LOCAL_PORT}/tcp
            sudo firewall-cmd --reload
            echo "已开放本地SSH端口 $LOCAL_PORT/tcp"
        fi
    fi
else
    echo "未安装firewalld，请确保本地SSH端口 $LOCAL_PORT 可访问"
fi

# 11. 检查本地SSH服务
echo -e "\n========== 本地SSH服务检查 =========="
if sudo systemctl is-active --quiet sshd || sudo systemctl is-active --quiet ssh; then
    echo "✓ SSH服务正在运行"
else
    echo "⚠ SSH服务未运行"
    echo "启动SSH服务命令:"
    echo "sudo systemctl start sshd 或 sudo systemctl start ssh"
fi

sudo systemctl status frpc

echo -e "\n========== 部署完成 =========="
echo "服务状态: sudo systemctl status $SERVICE_NAME"
echo "查看日志: sudo tail -f /var/log/frp/frpc.log"
echo "重启服务: sudo systemctl restart $SERVICE_NAME"
echo "======================================"

