#!/bin/bash
#                       _        
#                      | |       
#_ __   __ _ _ __ _   _| |_ ___  
#| '_ \ / _` | '__| | | | __/ _ \ 
#| | | | (_| | |  | |_| | || (_) |
#|_| |_|\__,_|_|   \__,_|\__\___/ .TIGERB.cn
#
#An object-oriented multi process manager for PHP
#
#Version: 0.5.0
#

# Find the master process pid
os=$(uname)

if [[ "$os" == 'Linux' ]]
then
    ppid=$(pstree -aps | grep 'naruto' | grep 'php' | awk -F ',' '{if(NR==1){print $2}}' | awk '{print $1}')
elif [[ "$os" == 'Darwin' ]]
then
    ppid=$(pstree | grep 'naruto --worker-num' | grep '\-+' | awk '{print $4}')
else
    echo -e "just support macos and linux os system"
    exit
fi

case $1 in
"start")
    if [[ "$ppid" != '' ]]
    then
        echo -e "naruto is already running..."
        exit
    fi
    phpversion=$(php -v | grep 'PHP 7')
    if [[ "$phpversion" == '' ]]
    then
        echo -e "Please use php 7+"
        exit
    fi
    php "$NARUTO_PATH"/naruto --worker-num="$2" --passwd="$3" --os="$os"
    ;;
"reload")
    if [[ "$ppid" == '' ]]
    then
        echo -e "naruto is not running..."
        exit
    fi
    kill -s SIGUSR1 "$ppid"
    if [[ $? != 0 ]]
    then
        echo -e "reload signal be sent fail..."
        exit
    fi 
    echo -e "reload signal be sent success..."
    ;;
"quit")
    if [[ "$ppid" == '' ]]
    then
        echo -e "naruto is not running..."
        exit
    fi
    kill -s SIGUSR2 "$ppid"
    if [[ $? != 0 ]]
    then
        echo -e "quit signal be sent fail..."
        exit
    fi 
    echo -e "quit signal be sent success..."
    ;;
"stop")
    if [[ "$ppid" == '' ]]
    then
        echo -e "naruto is not running..."
        exit
    fi
    kill -s SIGTERM "$ppid"
    if [[ $? != 0 ]]
    then
        echo -e "stop signal be sent fail..."
        exit
    fi 
    echo -e "stop signal be sent success..."
    ;;
*)

cat <<EOF
    Usage:
        naruto start/reload/quit/stop <worker-num> <passwd>

    Example:
        naruto start 10 123456
        naruto reload
        naruto stop
        naruto quit
        ...    
EOF
echo -e "\n \033[36m An object-oriented multi process manager for PHP\033[0m \n"
echo -e "  \033[36mVersion: 0.5.0 \033[0m \n"
    exit
esac
