#!/bin/bash

MEASUREMENT_DIR=
SAMPLING_MODE=1
SAMPLING_RATIO=0
SAMPLING_IFRANDOM=0
ENABLE_BACKTRACE=0
BACKTRACE_MAX_DEPTH=20
POSITIONAL_ARGS=()

USAGE_STR="mpi_adaptive_tool sclrun [ -h | --help ] [ --backtrace ] [ -backtrace_max_depth <depth> ] [ -samp_mode {1,2,3} ] [ -samp_ratio <ratio> ] [ -samp_random <seed> ] [ -l | --log-level {0,1,2,3} ] [ -o | --output <collect_result_directory> ] [ <exe> <args> ]"

print_name() {
    echo -e ""
    echo -e "\033[1mNAME\033[0m"
    echo -e "    mpi_adaptive_tool sclrun"
    echo -e "    Starts the target program and collects the performance data of the target program."
    echo -e ""
}

print_usage() {
    echo -e "\033[1mUSAGE\033[0m"
    echo -e "    ${USAGE_STR}"
    echo -e ""
}

print_description() {
    echo -e "\033[1mDESCRIPTION\033[0m"
    echo -e "    Uses the sclrun tool to start the target program. sclrun instruments the MPI function to collect the call stack information and PMU event data of the target program for subsequent analysis."
    echo -e ""
}

print_option() {
    echo -e "\033[1mOPTIONS\033[0m"

    echo -e "    -h, --help"
    echo -e "    Get help information and exit."
    echo -e ""

    echo -e "    -o <collect_result_directory>, --output <collect_result_directory>"
    echo -e "    Result directory generated after collecting the performance data of the target program."
    echo -e ""

    echo -e "    -l {0,1,2,3}, --log-level {0,1,2,3}"
    echo -e "    Specify the print log level, 0(debug) | 1(info) | 2(warning) | 3(error). Default is 1(info). Log path refers to the log configuration file config/cfg.ini."
    echo -e ""

    echo -e "    --backtrace"
    echo -e "    Collects the call stack information of the target program. This may prolong the application running time."
    echo -e ""

    echo -e "    -backtrace_max_depth <depth>"
    echo -e "    Maximum depth of call stack information to be collected. The default value is 20."
    echo -e ""

    echo -e "    -samp_mode {1,2,3}"
    echo -e "    Sampling mode for collecting the performance data of the target program. The default value is 1."
    echo -e "        1: Full collection. The performance data of all ranks is collected."
    echo -e "        2: Fixed step sampling. Data is collected based on the sampling ratio specified by the samp_ratio parameter."
    echo -e "        3: Adaptive sampling. Data is collected based on the sampling ratio determined by the number of ranks. The samp_ratio parameter becomes invalid and the sampling ratio is determined by the number of ranks."
    echo -e ""

    echo -e "    -samp_ratio <ratio>"
    echo -e "    Sampling ratio. The value ranges from 0 to 100 and defaults to 0. This parameter is invalid when samp_mode is set to 1 or 3."
    echo -e ""

    echo -e "    -samp_random <seed>"
    echo -e "    Random sampling mode, and set the random number seed."
    echo -e ""

    echo -e "    <exe> <args>"
    echo -e "    MPI application whose data is to be collected and the associated parameters."
    echo -e ""
}

print_help() {
    if [[ "${OMPI_COMM_WORLD_RANK}" -ne 0 ]]; then
        return
    fi
    print_name
    print_usage
    print_description
    print_option
}

print_error_usage() {
    error_info="$1"
    echo -e "usage: ${USAGE_STR}\n"
    echo -e "error: ${error_info}\n\n"
}

arg_parser() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -o|--output)
                MEASUREMENT_DIR=$(realpath "$2")
                shift # past argument
                shift # past value
                ;;
            -h|--help)
                print_help
                exit 0
                ;;
            -l|--log-level)
                LOG_LEVEL="$2"
                export SCL_LOG_LEVEL=${LOG_LEVEL}
                shift
                shift
                ;;
            --backtrace)
                ENABLE_BACKTRACE=1
                shift # past argument
                ;;
            -backtrace_max_depth)
                BACKTRACE_MAX_DEPTH="$2"
                shift
                shift
                ;;
            -samp_mode)
                SAMPLING_MODE="$2"    # op=1: all sampling// op=2: specific sampling ratio// op=3: random sampling ratio
                shift
                shift
                ;;
            -samp_ratio)
                SAMPLING_RATIO="$2"    # sampling ratio
                shift
                shift
                ;;
            -samp_random)
                SAMPLING_IFRANDOM="$2"    # if random sampling, the value is the seed value generating original sampling list
                shift
                shift
                ;;
            -*|--*)
                print_error_usage "unknown option $1"
                return 1
                ;;
            *)
                CMD=$*
                break
                ;;
        esac
    done
}

