#!/bin/bash

# 添加必要的工具路径
export PATH=$PATH:/usr/local/bin:$(go env GOPATH)/bin

# 进入 proto 文件目录
cd bin/client_msg || { echo "Error: Failed to enter bin/client_msg"; exit 1; }

# 目标目录(确保存在)
TARGET_DIR="../../src/server/msg"
mkdir -p "$TARGET_DIR" || { echo "Error: Failed to create $TARGET_DIR"; exit 1; }

# 遍历所有 .proto 文件并编译
for proto_file in *.proto; do
    if [ -f "$proto_file" ]; then
        echo "Compiling $proto_file..."

        # 生成 Go 代码(自动处理 go_package 路径)
        protoc --proto_path=. --go_out=paths=source_relative:. "$proto_file" || {
            echo "Error: protoc failed for $proto_file"
            exit 1
        }

        # 提取 go_package 名称(从 .proto 文件中解析)
        go_package=$(grep "^option go_package" "$proto_file" | awk -F'"' '{print $2}')
        if [ -z "$go_package" ]; then
            echo "Warning: Missing 'option go_package' in $proto_file, using default"
            go_package="msg"
        fi

        # 移动生成的 .pb.go 文件
        gen_file="${proto_file%.proto}.pb.go"
        if [ -f "$gen_file" ]; then
            mv "$gen_file" "$TARGET_DIR/" || {
                echo "Error: Failed to move $gen_file"
                exit 1
            }
            echo "Moved $gen_file to $TARGET_DIR/"
        else
            echo "Error: Generated file $gen_file not found"
            exit 1
        fi
    fi
done

echo "All proto files compiled and moved successfully!"