#! /bin/sh
run_path='/home/server/switch/install/freeswitch'
install_path=/home/server/switch
fs_path="$install_path/"freeswitch

shell_main () {
    mkdir -p $run_path/log
    linux=$(check_linux);
    notice '====== freeswitch gateway generate, linux system version: '$linux' ======'
    # 判定当前系统
    if [ "$linux" == "Unknown" ]; then
        error 'Unknown linux exit.'
        exit
    fi

    P=`pwd`
    if [ $P != "$run_path" ];then
        error "请在["$run_path"]目录下执行脚本"
        exit
    fi
    
    cfg_path=$run_path/init/template/gateway.cfg

    if [ ! -f $cfg_path ];then
        error $cfg_path", 网关模板文件不存在"
        exit
    fi

    # 逐行读取文件内容
    while IFS= read -r line; do
        # 按照分号隔开
        echo "$line"
    done < "$cfg_path"
    notice '====== freeswitch gateway generate end ======'
}

check_linux () {
    if [ -f /etc/os-release ]; then
        # Arch Linux, Manjaro, etc.
        echo $(grep '^ID=' /etc/os-release | cut -d= -f2-|cut -d '"' -f2)
    else
        echo "Unknown"
    fi
}

verbose () {
	echo "${green}$@${normal}"
    save_log "[INFO] "$@
}
error () {
	echo "${red}$@${normal}"
    save_log "[ERR] "$@
}
warning () {
	echo "${yellow}$@${normal}"
    save_log "[WARNING] "$@
}

notice () {
	echo "${blue}$@${normal}"
    save_log "[NOTICE] "$@
}

execute_shell() {
    if [ $# -gt 0 ]; then
        verbose "执行命令 ["$@"]"
        echo $@|sh
    fi
}

# check for color support
if test -t 1; then
    # see if it supports colors...
    ncolors=$(tput colors)

    if test -n "$ncolors" && test $ncolors -ge 8; then
        normal="$(tput sgr0)"
        red="$(tput setaf 1)"
        green="$(tput setaf 2)"
        yellow="$(tput setaf 3)"
        blue="$(tput setaf 4)"
    fi
fi

index=1
index_log() {
    notice $index". "$1
    index=`expr $index + 1`
}

save_log(){
    str_tmp="`date +%Y-%m-%d_%H:%M:%S` "
    while [ $# -ge 1 ];do
        str_tmp="$str_tmp $1"
        shift
    done
    echo $str_tmp >>$run_path/log/gateway_`date +%Y-%m-%d`.log
}

shell_main