check_cmd() {
    cmd_parser_list=(${CMD})
    cmd_parser_num=${#cmd_parser_list[@]}
    if [[ -z "${CMD}" ]] || [[ ${cmd_parser_num} -eq 0 ]] || [[ ! -f "${cmd_parser_list[0]}" ]]; then
        print_error_usage "The MPI application is not accessible."
        return 1
    fi
    return 0
}

check_samp_mode() {
    samp_mode=(1 2 3)
    if [[ "${samp_mode[@]}" =~ "${SAMPLING_MODE}" ]]; then
        return 0
    fi

    print_error_usage "argument -samp_mode invalid choice:"${SAMPLING_MODE}" (choose from 1,2,3)."
    return 1
}

check_samp_ratio() {
    if [[ "${SAMPLING_RATIO}" =~ ^[0-9]+$ ]] && [[ "${SAMPLING_RATIO}" -ge "0" ]] && [[ "${SAMPLING_RATIO}" -le "100" ]]; then
        return 0
    fi
    print_error_usage "argument -samp_ratio invalid value:"${SAMPLING_RATIO}" (integer from 0 to 100)."
    return 1
}

check_backtrace_depth() {
    if [[ "${BACKTRACE_MAX_DEPTH}" =~ ^[0-9]+$ ]] && [[ "${BACKTRACE_MAX_DEPTH}" -gt 0 ]]; then
        return 0
    fi
    print_error_usage "argument -backtrace_max_depth invalid value:${BACKTRACE_MAX_DEPTH} (must be a positive integer)."
    return 1
}

check_output_path() {
  if [[ -z "${MEASUREMENT_DIR}" ]]; then
      print_error_usage "-o or --output must be specified!"
      return 1
  fi

  if [[ ! -d "${MEASUREMENT_DIR}" ]]; then
    mkdir -p "${MEASUREMENT_DIR}" || { print_error_usage "failed to create ${MEASUREMENT_DIR}"; return 1; }
    chmod 700 "${MEASUREMENT_DIR}"
    return 0
  fi

  if [[ ! -x "${MEASUREMENT_DIR}" ]]; then
    print_error_usage "The output path ${MEASUREMENT_DIR} does not have permissions."
    return 1
  fi

  meta_files=$(ls "${MEASUREMENT_DIR}"/data.*.meta 2> /dev/null | wc -l)
  tr_files=$(ls "${MEASUREMENT_DIR}"/data.*.tr 2> /dev/null | wc -l)
  bin_files=$(ls "${MEASUREMENT_DIR}"/backtrace_db.*.bin 2> /dev/null | wc -l)
  if [[ "${meta_files}" != "0" ]] || [[ "${tr_files}" != "0" ]] || [[ "${bin_files}" != "0" ]]; then
    echo -e "warning: Delete historical collection files in the output directory ${MEASUREMENT_DIR}"
  fi
  rm -f "${MEASUREMENT_DIR}"/data.*.meta || { print_error_usage "failed to delete the history file data.*.meta"; return 1; }
  rm -f "${MEASUREMENT_DIR}"/data.*.tr || { print_error_usage "failed to delete the history file data.*.tr"; return 1; }
  rm -f "${MEASUREMENT_DIR}"/backtrace_db.*.bin || { print_error_usage "failed to delete the history file backtrace_db.*.bin"; return 1; }
  return 0
}

check_random_seed() {
    if [[ "${SAMPLING_IFRANDOM}" =~ ^[0-9]+$ ]]; then
        return 0
    fi
    print_error_usage "argument -samp_random invalid value:${SAMPLING_IFRANDOM}."
    return 1
}

check_log_level() {
    log_level=(0 1 2 3)
    if [[ "${log_level[@]}" =~ "${LOG_LEVEL}" ]]; then
        return 0
    fi

    print_error_usage "argument -l/--log-level invalid choice:"${LOG_LEVEL}" (choose from 0,1,2,3)."
    return 1
}

check_args() {
    check_samp_mode || return 1

    check_samp_ratio || return 1

    check_backtrace_depth || return 1

    check_random_seed || return 1

    check_log_level || return 1

    check_cmd || return 1

    check_output_path || return 1
}


arg_parser "$@"
if [[ $? -ne 0 ]]; then
    exit 1
fi

check_args
if [[ $? -ne 0 ]]; then
    exit 1
fi


set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters

echo "================================"
echo "Bootstrapping SCL Toolkit..."

ROOT=$(dirname "$0")
WRAPPER=$ROOT/../lib/libmpi_wrapper.so
export LD_PRELOAD=$WRAPPER
export SCL_MEASUREMENT_DIR=$MEASUREMENT_DIR
export SCL_SAMPLING_MODE=$SAMPLING_MODE
export SCL_SAMPLING_RATIO=$SAMPLING_RATIO
export SCL_SAMPLING_IFRANDOM=$SAMPLING_IFRANDOM
export SCL_ENABLE_BACKTRACE=${ENABLE_BACKTRACE}
export SCL_BACKTRACE_MAX_DEPTH=${BACKTRACE_MAX_DEPTH}

echo "Measurement Directory: $MEASUREMENT_DIR"
if [[ "${SCL_ENABLE_BACKTRACE}" -eq 1 ]]; then
  echo "Backtrace enabled"
fi
if [[ "${SCL_ENABLE_PMU}" -eq 1 ]]; then
  echo "PMU collecting enabled"
fi
echo "Executing command: $CMD"
echo "================================"
$CMD
