#!/usr/bin/env python3
"""
一键配置脚本 - 完成所有配置直到 HTTPS 可访问
"""

import paramiko
import subprocess
import time
import os
import signal

HOST = "124.223.79.92"
USER = "root"
PASSWORD = "CHENliqq123"
FRP_PATH = "C:\\Users\\Administrator\\Desktop\\BM\\frp_0.66.0_windows_amd64"
NEED_LIST_PATH = "C:\\Users\\Administrator\\Desktop\\BM\\AiTools\\Need_list"

def run_ssh_command(client, command, description=""):
    """运行 SSH 命令"""
    if description:
        print(f"[*] {description}")
    stdin, stdout, stderr = client.exec_command(command)
    output = stdout.read().decode()
    error = stderr.read().decode()
    if error and "error" in error.lower():
        print(f"  错误: {error}")
    return output

def main():
    print("=" * 70)
    print("  一键配置 - 完成所有设置直到 HTTPS 可访问")
    print("=" * 70)
    print()
    
    # 1. 连接服务器
    print("[1/6] 连接服务器...")
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(HOST, username=USER, password=PASSWORD, timeout=10)
        print("  [+] 连接成功")
    except Exception as e:
        print(f"  [-] 连接失败: {e}")
        return
    
    # 2. 配置 frps.toml
    print("\n[2/6] 配置服务器 frps.toml...")
    frps_config = """bindPort = 7000

auth.method = "token"
auth.token = "chenliqq123"

vhostHTTPPort = 80
"""
    run_ssh_command(client, f"cat > /usr/local/frp/frps.toml << 'EOF'\n{frps_config}\nEOF", "写入 frps.toml")
    output = run_ssh_command(client, "cat /usr/local/frp/frps.toml", "验证配置")
    print(f"  配置内容:\n{output}")
    
    # 3. 重启 frps
    print("\n[3/6] 重启 frps...")
    run_ssh_command(client, "killall frps 2>/dev/null; sleep 1", "停止旧进程")
    run_ssh_command(client, "nohup /usr/local/frp/frps -c /usr/local/frp/frps.toml > /var/log/frps.log 2>&1 &", "启动新进程")
    time.sleep(3)
    
    # 检查 frps 状态
    output = run_ssh_command(client, "ps aux | grep frps | grep -v grep", "检查进程")
    if "frps" in output:
        print("  [+] frps 运行中")
    else:
        print("  [-] frps 未运行")
    
    output = run_ssh_command(client, "ss -lntp | grep -E ':(7000|80)'", "检查端口")
    print(f"  端口状态:\n{output}")
    
    # 4. 配置 Caddyfile
    print("\n[4/6] 配置 Caddyfile...")
    caddyfile = """{
    auto_https disable_redirects
}

https://heigui123.top:443 {
    reverse_proxy 127.0.0.1:80
}

https://www.heigui123.top:443 {
    redir https://heigui123.top{uri} permanent
}

https://dev.heigui123.top:443 {
    reverse_proxy 127.0.0.1:80
}

https://files.heigui123.top:443 {
    reverse_proxy 127.0.0.1:80
}
"""
    run_ssh_command(client, f"cat > /etc/caddy/Caddyfile << 'EOF'\n{caddyfile}\nEOF", "写入 Caddyfile")
    run_ssh_command(client, "systemctl restart caddy", "重启 Caddy")
    time.sleep(2)
    
    output = run_ssh_command(client, "systemctl is-active caddy", "检查 Caddy 状态")
    if "active" in output:
        print("  [+] Caddy 运行中")
    else:
        print(f"  [-] Caddy 状态: {output}")
    
    client.close()
    
    # 5. 启动本地 HTTP 服务器
    print("\n[5/6] 启动本地 HTTP 服务器...")
    try:
        # 检查是否已运行
        result = subprocess.run(
            ["curl", "-s", "-o", "nul", "-w", "%{http_code}", "http://127.0.0.1:18080"],
            capture_output=True,
            text=True,
            timeout=3
        )
        if result.stdout.strip() == "200":
            print("  [+] HTTP 服务器已在运行")
        else:
            raise Exception("未运行")
    except:
        subprocess.Popen(
            ["python", "-m", "http.server", "18080"],
            cwd=NEED_LIST_PATH,
            creationflags=subprocess.CREATE_NEW_CONSOLE
        )
        time.sleep(2)
        print("  [+] HTTP 服务器已启动")
    
    # 6. 启动 FRP 客户端
    print("\n[6/6] 启动 FRP 客户端...")
    frpc_config = os.path.join(NEED_LIST_PATH, "frpc_need_list.toml")
    
    # 确保配置文件正确
    with open(frpc_config, 'w') as f:
        f.write("""serverAddr = "124.223.79.92"
serverPort = 7000

auth.method = "token"
auth.token = "chenliqq123"

[[proxies]]
name = "need_list_http"
type = "http"
localIP = "127.0.0.1"
localPort = 18080
customDomains = ["files.heigui123.top"]
""")
    
    frpc_exe = os.path.join(FRP_PATH, "frpc.exe")
    subprocess.Popen(
        [frpc_exe, "-c", frpc_config],
        creationflags=subprocess.CREATE_NEW_CONSOLE
    )
    time.sleep(3)
    print("  [+] FRP 客户端已启动")
    
    print()
    print("=" * 70)
    print("  配置完成!")
    print("=" * 70)
    print()
    print("访问地址:")
    print("  https://files.heigui123.top")
    print()
    print("本地服务:")
    print("  - HTTP 服务器: http://127.0.0.1:18080")
    print("  - FRP 客户端: 运行中")
    print()
    print("服务器服务:")
    print("  - frps: 7000, 80 端口")
    print("  - Caddy: 443 端口")

if __name__ == "__main__":
    main()
