#!/bin/bash
CURRENT_DIR=$(cd $(dirname "$0"); pwd)
# PID白名单文件存放路径
WHITE_LIST_FILE="$CURRENT_DIR/pid_list"
DEVKIT_CLI_PATH="$INSTALL_PATH/devkit"
params="$@"
miss_event_flag=0
etc_config="/etc/centos-release"

echo "${HOME}" > "$CURRENT_DIR/debug_path"
# 将父进程PID加入白名单，当取消或停止时做校验
echo "$PPID" >> ${WHITE_LIST_FILE}
chmod 600 ${WHITE_LIST_FILE}

# 白名单跳过参数校验
WHITE_LIST=("-*" "sleep" "stat")
if [[ "$1" == "script" ]]  && [[ ${params} =~ " -s " || ${params} =~ " --script " ]]; then
    echo "Invalid privilege escalation parameter -s/--script."
    exit 1
fi
# 遍历命令行的每一个参数
for args in "$@"
do
    # 如果是第一个参数，则跳过
    if [[ "${args}" == "$1" ]]
    then
        continue
    fi
    # 过滤-h --help 参数
    if [[ "${args}" == "--help" ]] || [[ "${args}" == "-h" ]] || [[ "${args}" == "--" ]];then
        exit 1
    fi
    # 标志如果在白名单中的参数，则跳过检查，1为跳过
    # 检查参数以-或--开头，及命令行关键字，则跳过
    skip_flag=0
    for cmd_param in ${WHITE_LIST[@]}
    do
        if [[ ${args} == ${cmd_param} ]];then
            skip_flag=1
            break
        fi
    done
    if [[ ${skip_flag} -eq 1 ]];then
        # 跳过这个参数
        continue
    fi

    # 获取可执行文件的路径
    path=$(which ${args} 2>/dev/null)
    if [[ $? -ne 0 ]]; then
        path=${args}
    fi

    if [[ -f "${path}" && -x "${path}" ]];then
        if [[ "${path}" != "$CURRENT_DIR/launch_app.sh" ]] &&
        [[ "${path}" != "$CURRENT_DIR/launch_app_uarch.sh" ]]; then
            echo "The app mode must be called by the launch_app.sh script"
            exit 1
        else
            break
        fi
    fi
done
 
for args in "${params}"
do
    if [[ "${args}" =~ arm_spe_0.* ]]; then
        miss_event_flag=1
    fi
done
perf_path=$(which perf)
if [[ -f "${etc_config}" ]] && [[ "${miss_event_flag}" == 1 ]]; then
    grep "CentOS Linux release 7.6.1810" "${etc_config}" >/dev/null 2>&1
    if [[ "$?" -eq 0 ]]; then
        perf_path="$DEVKIT_CLI_PATH/spe/4.14.0-115.el7a.0.1/perf"
    fi
fi
 
if [[ "${params}" =~ "list sched" ]];then
    ${perf_path} list sched|awk '{print $0}' ${param/list sched/}
    exit
fi
if [[ "${params}" =~ "list" ]];then
    ${perf_path} list |awk '{print $0}' ${param/list/}
    exit
fi

if [[ "${params}" == "--help" ]] || [[ "${params}" == "-h" ]];then
    exit 1
fi

${perf_path} ${params}