#!/bin/bash

# 远程服务器管理脚本
# 使用方法: ./manage.sh <action> [server] [user] [port]

set -e

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# 参数
ACTION=$1
REMOTE_HOST=${2:-""}
REMOTE_USER=${3:-"root"}
REMOTE_PORT=${4:-"22"}
REMOTE_DIR="/opt/proxy-server"

# 检查 .env 文件获取服务器信息
ENV_FILE="$PROJECT_DIR/docker/.env"
if [ -f "$ENV_FILE" ] && [ -z "$REMOTE_HOST" ]; then
    # 尝试从部署历史获取服务器信息
    DEPLOY_HISTORY="$PROJECT_DIR/.deploy-history"
    if [ -f "$DEPLOY_HISTORY" ]; then
        source "$DEPLOY_HISTORY"
    fi
fi

# 显示使用说明
show_usage() {
    echo -e "${BLUE}CodeLook Proxy Server 管理工具${NC}"
    echo ""
    echo "使用方法: $0 <action> [server] [user] [port]"
    echo ""
    echo "Actions:"
    echo "  status    - 查看服务状态"
    echo "  logs      - 查看服务日志"
    echo "  restart   - 重启服务"
    echo "  stop      - 停止服务"
    echo "  start     - 启动服务"
    echo "  update    - 更新服务"
    echo "  config    - 查看配置"
    echo "  stats     - 查看统计信息"
    echo ""
    echo "示例:"
    echo "  $0 status proxy.example.com"
    echo "  $0 logs proxy.example.com root 22"
    echo "  $0 restart"
}

# 检查参数
if [ -z "$ACTION" ]; then
    show_usage
    exit 1
fi

if [ -z "$REMOTE_HOST" ]; then
    echo -e "${RED}错误: 请提供服务器地址${NC}"
    echo -e "${YELLOW}提示: 运行 quick-deploy.sh 先部署服务${NC}"
    exit 1
fi

# 执行远程命令
run_remote() {
    ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "$@"
}

# 根据不同的 action 执行操作
case "$ACTION" in
    status)
        echo -e "${BLUE}📊 检查服务状态...${NC}"
        run_remote "cd $REMOTE_DIR && docker-compose ps"
        echo ""
        echo -e "${BLUE}🔍 健康检查...${NC}"
        run_remote "curl -s http://localhost:8080/health | python3 -m json.tool || echo '服务未响应'"
        ;;
        
    logs)
        echo -e "${BLUE}📜 查看服务日志...${NC}"
        echo -e "${YELLOW}提示: 按 Ctrl+C 退出${NC}"
        run_remote "cd $REMOTE_DIR && docker-compose logs -f --tail=100"
        ;;
        
    restart)
        echo -e "${YELLOW}🔄 重启服务...${NC}"
        run_remote "cd $REMOTE_DIR && docker-compose restart"
        echo -e "${GREEN}✅ 服务已重启${NC}"
        ;;
        
    stop)
        echo -e "${YELLOW}⏹️  停止服务...${NC}"
        run_remote "cd $REMOTE_DIR && docker-compose down"
        echo -e "${GREEN}✅ 服务已停止${NC}"
        ;;
        
    start)
        echo -e "${YELLOW}▶️  启动服务...${NC}"
        run_remote "cd $REMOTE_DIR && docker-compose up -d"
        echo -e "${GREEN}✅ 服务已启动${NC}"
        ;;
        
    update)
        echo -e "${BLUE}🔄 更新服务...${NC}"
        echo -e "${YELLOW}此操作将重新部署最新版本${NC}"
        read -p "$(echo -e ${YELLOW}确认更新？ [Y/n]: ${NC})" -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then
            # 保存服务器信息
            echo "REMOTE_HOST=$REMOTE_HOST" > "$PROJECT_DIR/.deploy-history"
            echo "REMOTE_USER=$REMOTE_USER" >> "$PROJECT_DIR/.deploy-history"
            echo "REMOTE_PORT=$REMOTE_PORT" >> "$PROJECT_DIR/.deploy-history"
            
            # 执行部署
            "$SCRIPT_DIR/deploy.sh" "$REMOTE_HOST" "$REMOTE_USER" "$REMOTE_PORT"
        else
            echo -e "${RED}取消更新${NC}"
        fi
        ;;
        
    config)
        echo -e "${BLUE}⚙️  查看配置...${NC}"
        run_remote "cd $REMOTE_DIR && cat .env | grep -v TOKEN | sed 's/=.*$/=***/' && echo 'PROXY_AUTH_TOKEN=***（已隐藏）'"
        ;;
        
    stats)
        echo -e "${BLUE}📈 服务统计...${NC}"
        run_remote "cd $REMOTE_DIR && docker stats --no-stream"
        echo ""
        echo -e "${BLUE}💾 磁盘使用...${NC}"
        run_remote "cd $REMOTE_DIR && du -sh ."
        echo ""
        echo -e "${BLUE}🐳 Docker 信息...${NC}"
        run_remote "docker ps --filter name=codelook-proxy --format 'table {{.Names}}\t{{.Status}}\t{{.Size}}'"
        ;;
        
    *)
        echo -e "${RED}错误: 未知操作 '$ACTION'${NC}"
        echo ""
        show_usage
        exit 1
        ;;
esac

# 保存服务器信息供下次使用
if [ ! -f "$PROJECT_DIR/.deploy-history" ]; then
    echo "REMOTE_HOST=$REMOTE_HOST" > "$PROJECT_DIR/.deploy-history"
    echo "REMOTE_USER=$REMOTE_USER" >> "$PROJECT_DIR/.deploy-history"
    echo "REMOTE_PORT=$REMOTE_PORT" >> "$PROJECT_DIR/.deploy-history"
fi