
pprofdir=$1
if [[ "${pprofdir}" == "" ]]; then
    pprofdir="/tmp/pprof"
fi

pprofhttp() {
    port=$1
    pft=$2

    # stop last process
    lpid=`ps -ef | grep -v grep | grep "tail -F ${pprofdir}/.${port}.pprof.running.flag" | awk '{print $2 " " $3}'`
    while [[ "${lpid}" != "" ]]; do
        kill ${lpid} >/dev/null 2>&1
        lpid=`ps -ef | grep -v grep | grep "tail -F ${pprofdir}/.${port}.pprof.running.flag" | awk '{print $2 " " $3}'`
    done
    # pprof.sh running flag
    tail -F ${pprofdir}/.${port}.pprof.running.flag >/dev/null 2>&1 &

    changeflag=
    while true; do
        cf=`ls -l ${pprofdir}/${pft}.prof 2>&1`
        if [[ "${cf}" != "${changeflag}" ]]; then
            lpid=`ps -ef | grep -v grep | grep "go tool pprof -http=0.0.0.0:${port}" | awk '{print $2}'`
            while [[ "${lpid}" != "" ]]; do
                kill ${lpid} >/dev/null 2>&1
                lpid=`ps -ef | grep -v grep | grep "go tool pprof -http=0.0.0.0:${port}" | awk '{print $2}'`
            done
            date >>"${pprofdir}/.pprof.log" 2>&1
            go tool pprof -http=0.0.0.0:${port} ${pprofdir}/${pft}.prof >>"${pprofdir}/.pprof.log" 2>&1 &
            if [[ "${changeflag}" = "" ]]; then
                echo "${cf}"
            fi
            changeflag=${cf}
        else
            sleep 1
        fi
    done
}

openpprof() {
    port=$1
    pft=$2
    if [[ -e "${pprofdir}/${pft}.prof" ]]; then
        pprofhttp ${port} ${pft} &
    else
        echo "${pprofdir}/${pft}.prof" not exist
    fi
}

echo > "${pprofdir}/.pprof.log"
openpprof 8181 "cpu"
openpprof 8282 "mem"
sleep 1
cat "${pprofdir}/.pprof.log"
