# -*- coding: utf-8 -*-
"""
上传登录认证功能到 192.168.5.60 服务器
"""

import paramiko
import os
import time

# 从环境变量读取服务器配置
HOST = os.environ.get('SSH_HOST', '192.168.5.60')
USER = os.environ.get('SSH_USER', 'ubains')
PASSWORD = os.environ.get('SSH_PASSWORD', '')
REMOTE_BASE = '/opt/troubleshoot'

if not PASSWORD:
    print("错误：SSH_PASSWORD 环境变量未设置")
    print("请设置环境变量或创建 .env 文件")
    exit(1)

# 本地路径
LOCAL_BASE = r'E:\github\ubains-module-test\develop\.claude\skills\Troubleshoot\code'

# 需要上传的文件
FILES_TO_UPLOAD = [
    ('web/auth.py', 'web/auth.py'),
    ('web/decorators.py', 'web/decorators.py'),
    ('web/server.py', 'web/server.py'),
    ('web/templates/login.html', 'web/templates/login.html'),
    ('web/templates/index.html', 'web/templates/index.html'),
    ('requirements.txt', 'requirements.txt'),
]

def upload_files():
    """上传文件到服务器"""
    print("="*60)
    print("上传登录认证功能到服务器 192.168.5.60")
    print("="*60)

    # 连接 SSH
    print("\n[1/6] 连接 SSH...")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(HOST, username=USER, password=PASSWORD)
        print("OK: SSH 连接成功")

        # 备份原文件
        print("\n[2/6] 备份原文件...")
        timestamp = time.strftime('%Y%m%d_%H%M%S')
        files_to_backup = ['web/server.py', 'web/templates/index.html']

        for file_path in files_to_backup:
            stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE} && cp {file_path} {file_path}.bak.{timestamp}')
            stdout.read()

        print(f"OK: 已备份到 *.bak.{timestamp}")

        # 安装依赖
        print("\n[3/6] 安装依赖包...")
        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE}/code && pip install werkzeug>=2.3.0')
        stdout.read()
        print("OK: werkzeug 已安装")

        # 上传新文件
        print("\n[4/6] 上传新文件...")
        sftp = ssh.open_sftp()

        for local_rel, remote_rel in FILES_TO_UPLOAD:
            local_path = os.path.join(LOCAL_BASE, local_rel)
            remote_path = f"{REMOTE_BASE}/{remote_rel}"

            print(f"  上传: {local_rel}")
            try:
                sftp.put(local_path, remote_path)
                print(f"    OK: 已上传")
            except Exception as e:
                print(f"    错误: {e}")

        sftp.close()

        # 重启服务
        print("\n[5/6] 重启服务...")
        stdin, stdout, stderr = ssh.exec_command('pkill -f "python.*server.py"')
        stdout.read()
        time.sleep(2)

        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE}/web && nohup python server.py > /tmp/troubleshoot.log 2>&1 &')
        stdout.read()
        time.sleep(3)
        print("OK: 服务已重启")

        # 验证服务
        print("\n[6/6] 验证服务...")
        stdin, stdout, stderr = ssh.exec_command('curl -s -I http://localhost:8088/login | head -n 1')
        result = stdout.read().decode()

        if '200 OK' in result or '302' in result:
            print("OK: 登录页面可访问")
        else:
            print(f"警告: 登录页面访问异常 - {result}")

        # 检查主页是否重定向到登录页
        stdin, stdout, stderr = ssh.exec_command('curl -s -I http://localhost:8088/ | head -n 1')
        result = stdout.read().decode()

        if '302' in result:
            print("OK: 未登录访问主页正确重定向")
        else:
            print(f"提示: 主页响应 - {result}")

        print("\n" + "="*60)
        print("部署完成！")
        print(f"访问地址: http://192.168.5.60:8088")
        print("账号问题请联系管理员")
        print("="*60)

    except Exception as e:
        print(f"错误: {e}")
        return False
    finally:
        ssh.close()

    return True

if __name__ == '__main__':
    upload_files()