#!/bin/bash

# 设置工作目录
# 龙岗环境
WORK_DIR="/data_ai/ai-application/docker"
# 公司环境
# WORK_DIR="/data/docker/images/bqw-ai"

# 检查参数是否提供
if [ "$#" -lt 1 ]; then
    echo "Error: No arguments provided."
    echo "Supported commands:"
    echo "  bqw up                - Start services"
    echo "  bqw down              - Stop services"
    echo "  bqw restart           - Restart all services"
    echo "  bqw restart <name>    - Restart a specific container (e.g., bqw-ai-<name>)"
    echo "  bqw logs <name>       - logs -f a specific container (e.g., bqw-ai-<name>)"
    echo "  bqw clear cache       - Clear Redis cache and restart services"
    echo "  bqw bak system        - Backup system jar file"
    echo "  bqw oa data          - Get OA org data"
    exit 1
fi

# 切换到工作目录
cd "$WORK_DIR" || { echo "Failed to enter work directory: $WORK_DIR"; exit 1; }

# 根据参数执行不同的命令
case "$1" in
    up)
        echo "Starting services with docker compose..."
        sudo docker compose -p bqw up -d
        ;;
    down)
        echo "Stopping services with docker compose..."
        sudo docker compose -p bqw down
        ;;
    bak)
        if [ "$2" == "system" ]; then
            # 获取当前时间作为备份文件名的一部分
            BACKUP_TIME=$(date +"%Y-%m-%d-%H%M%S")
            SOURCE_FILE="${WORK_DIR}/system/target/bqw-ai.jar"
            BACKUP_FILE="${WORK_DIR}/system/target/bqw-ai.jar-${BACKUP_TIME}"
            
            # 检查源文件是否存在
            if [ ! -f "$SOURCE_FILE" ]; then
                echo "Error: Source file $SOURCE_FILE does not exist."
                exit 1
            fi
            
            # 执行备份
            echo "Backing up system jar file..."
            cp "$SOURCE_FILE" "$BACKUP_FILE"
            
            if [ $? -eq 0 ]; then
                echo "Backup completed successfully: $BACKUP_FILE"
            else
                echo "Error: Backup failed."
                exit 1
            fi
        else
            echo "Invalid argument. Usage: bqw bak system"
            exit 1
        fi
        ;;
    restart)
        if [ "$2" == "" ]; then
            # 如果没有提供名称，则重启整个服务
            echo "Restarting bqw services..."
            echo "Stopping services..."
            sudo docker compose -p bqw down
            echo "Starting services..."
            sudo docker compose -p bqw up -d
        else
            # 如果提供了名称，则重启指定的容器
            CONTAINER_NAME="bqw-ai-$2"
            echo "Restarting container: $CONTAINER_NAME"
            if sudo docker ps -a --format '{{.Names}}' | grep -q "^$CONTAINER_NAME\$"; then
                sudo docker restart "$CONTAINER_NAME"
                echo "Container $CONTAINER_NAME restarted successfully."
            else
                echo "Error: Container $CONTAINER_NAME not found."
                exit 1
            fi
        fi
        ;;
    logs)
            # 如果提供了名称，则重启指定的容器
            CONTAINER_NAME="bqw-ai-$2"
            echo "logs container: $CONTAINER_NAME"
            if sudo docker ps -a --format '{{.Names}}' | grep -q "^$CONTAINER_NAME\$"; then
                sudo docker logs --tail 500  -f "$CONTAINER_NAME"
                echo "Container $CONTAINER_NAME logs successfully."
            else
                echo "Error: Container $CONTAINER_NAME not found."
                exit 1
            fi
            ;;
    clear)
        if [ "$2" == "cache" ]; then
            echo "Stopping bqw services before clearing cache..."
            sudo docker compose -p bqw down

            # 删除 Redis 缓存文件
            REDIS_CACHE_DIR="${WORK_DIR}/redis/data"
            if [ -d "$REDIS_CACHE_DIR" ]; then
                echo "Deleting Redis cache files in $REDIS_CACHE_DIR..."
                sudo rm -rf "$REDIS_CACHE_DIR"/*
                echo "Cache cleared successfully."
            else
                echo "Redis cache directory not found: $REDIS_CACHE_DIR"
            fi

            echo "Restarting bqw services..."
            sudo docker compose -p bqw up -d
        else
            echo "Invalid argument. Usage: bqw clear cache"
            echo "Supported commands:"
            echo "  bqw up                - Start services"
            echo "  bqw down              - Stop services"
            echo "  bqw restart           - Restart all services"
            echo "  bqw restart <name>    - Restart a specific container (e.g., bqw-ai-<name>)"
            echo "  bqw logs <name>       - logs a specific container (e.g., bqw-ai-<name>)"
            echo "  bqw clear cache       - Clear Redis cache and restart services"
            echo "  bqw bak system        - Backup system jar file"
            echo "  bqw oa token          - Get OA token"
            echo "  bqw oa data <token> <output_path> - Get OA data and save to specified path"
            exit 1
        fi
        ;;
    oa)
        if [ "$2" == "data" ]; then
            echo "Getting OA token..."
            # 获取token并保存到临时变量
            TOKEN_RESPONSE=$(curl -X POST https://xtbg.lg.gov.cn/LGOA/restservices/LgoaAPINew/lgoaToken/query \
            -H "Content-Type: application/json" \
            -d '{
                "authaccount": "LGOA_ZNTPTDJ",
                "authid": "20250328_073714dcf19814d6dd9e"
            }')
            
            # 使用grep和cut提取token值
            TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
            
            if [ -z "$TOKEN" ]; then
                echo "Error: Failed to get token"
                exit 1
            fi
            
            echo "Token obtained successfully: $TOKEN"
            
            # 处理相对路径
            if [[ "$3" == "./" ]]; then
                OUTPUT_PATH="${WORK_DIR}/output.json"
            else
                # 构建完整的输出文件路径
                OUTPUT_PATH="${WORK_DIR}/${3}/output.json"
            fi
            
            echo "Getting OA data with token: $TOKEN"
            echo "Saving output to: $OUTPUT_PATH"
            echo "Please Waiting..."
            
            curl -X POST https://xtbg.lg.gov.cn/LGOA/restservices/LgoaAPINew/getOrgPosUserInfo/query \
            -H "Content-Type: application/json" \
            -d "{\"token\":\"$TOKEN\"}" \
            -o "$OUTPUT_PATH"
            
            if [ $? -eq 0 ]; then
                echo "Data successfully saved to $OUTPUT_PATH"
            else
                echo "Error: Failed to get data"
                exit 1
            fi
        else
            echo "Invalid argument. Usage: bqw oa data"
            exit 1
        fi
        ;;
    *)
        echo "Error: Invalid command '$1'."
        echo "Supported commands:"
        echo "  bqw up                - Start services"
        echo "  bqw down              - Stop services"
        echo "  bqw restart           - Restart all services"
        echo "  bqw restart <name>    - Restart a specific container (e.g., bqw-ai-<name>)"
        echo "  bqw logs <name>       - logs a specific container (e.g., bqw-ai-<name>)"
        echo "  bqw clear cache       - Clear Redis cache and restart services"
        echo "  bqw bak system        - Backup system jar file"
        echo "  bqw oa data          - Get OA org data"
        exit 1
        ;;
esac
