#!/bin/bash
# Argument parser for training.
# 导入函数方法：source parse_torchrun_args.sh

parse_torchrun_args()
{
  # default values
  master_addr="localhost"
  master_port="19981"
  node_num="1"
  node_rank="0"
  nproc_per_node="8"

  # manual parsing
  while [[ $# -gt 0 ]]; do
    case $1 in
      --master_addr)
        if [[ -z "$2" ]] || [[ "$2" == -* ]]; then
          echo "Error: '$1' requires a non-empty argument." >&2
          exit 1
        fi
        master_addr="$2"
        shift 2
        ;;
      --master_port)
        if [[ -z "$2" ]] || [[ "$2" == -* ]]; then
          echo "Error: '$1' requires a non-empty argument." >&2
          exit 1
        fi
        master_port="$2"
        shift 2
        ;;
      --node_num)
        if [[ -z "$2" ]] || [[ "$2" == -* ]]; then
          echo "Error: '$1' requires a non-empty argument." >&2
          exit 1
        fi
        node_num="$2"
        shift 2
        ;;
      --node_rank)
        if [[ -z "$2" ]] || [[ "$2" == -* ]]; then
          echo "Error: '$1' requires a non-empty argument." >&2
          exit 1
        fi
        node_rank="$2"
        shift 2
        ;;
      --nproc_per_node)
        if [[ -z "$2" ]] || [[ "$2" == -* ]]; then
          echo "Error: '$1' requires a non-empty argument." >&2
          exit 1
        fi
        nproc_per_node="$2"
        shift 2
        ;;
      --*)
        # 未知长选项：跳过它和它的值（如果值存在且不是选项）
        if [[ -n "$2" ]] && [[ "$2" != -* ]]; then
          shift 2
        else
          shift 1
        fi
        ;;
      *)
        # 其他未知参数（如位置参数），跳过一个
        shift 1
        ;;
    esac
  done
}
