#!/bin/bash
#
# OneAPM PHP agent installation script.
#

: ${oneapmversion:="0.0.1"}

show_oa_php_ini_info() {
cat << EOF

;~ Setting: oneapm.appname
;~ Type   : string
;~ Default: "PHP Application"
;~ Info   : Set Application Name
;~
;oneapm.appname="PHP Application"

;~
;~ Setting: oneapm.record_sql
;~ Type   : "off", "raw" or "obfuscated"
;~ Default: "obfuscated"
;~ Info   : Sets how SQL statements are recorded (if at all). If this is set to
;~          "raw" then no attempt is made at obfuscating SQL statements.
;~          USING "raw" IS HIGHLY DISCOURAGED IN PRODUCTION ENVIRONMENTS!
;~          Setting this to "raw" has considerable security implications
;~          as it can expose sensitive and private customer data.
;~
;oneapm.record_sql="obfuscated"

;~
;~ Setting: oneapm.errorlevel
;~ Type   : string
;~ Default: "ERROR"
;~ Info   : Sets the PHP error info grab level.
;~          Must be one of the following values:
;~            NOTICE, WARNING, ERROR, CLOSE
;~
;oneapm.errorlevel="ERROR"

;~
;~ Setting: oneapm.loglevel
;~ Type   : string
;~ Default: "WARN"
;~ Info   : Sets the level of detail to include in the log file. You should
;~          rarely need to change this from the default, and usually only under
;~          the guidance of technical support.
;~          Must be one of the following values:
;~            ERROR, WARN, INFO, TRACE, DEBUG
;~
;oneapm.loglevel="WARN"

;~
;~ Setting: oneapm.auto_transaction_get
;~ Type   : string
;~ Default: ""
;~ Info   : set the get parameter as transaction name.
;~          eg : url http://url/index.php?s=/home/index/index.html, if we set it to "s",
;~          the transaction name will be rename 'WebTransaction/Uri/home/index/index.html',
;~          the original WebTransaction Name was : 'WebTransaction/Uri/index.php'.
;~
;oneapm.auto_transaction_get=""

;~
;~ Setting: oneapm.auto_transaction_post
;~ Type   : string
;~ Default: ""
;~ Info   : set the post parameter as transaction name.
;~
;oneapm.auto_transaction_post=""

;~
;~ Setting: oneapm.auto_transaction_naming
;~ Type   : bool
;~ Default: true
;~ Info   : Whether to automatically detect the PHP frameworks and supports.
;~          true, automatically detect; false, not detect;
;~
;oneapm.auto_transaction_naming=true

;~
;~ Setting: oneapm.usesitename
;~ Type   : bool
;~ Default: false
;~ Info   : use site name as identifier name. default identifier PHP:PHP Application:80(host name)
;~          set true, identifier is LANGUAGE:$_SERVER['HTTP_HOST']:PORT(host name) 
;~          eg PHP:www.xxxx.com:80(host name) or PHP:localhost:80(host name) or PHP:127.0.0.1:80(host name)
;~
;oneapm.usesitename=false

;~
;~ Setting: oneapm.transaction_threshold
;~ Type   : double
;~ Default: 0.5s
;~ Info   : Sets the threshold above which the OneApm agent will record a
;~          stack trace for a transaction trace. 
;~
;oneapm.transaction_threshold=0.5

;~
;~ Setting: oneapm.explain_threshold
;~ Type   : double
;~ Default: 0.5s
;~ Info   : Sets the threshold above which the OneApm agent will record a
;~          slow sql.
;~
;oneapm.explain_threshold=0.5

;~
;~ Setting: oneapm.http_capture_params
;~ Type   : bool
;~ Default: true
;~ Info   : capture http params (get or post) switch.
;~
;oneapm.http_capture_params=true

;~
;~ Setting: oneapm.is_pathinfo
;~ Type   : bool
;~ Default: false
;~ Info   : Capturing the $_SERVER['PATH_INFO'] switch.
;~          eg: Your url is  http://www.xxx.com/index.php/key1/key2/key3
;~              default false, OneAPM only capture index.php
;~				set true, OneAPM capture index.php/key1/key2/key3
;~
;oneapm.is_pathinfo=false

;~
;~ Setting: oneapm.num_pathinfo
;~ Type   : int
;~ Default: 3
;~ Info   : if your url is  http://www.xxx.com/index.php/key1/key2/key3
;~          when oneapm.is_pathinfo=true, 0 means no limit.
;~          set 1 means OneAPM capture index.php/key1
;~          set 2 means OneAPM capture index.php/key1/key2 and so on.
;~
;oneapm.num_pathinfo=3

;~
;~ Setting: oneapm.browser_monitoring
;~ Type   : bool
;~ Default: false
;~ Info   : browser monitoring switch.
;~
;oneapm.browser_monitoring=false

;~
;~ Setting: oneapm.browser_monitoring.is_js_text
;~ Type   : bool
;~ Default: false
;~ Info   : browser monitoring js type (text or url) switch.
;~
;oneapm.browser_monitoring.is_js_text=false

;~
;~ Setting: oneapm.browser_monitoring.request.ip
;~ Type   : string
;~ Default: "all"
;~ Info   : enable brower monitoring when request ip is captured, separated by ','.
;~
;oneapm.browser_monitoring.request.ip="all"

;~
;~ Setting: oneapm.browser_monitoring.request.url
;~ Type   : string
;~ Default: "all"
;~ Info   : enable brower monitoring when request url is captured, separated by ','.
;~
;oneapm.browser_monitoring.request.url="all"

;~
;~ Setting: oneapm.browser_monitoring.request.param
;~ Type   : string
;~ Default: "all"
;~ Info   : enable brower monitoring when request param is captured, separated by ','.
;~
;oneapm.browser_monitoring.request.param="all"

;~
;~ Setting: oneapm.cross_application_tracer.enabled
;~ Type   : bool
;~ Default: true
;~ Info   : cross application call is mean multi-node Call each other monitor
;~
;oneapm.cross_application_tracer.enabled=true

;~
;~ Setting: oneapm.cross_application_tracer.internal_host
;~ Type   : string
;~ Default: ""
;~ Info   : need oneapm.cross_application_tracer.enabled=true, multiple host directly separated by commas
;~
;oneapm.cross_application_tracer.internal_host=www.aaa.com,www.bbb.com

;~
;~ Setting: oneapm.trace_node_limit
;~ Type   : int
;~ Default: 500
;~ Info   : stack trace node limit number.
;~
;oneapm.trace_node_limit=500

;~
;~ Setting: oneapm.enable_rate
;~ Type   : int
;~ Default: 100
;~ Info   : Value range 0 ~ 100 , all the data capture ratio
;~
;oneapm.enable_rate=100

;~
;~ Setting: oneapm.ignore_port
;~ Type   : string
;~ Default: ""
;~ Info   : in list port, not upload data
;~          eg: oneapm.ignore_port="80,8080,8088"
;~
;oneapm.ignore_port=""

;~
;~ Setting: oneapm.catch_exception
;~ Type   : bool
;~ Default: false
;~ Info   : if ture, capture set_exception_handler function data
;~
;oneapm.catch_exception=true

EOF
}

print_oa_dfmissing_info() {
	cat <<EOF
maybe the download install package is error, please join qq group:321095806 or contact ${bold}http://support.oneapm.com${rmso} and report the issue.
EOF
}

print_oa_fatal_error_info() {
	cat >&2 <<EOF
FATAL: OneAPM agent installation failed. Please  join qq group:321095806 or contact ${bold}http://support.oneapm.com${rmso} and report the above error. 
EOF
}

print_oa_main_menu_info() {
	cat <<EOF
    Please select from one of the following options:

    1)  Install ${bold}OneAPM${rmso} Agent and Daemon
    2)  Uninstall ${bold}OneAPM${rmso} Agent and Daemon
    
    0)  Exit

EOF
}

print_select_info() {
	echo "Please select the directory or directories for which you wish to install ${bold}OneAPM${rmso}."
	echo "You can select only a single directory."
}
print_install_success_info() {
	cat <<EOF
	
${bold}OneAPM${rmso} is now installed on your system. Congratulations!
${bold}Restart your web server or servers${rmso}.
Any question join qq group:321095806 or contact ${bold}http://support.oneapm.com${rmso}
EOF
}

print_oa_uninstall_success_info() {
		cat <<EOF

Removal of ${bold}OneAPM${rmso} complete. 
Any question join qq group:321095806 or contact ${bold}http://support.oneapm.com${rmso}
EOF
}

echo_no_found_php_ini() {
        echo -e "\n ${bold} Sorry, not found php.ini file, please enter the php.ini file location. eg: /usr/local/php.ini ${rmso}\n"
        echo -n "${bold} Please input the absolute path of php.ini: ${rmso}"
}

show_script_usage() {
cat << EOF
		"oneapm-install <action> [option]"
		"Valid action:
				install 	Install  OneAPM Agent
				uninstall	Uninstall OneAPM Agent
		  Valid options:
				--help		Show this message
				Install valid option:
					--license='license key'
					--php-path='path-to-php-binary'
					--php-ini-file='path-to-php.ini'
					--appname='Example_app'
					--version="version"
					--thread_safe="no or yes"
					--extension_dir="extension_directory"
				when you don't have php you must have --php-ini-file,--version,--thread_safe,extension_dir options
				Uninstall valid option:
		"
		"exam:
		oneapm-install install --php-path=/usr/local/php5/bin --php-ini-file=/usr/local/php5/etc/php.ini --license=yyyy
		oneapm-install uninstall
		"
EOF
}

# global stuff

g_unit_test=n
action=
g_ostype=
g_one_apm_install_base_dir=
g_arch=
g_dmissing=
g_fmissing=
g_guess_php_list=
g_daemon_pid=
g_install_license=
g_php_params_path=
g_php_ini_params_file=
g_appname=
g_oa_daemon_bin=
g_os_init_file=
g_changed_ini_file=
g_numphp=0
g_php_ini_list=
g_user_modify_ini=
g_user_chosen_php=
g_php_ver=
g_pi_extdir=
g_php_include_dir=
g_php_mod_ver=
php_support_zts=
without_php_ok=
prefix=
is_root=
g_etc_base_path=/etc/oneapm
g_log_base_path=/var/log/oneapm
g_daemon_path=
g_daemonloc=/usr/bin/oneapm-daemon
g_sock_loc=/etc/oneapm/.oneapm-daemon.domain

one_apm_php_log=${g_etc_base_path}/.oneapmphp.log
one_apm_php_ini_log=${g_etc_base_path}/.oneapmphpini.log
one_apm_time_pid=`date +%Y%m%d-%H%M%S 2> /dev/null`
one_apm_time_pid="${one_apm_time_pid}-$$"
g_one_apm_install_log=/tmp/oneapm-install-${one_apm_time_pid}.log
g_one_apm_sys_info=/tmp/oneapm-install-${one_apm_time_pid}.sysinfo
g_one_apm_log_tar=/tmp/oneapm-install-${one_apm_time_pid}.tar
g_one_apm_begin_flag=';############# OneAPM Begin #############'
g_one_apm_end_flag=';############## OneAPM End ##############'
now=`date 2>/dev/null`

green_on="\033[32;49;1m"
green_off="\033[39;49;0m"
stty erase ^H

analysis_command_params() {
	if [ -n "${1}" ]; then
		if [ "${1}" = "install" ];  then
			action="install"
			shift;
			while [ $# -ge 1 ]; do
				local tmp=`echo ${1}`
				if [ "${tmp:0:9}"X = "--license"X ]; then
					g_install_license=`echo ${tmp:10}`; shift;
				elif [ "${tmp:0:10}"X = "--php-path"X ]; then
					g_php_params_path=`echo ${tmp:11}`
					echo ${g_php_params_path};
					[ ! -d ${g_php_params_path} ] && { echo "sorry, not found your file! please check your php path"; exit 1; }
					shift
				elif [ "${tmp:0:14}"X = "--php-ini-file"X ]; then
					g_php_ini_params_file=`echo ${tmp:15}`
					echo ${g_php_ini_params_file};
					[ ! -f ${g_php_ini_params_file} ] && { echo "sorry, not found your php.ini file! please check your php.ini path"; exit 1; };
					shift
				elif [ "${tmp:0:9}"X = "--appname"X ];then
					g_appname=`echo ${tmp:10}`
					echo ${g_appname};
					[ ${#g_appname} -gt 64 ] && g_appname=`echo ${g_appname:0:63}`
					shift
				elif [ "${tmp:0:13}"X = "--thread_safe"X ]; then
					 php_support_zts=`echo ${tmp:14}`
					 echo ${php_support_zts}
					 [ ${php_support_zts} = "yes" -o ${php_support_zts} = "no" ] || { echo "sorry,your parameter php_support_zts not valid!"; exit 1;}
					 shift
				elif [ "${tmp:0:9}"X = "--version"X ]; then
					 g_php_ver=`echo ${tmp:10}`
					 echo ${g_php_ver}
					 shift
				elif [ "${tmp:0:15}"X = "--extension_dir"X ]; then
					 g_pi_extdir=`echo ${tmp:16}`
					 echo ${g_pi_extdir};
					 [ ! -d ${g_pi_extdir} ] && { echo "sorry, not found your file! please check extension directory"; exit 1;}
					 shift
				else
					echo "maybe params error"
					show_script_usage && exit 0
				fi
			done
		elif [ "${1}" = "uninstall" ]; then
			action="uninstall"
			shift
		elif [ "${1}" = "--help" ]; then
			show_script_usage && exit 0
		else
			echo "maybe params error"
			show_script_usage && exit 0
		fi
	fi
	echo "analysis_command_params finish"
}

#
# Set up enough of the error handling environment so we can error out
# in the event we don't like the O/S we're on.
#
error() {
	echo "ERROR: $@" >> $g_one_apm_install_log
	echo "ERROR: $@" >&2
}

as_root_run_check() {
	myuid=`id -u 2>/dev/null`
	if [ "${myuid}" != "0" ]; then
		is_root=0;
		echo "the user is not root"
	else
		is_root=1;
		echo 'the user is root'
	fi
}
add_user_director_x_authority()
{
	#cd ~
	#user=`who |head -1|cut -d ' ' -f 1`
	#chmod -R  +x ../${user} 2> add_execute_log
	#rm -f add_execute_log
	#cd ${prefix}
	ioIFS="$IFS"
	IFS="/"
	local path=
	local local_prefix=`echo ${prefix:1}`
	for directory in ${local_prefix}; do
		path="${path}/${directory}"
		if [ "${path}" ！= "/home" ]; then
			chmod +x ${path}
		fi
	done
	chmod -R +x ../
}
change_install_path()
{
	prefix=`pwd`;
	g_etc_base_path=${prefix}/etc/oneapm
	one_apm_php_log=${g_etc_base_path}/.oneapmphp.log
	one_apm_php_ini_log=${g_etc_base_path}/.oneapmphpini.log
	g_sock_loc=${prefix}${g_sock_loc}
	g_log_base_path=${prefix}/var/log/oneapm
	g_daemon_path=${prefix}/usr/bin/
	g_daemonloc="${g_daemon_path}oneapm-daemon"
	if [ -z ${g_pi_extdir} -a -z ${g_php_params_path} ]; then
		g_pi_extdir=${prefix}/extension/
	fi
	g_one_apm_install_log=${prefix}${g_one_apm_install_log}
	g_one_apm_sys_info=${prefix}${g_one_apm_sys_info}
	g_one_apm_log_tar=${prefix}${g_one_apm_log_tar}
}


kill_running_daemon() {
	[ -n "${g_daemon_pid}" ] && { kill -9 ${g_daemon_pid} > /dev/null 2>&1; sleep 1; kill -9 ${g_daemon_pid} > /dev/null 2>&1; }
}
get_os_type() {
	if [ -f /etc/redhat-release -o -f /etc/redhat_version ]; then
		g_ostype=rhel
	elif [ -d /etc/dpkg ]; then
		g_ostype=debian
	elif [ -f /etc/release ]; then
		if grep Solaris /etc/release > /dev/null 2>&1; then
			g_ostype=solaris
		fi
	fi

	if [ -z "${g_ostype}" ]; then
		local tus=`uname -s 2> /dev/null`
		case "${tus}" in
			[Dd][Aa][Rr][Ww][Ii][Nn])     g_ostype=darwin ;;
			[Ff][Rr][Ee][Ee][Bb][Ss][Dd]) g_ostype=freebsd ;;
			[Ss][Uu][Nn][Oo][Ss])         g_ostype=solaris ;;
			[Ss][Mm][Aa][Rr][Tt][Oo][Ss]) g_ostype=solaris ;;
		esac
	fi
	: ${g_ostype:=generic}
	if [ "${g_ostype}" = "freebsd" -o "${g_ostype}" = "solaris" -o "${g_ostype}" = "darwin" ] ; then
		error "unsupported os type"
		exit 1
	fi

}
find_apm_install_base_dir() {
	local myloc=
	case "$0" in
		*/*) myloc=$0 ;;
		*) oIFS=$IFS
			IFS=$PATH_SEPARATOR
			for d in $PATH; do
				IFS="${oIFS}"
				[ -z "$d" ] && d="."
				[ -r "$d/$0" ] && {
					myloc="$d/$0"
					break
				}
			done
			IFS="${oIFS}"
			;;
	esac

	[ -z "${myloc}" ] && myloc=$0
	[ -z "${myloc}" ] && { error "existential crisis: could not find myself. Re-run with absolute path."; exit 1; }
	# Extract dir
	local mydir="${myloc%/*}"
	g_one_apm_install_base_dir=`(cd "${mydir}" 2> /dev/null; pwd 2>/dev/null)`
}

check_arch_type() {
	#
	# Determine the architecture we are executing on.
	#
	g_arch=`(uname -m) 2> /dev/null` || g_arch="unknown"

	case "${g_arch}" in
		i[3456789]86)         g_arch=x86 ;;
		*64* | *amd*)         g_arch=x64 ;;
		unknown)              g_arch=x86 ;;
	esac
}

######################################################
# Do some sanity checking. g_one_apm_install_base_dir should contain the 
# daemon, the agents and the init scripts.
######################################################

check_dir() {
	if [ ! -d "$1" ]; then
		[ -n "$1" ] && g_dmissing="${1}${nl}${g_dmissing}"
	fi
}

check_file() {
	if [ ! -f "$1" ]; then
		[ -n "$1" ] && g_fmissing="${1}${nl}${g_fmissing}"
	fi
}

check_install_dir_and_files() {
	# check directories and files
	if [ -z "${OA_INSTALL_LOCATION}" ]; then
		local daemon_dir="${g_one_apm_install_base_dir}/daemon"
		g_oa_daemon_bin="${g_one_apm_install_base_dir}/daemon/oneapm-daemon-${g_arch}"
		for d in "${g_one_apm_install_base_dir}/scripts" "${g_one_apm_install_base_dir}/agent" "${daemon_dir}"; do
			check_dir "${d}"
		done
	fi
	check_dir "${g_one_apm_install_base_dir}/agent/${g_arch}"
	if [ "${g_arch}" = "x86" ]; then
		[ -z "${OA_INSTALL_LOCATION}" ] && { check_dir "${g_one_apm_install_base_dir}/agent/x64"; } 
	fi
	if [ "${g_arch}" = "x64" ]; then
		[ -z "${OA_INSTALL_LOCATION}" ] && { check_dir "${g_one_apm_install_base_dir}/agent/x86"; }
	fi

	[ -n "${g_dmissing}" ] && { error "the following directories could not be found:"; echo "${g_dmissing}" | sed -e 's/^/   /' >&2; }
	[ -z "${OA_INSTALL_LOCATION}" ] && { check_file "${g_oa_daemon_bin}"; }

	check_file "${g_one_apm_install_base_dir}/scripts/init.rhel"
	check_file "${g_one_apm_install_base_dir}/scripts/init.debian"
	check_file "${g_one_apm_install_base_dir}/scripts/init.solaris"
	check_file "${g_one_apm_install_base_dir}/scripts/init.generic"
	check_file "${g_one_apm_install_base_dir}/scripts/init.darwin"
	check_file "${g_one_apm_install_base_dir}/scripts/oneapm.cfg.template"

	for pmv in "php5.2" "php5.3" "php5.4" "php5.5" "php5.6" "php7.0" ; do
		if [ -n "${g_arch}" ]; then
			check_file "${g_one_apm_install_base_dir}/agent/${g_arch}/oneapm-${pmv}.so"
			check_file "${g_one_apm_install_base_dir}/agent/${g_arch}/oneapm-${pmv}-zts.so"
		fi
	done
	# when rpm package install, will set env var:OA_INSTALL_LOCATION. so tar.gz install not run
	if [ -n "${OA_INSTALL_LOCATION}" ]; then
		check_file "/usr/bin/oneapm-daemon"
		check_file "/usr/bin/oneapm-install-rpm-deb.sh"
		check_file "${g_one_apm_install_base_dir}/oneapm-install"
	fi

	[ -n "${g_fmissing}" ] && { error "the following files could not be found:"; echo "${g_fmissing}" | sed -e 's/^/   /' >&1; }
	[ -n "${g_dmissing}" -o -n "${g_fmissing}" ] && { print_oa_dfmissing_info; exit 1; }

}
write_oa_sys_info_file() {
	local oneapm_uname=`uname -a 2>/dev/null`
	# And the sysinfo file
	echo "OneAPM Agent Install sysinfo dated: $now" > $g_one_apm_sys_info
	echo "ONEAPMVERSION: ${oneapmversion}" >> $g_one_apm_sys_info
	echo "ONEAPM_INSTALL_LOCATION: ${g_one_apm_install_base_dir}" >> $g_one_apm_sys_info
	echo "ARCH: ${g_arch}" >> $g_one_apm_sys_info
	echo "UNAME: $oneapm_uname" >> $g_one_apm_sys_info
	env | sort | sed -e 's/^/ENV: /' >> $g_one_apm_sys_info
}
guess_php_bin_path() {
	local found_path="/usr/local /usr/bin /opt"
	for found in ${found_path}; do
		local php_tmp=$(find ${found} -xtype f -name php)
		for e in $php_tmp; do
			local nf=$(echo "$e" |awk -F"/" '{print NF}')
			[ $nf -gt 2 ] && e="${e%/*}"
			g_guess_php_list="${g_guess_php_list}${PATH_SEPARATOR}${e}"
			echo "bin path ${e}";
		done
		g_guess_php_list=${g_guess_php_list#${PATH_SEPARATOR}}
	done
}

cleanup() {
	(cd "${prefix}/tmp"
		tar cf "${g_one_apm_log_tar}" ${g_one_apm_install_log} ${g_one_apm_sys_info} > /dev/null 2>&1)
		rm -f ${g_one_apm_install_log} ${g_one_apm_sys_info} > /dev/null 2>&1
}

fatal() {
	echo "FATAL: $@" >> $g_one_apm_install_log
	echo "FATAL: $@" >&2
	print_oa_fatal_error_info
	exit 1
}

log() {
	echo "$@" >> $g_one_apm_install_log
}
info() {
	echo -e "$@\n" >> $one_apm_php_log
}
ini_info() {
	echo -n "$@" >> $one_apm_php_ini_log
}
logcmd() {
	echo "Executing: $@" >> $g_one_apm_install_log
	"$@" >> $g_one_apm_install_log 2>&1
	ret=$?
	echo "Command returned: $ret" >> $g_one_apm_install_log
	return $ret
}

banner() {
	clear
	echo "${bold}OneAPM PHP Agent Installation ${rmso}"
	echo "======================================================="
	echo ""
	echo -e "${green_on} you can use 'ctrl+c' to interrupt install, backup your ini file to avoid incorrect write. ${green_off}"
	echo ""
}

count_php() {
	if [ -z $1 ];then
		g_numphp=0
	else
		oIFS="$IFS"
		IFS=${PATH_SEPARATOR}
		set -- $1
		g_numphp=$#
		IFS="${oIFS}"
	fi
}
choose_list() {
	local prompt="$1"; shift
	local upper=$1; shift
	local choice=

	while [ -z "${choice}" ]; do
		echo -n  "${prompt} (1-${upper}, 0 to exit):"
		read choice
		case "${choice}" in
			0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;;
			*) choice= ;;
		esac
		if [ -n "${choice}" ]; then
			[ $choice -ge 0 -a $choice -le $upper ] && break
		fi
	done
	case ${choice} in
		0)  exit 0 ;;
		2)  action="uninstall" ;;
		*)  action="install" ;;
	esac
}

id_to_php_location() {
	local gin=1
	local gioIFS="$IFS"
	IFS=${PATH_SEPARATOR}
	for giod in $g_guess_php_list; do
		if [ $gin -eq $1 ]; then
			echo "${giod}"
			break
		fi
		gin=$(($gin+1))
	done
	IFS="${gioIFS}"
}

# Display a list of choices of PHP location and allow
# the user to select which of the location to work on.
display_get_php_list_and_chosen() {
	local pln=0
	oIFS="$IFS"
	IFS=${PATH_SEPARATOR}
	for d in ${g_guess_php_list}; do
		pln=$(($pln+1))
		IFS="$oIFS"
		if [ $pln -lt 10 ]; then
			spaces="   "
		else
			spaces= "  "
		fi
		echo "   ${pln})${spaces}${d}"
	done
	IFS="$oIFS"
	echo ""

	if [ $pln -eq 0 ]; then
		log "Empty PHP directory list"
		echo "${bold}We couldn't find any complete enough PHP installs.${rmso}"
	fi
	
	pln=$(($pln+1))
	echo "   ${pln})   Enter path by yourself"
	echo ""
	echo "( use command ${bold}'find / -xtype f -name 'php'|sed 's/\/php$//g''${rmso} to find the bin path of PHP )"

	echo ""
	echo "   0)   Exit"
	echo ""

	local valid=0
	while [ $valid -eq 0 ]; do
		if [ $pln -eq 1 ]; then
			echo -n "   Selection (1, 0 to exit):"
		else
			echo -n "   Selection (1-${pln}, 0 to exit):"
		fi
		read sel
		if [ -n "$sel" ]; then
			valid=1
			case "${sel}" in
				0) exit 0 ;;
				${pln}) 
					echo ""
					local badpath=1
					while [ "${badpath}" == "1" ]; do
						echo -n "  Enter path of PHP:"
						read g_user_chosen_php
						[ -n "${g_user_chosen_php}" -a -d ${g_user_chosen_php} ] && badpath=0
					done ;;
				[1-9] | [1-9][0-9] | [1-9][0-9][0-9])
					if [ $sel -gt $pln ]; then
						valid=0
					else
						g_user_chosen_php=`id_to_php_location $sel`
					fi
					;;
				*) valid=0 ;;
			esac
		else
			valid=0
		fi
		[ -n "${g_user_chosen_php}" -a -d "${g_user_chosen_php}" ] || { echo " your chose php is not exist! please retype"; valid=0; }
	done
	echo ""
	return 0
}
set_os_init_file() {
	if  [ -f /etc/arch-release ]; then
		# It is possible that this is only for freebsd
		: ${g_os_init_file:=/etc/rc.d/oneapm_daemon_service}
	else
		: ${g_os_init_file:=/etc/init.d/oneapm_daemon_service}
	fi
}
set_os_init_file_and_install() {
	set_os_init_file
	if logcmd cp -f "${g_one_apm_install_base_dir}/scripts/init.${g_ostype}" "${g_os_init_file}"; then
		logcmd chmod 755 "${g_os_init_file}" || {
			echo "warning: failed to copy daemon init script to ${g_os_init_file}" >> $g_one_apm_install_log
		}
	else	
		echo "warning: failed to copy daemon init script to ${g_os_init_file}" >> $g_one_apm_install_log
	fi
	#delete before version
	rm -rf "${g_os_init_file%/*}/oneapm-daemon-service"
	logcmd cp -f "${g_one_apm_install_base_dir}/scripts/oneapm.cfg.template" ${g_etc_base_path}/oneapm.cfg
}

set_daemon_location_and_install() {
	if [ -z "${OA_INSTALL_LOCATION}" ]; then
		
		if logcmd rm -f "${g_daemonloc}"; then
			if logcmd cp -f "${g_oa_daemon_bin}" "${g_daemonloc}"; then
				logcmd chmod 755 "${g_daemonloc}"
				logcmd chmod u+s "${g_daemonloc}"
				log "daemon installed"
				info "g_daemonloc :${g_daemonloc}"
			else
				fatal "failed to copy new daemon into place"
			fi
		else
			fatal "could not remove existing daemon"
		fi
	else
		if [ -f "${g_daemonloc}" ]; then
			logcmd chmod 755 "${g_daemonloc}"; logcmd chmod u+s "${g_daemonloc}";
		else
			fatal "no found oneapm-daemon"
		fi
	fi
}

get_php_ver_info() {
	[ $# -lt 2 ] && { echo "get_php_ver_info() params incorrect"; exit 1; }
	local php_bin_dir=${1}
	local one_php_bin=${2}
	
	[ -n "${one_php_bin}" ] && { g_php_ver=`echo '<?php print phpversion(); ?>' | ${one_php_bin} -d display_errors=Off -d display_startup_errors=Off -d error_reporting=0 -q 2> /dev/null`; }
	[ -z "${g_php_ver}" ] && { g_php_ver=`${php_bin_dir}/php-config --version 2> /dev/null`; }

	[ -z "${g_php_ver}" ] && { fatal "could not determine the version of PHP located at: ${php_bin_dir}"; }
	log "${php_bin_dir}: g_php_ver=${g_php_ver}"

	case "${g_php_ver}" in
		5.2.* | 5.3.* | 5.4.* | 5.5.* | 5.6.* | 7.0.*)
			;;
		*)
			fatal "unsupported version '${g_php_ver}' of PHP found at: ${php_bin_dir}"
			;;
	esac
}
found_other_ini_files() {
	[ $# -lt 1 ] && { echo "found_other_ini_files() params incorrect"; exit 1; }
	local php_bin=${1}
	local php_config_path=`echo '<?php print PHP_CONFIG_FILE_PATH; ?>'    | ${php_bin} -d display_errors=Off -d display_startup_errors=Off -d error_reporting=0 -q 2> /dev/null`
	local nf=$(echo "$php_config_path" |awk -F"/" '{print NF}')
	[ $nf -gt 2 ] && php_config_path=${php_config_path%/*}
	
	local all_ini_list=$(find ${php_config_path} -name php.ini)
	for e in ${all_ini_list}; do
		g_php_ini_list="${g_php_ini_list}${PATH_SEPARATOR}${e}"
	done
	
	[ -z "${g_php_ini_params_file}" ] || {
		echo "$g_php_ini_list" | grep "${g_php_ini_params_file}";
		[ $? -eq 1 ] && g_php_ini_list="${g_php_ini_list}${PATH_SEPARATOR}${g_php_ini_params_file}"
	}
	
	[ -z "${g_php_ini_list}" -a "${all_ini_list}"X != "/etc"X ] && {
		all_ini_list=$(find /etc -name php.ini)
		for e in ${all_ini_list}; do
			g_php_ini_list="${g_php_ini_list}${PATH_SEPARATOR}${e}"
		done
	}
	#${g_user_modify_ini} only uninstall using
	[ -z "${g_php_ini_list}" -a -z "${g_user_modify_ini}" ] && {
		echo -e "${green_on} not found php.ini file ${green_off}"
		echo -e "${green_on} please enter yourself php.ini path: ${green_off}"
		while [ -z "${inifile_tmp}" ]; do
			read inifile_tmp
			[ -f ${inifile_tmp} ] || { echo "your need to retype"; inifile_tmp=""; }
		done
	}
	g_php_ini_list="${g_php_ini_list}${PATH_SEPARATOR}${inifile_tmp}"
	g_php_ini_list=${g_php_ini_list#${PATH_SEPARATOR}}
}

get_ext_ini_path() {
	[ $# -lt 2 ] && { echo "get_ext_ini_path() params incorrect"; exit 1; }
	if [ -z "${g_pi_extdir}" ];  then
		local php_bin_dir="${1}"
		local one_php_bin=${2}
		if [ -n "${one_php_bin}" ]; then
			g_pi_extdir=`echo '<?php print ini_get("extension_dir"); ?>'     | ${one_php_bin} -d display_errors=Off -d display_startup_errors=Off -d error_reporting=0 -q 2> /dev/null`
			[ -z "${g_pi_extdir}" -a -f "${php_bin_dir}/php-config" ] && { g_pi_extdir=`${php_bin_dir}/php-config --extension-dir 2> /dev/null`; }
			[ "${g_pi_extdir}" = "." -o "${g_pi_extdir}" = "./" ] && { g_pi_extdir=`${php_bin_dir}/php-config --extension-dir 2> /dev/null`; }
		fi
	fi
	[ -z "${g_pi_extdir}" ] && { error "could not determine extension directory for the PHP located at: ${php_dir}"; exit 1; }
}

get_php_include_dir() {
	[ $# -lt 1 ] && { echo "get_php_include_dir() params incorrect"; exit 1; }
	local php_bin_dir=${1}
	if [ -x "${php_bin_dir}/php-config" ]; then
		g_php_include_dir=`${php_bin_dir}/php-config --include-dir 2> /dev/null`
		[ -n "${g_php_include_dir}" -a -d "${g_php_include_dir}" -a -d "${g_php_include_dir}/main" -a -d "${g_php_include_dir}/Zend" ] || g_php_include_dir=
	fi
	log "${php_bin_dir}: g_php_include_dir=${g_php_include_dir}"
}

get_php_mod_api_ver_and_zts() {
# $# -lt 2 ] && { echo "get_php_mod_api_ver_and_zts() params incorrect"; exit 1; }
#local php_bin_dir="${1}"
	if [ -z "${php_support_zts}" ] ; then
		if [ $# -eq 1 ] ; then
			local one_php_bin="${1}"
			if [ -f "${one_php_bin}" ]; then
				if ${one_php_bin} -i | grep 'Thread Safety' | grep 'enabled' > /dev/null 2>&1; then
					php_support_zts="yes"
				else
					php_support_zts="no"
				fi
			fi
			if [ -z "${php_support_zts}" ]; then
				if [ -n "${g_php_include_dir}" -a -f "${g_php_include_dir}/main/php_config.h" ]; then
					if grep '^#define[ 	]*ZTS[ 	]*1' "${g_php_include_dir}/main/php_config.h" > /dev/null 2>&1; then
						php_support_zts="yes"
					else
						php_support_zts="no"
					fi
				else
					php_support_zts="no"
					case "${g_pi_extdir}" in
						*non-zts* | *no-zts*) ;;
						*zts*)  php_support_zts="yes" ;;
						*) ;;
					esac
				fi
			fi
		fi
	fi

	case "${g_php_ver}" in
		5.2.*)  g_php_mod_ver="20060613" ;;
		5.3.*)  g_php_mod_ver="20090626" ;;
		5.4.*)  g_php_mod_ver="20100525" ;;
		5.5.*)  g_php_mod_ver="20121212" ;;
		5.6.*)  g_php_mod_ver="20131226" ;;
		7.0.*)	g_php_mod_ver="20151012" ;;
	esac
	[ -z "${g_php_mod_ver}" ] && { error "not found support php module version"; exit 1; } 
	
	

	
	[ -z "${php_support_zts}" ] && { error "zts is incorrect"; exit 1; }
	log "g_php_mod_ver=${g_php_mod_ver}"
	log "php_support_zts=${php_support_zts}"
}

# Four things about PHP are important for a successful installation
# 1. Extension API version.
# 2. Extension load directory.
# 3. ZTS used or not
gather_php_info() {
	[ $# -lt 1 ] && { echo "gather_php_info() params incorrect"; exit 1; }
	local php_dir="$1"
	local got_one_php_bin=
	# Get the path to the binary
	# no php-config on ubuntu

	if [ -z "${got_one_php_bin}" ]; then
		[ -x "${php_dir}/php" ] && got_one_php_bin="${php_dir}/php"	
	fi
	[ -z "${got_one_php_bin}" ] && { error "not found php bin: ${php_dir}"; exit 1; }
	log "${php_dir}: got_one_php_bin=${got_one_php_bin}"
	
	# check php env to prevent php crash
	if [ -n "${got_one_php_bin}" ]; then
		{ ${got_one_php_bin} -i 2>&1 >/dev/null; } || {
			fatal "${bold} your php env maybe occur crash!! please enter "${got_one_php_bin}" -i to confirm it${rmso}"
		}
	fi
	if [ -n "${got_one_php_bin}" ]; then
		log "${php_dir}: php -i output follows {"
		${got_one_php_bin} -i  >> ${g_one_apm_install_log} 2> /dev/null
		log "${php_dir}: php -i output done }"
	fi
	
	get_php_include_dir ${php_dir}
	get_php_ver_info  ${php_dir} ${got_one_php_bin}
	get_ext_ini_path ${php_dir} ${got_one_php_bin}
	get_php_mod_api_ver_and_zts ${got_one_php_bin}
	
	found_other_ini_files ${got_one_php_bin}
	echo "Found a valid PHP in : ${php_dir}"
	echo "         PHP Version : ${g_php_ver}"
	echo "  Module API version : ${g_php_mod_ver}"
	echo "    Module directory : ${g_pi_extdir}"
	echo "  Zend Thread Safety : ${php_support_zts}"
	info " 			   php_dir :${php_dir}"
	info " 		   g_pi_extdir :${g_pi_extdir}"
	info "		g_php_ini_list :${g_php_ini_list}"
	[ -n "${g_php_ini_list}" ] && echo "        all CLI ini file : ${g_php_ini_list}"
	
	log "${php_dir}: final g_php_ini_list=${g_php_ini_list}"
}
gather_php_info_without_php()
{
	without_php_ok=1
	if [ -z ${php_support_zts} ] ; then
			without_php_ok=0
	fi

	if [ -z ${g_php_ver} ] ; then
		
			without_php_ok=0
	fi

	if [ -z ${g_pi_extdir} ]; then
			without_php_ok=0
	fi

	if [ -z ${g_php_ini_params_file} ]; then
		without_php_ok=0
	fi
		g_php_ini_list=${g_php_ini_params_file}
	if [ ${without_php_ok} = 1 ] ; then
		get_php_mod_api_ver_and_zts
		echo "          PHP Version : ${g_php_ver}"
		echo "   Module API version : ${g_php_mod_ver}"
		echo "     Module directory : ${g_pi_extdir}"
		echo "   Zend Thread Safety : ${php_support_zts}"
		info "          g_pi_extdir :${g_pi_extdir}"
		info "		 g_php_ini_list :${g_php_ini_params_file}"
	fi
}

get_host_name_write_ini() {
	[ -f "/bin/hostname" ] && { hostname=`/bin/hostname`; }
	[ -z "$hostname" ] && { hostname=`echo $HOSTNAME`; }
	[ -z "$hostname" ] && { hostname=`cat /proc/sys/kernel/hostname`; }
	
	if [ -n "$hostname" ]; then
		if [ ${#hostname} -gt 64 ]; then
			hostname=`echo "PHP_${hostname:0:59}"`
		else 
			hostname=`echo "PHP_${hostname}"`
		fi
		sed -i "s/;oneapm.appname=.*/oneapm.appname="${hostname}"/" "${1}"
	fi
}

del_php_ini_oneapm_info() {
	[ $# -lt 1 ] && { echo "del_php_ini_oneapm_info() params error"; exit 1; }
	for tmp in ${1}; do
		if [ -f "$tmp" ]; then
			sed -i '/oneapm\./d' "$tmp"
			sed -i '/^[\t ]*\[oneapm\].*$/d' "$tmp"
			sed -i '/^;\~.*$/d' "$tmp"
			sed -i '/OneAPM Begin/d' "$tmp"
			sed -i '/OneAPM End/d' "$tmp"
			sed -i '/oneapm.communicate_loc/d' "$tmp"
			sed -i '/oneapm.var_loc/d' "$tmp"
			sed -i '/oneapm.daemon_loc/d' "$tmp"
		fi
	done
}

echo_line_num_add_oa_ini_info() {
	[ $# -lt 1 ] && { echo "echo_line_num_add_oa_ini_info() params error"; exit 1; }
	local inifile=${1}
	local num=`grep -n "oneapm.so" ${inifile} |awk -F":" '{print $1}'`
	local nf=$(echo $num |awk -F" " '{print NF}')
	[ $nf -eq 1 ] || { error "please delete the "oneapm.so" line in your php.ini."; exit 1; }

	sed -n "1,${num}p" ${inifile} > ${g_etc_base_path}/.ini1.txt
	[ -n "${num}" ] && { ((num++)); }
	
	sed -n "${num},\$p" ${inifile} > ${g_etc_base_path}/.ini2.txt
	show_oa_php_ini_info >> ${g_etc_base_path}/.ini1.txt
	echo "${g_one_apm_end_flag}" >> ${g_etc_base_path}/.ini1.txt
	cat ${g_etc_base_path}/.ini2.txt >> ${g_etc_base_path}/.ini1.txt
	mv ${g_etc_base_path}/.ini1.txt ${1}
	rm ${g_etc_base_path}/.ini2.txt
}

modify_user_phpini_file() {
	[ $# -lt 1 ] && { echo "no ini path"; exit 1; }
	local inifile=${1}
	local oa_ini_info="\n[oneapm]\noneapm.key = \"${g_install_license}\"\n"
	if [ "${g_pi_extdir}"X = "."X -o "${g_pi_extdir}"X = "./"X ]; then
		oa_ini_info=${oa_ini_info}"extension=${g_etc_base_path}/oneapm.so\n"
	else
		oa_ini_info="${oa_ini_info}extension=${g_pi_extdir}/oneapm.so\n"
	fi
	if [ ${is_root} -eq 0 ]; then
		oa_ini_info="${oa_ini_info}oneapm.unix_socket_path= \"${g_sock_loc}\"\n"
		oa_ini_info="${oa_ini_info}oneapm.var_path=\"${g_log_base_path}\"\n"
		oa_ini_info="${oa_ini_info}oneapm.daemon_path=\"${g_daemonloc}\"\n"
	fi
	local add_begin_flag="\n${g_one_apm_begin_flag}\n${oa_ini_info}"
	# filter inifile and sort
	if [ -f "${inifile}" ]; then
		grep -n "^\[HOST=.*\]$" ${inifile} > ${g_etc_base_path}/.findtmp
		grep -n "^\[PATH=.*\]$" ${inifile} >> ${g_etc_base_path}/.findtmp
		grep -n "^\[Zend.*\]$" ${inifile} >> ${g_etc_base_path}/.findtmp
		grep -n "^\[CLI Server.*\]$" ${inifile} >> ${g_etc_base_path}/.findtmp
		local find_num=$(sort -n ${g_etc_base_path}/.findtmp |head -n 1 |awk -F":" '{print $1}')
		if [ -n "${find_num}" ]; then
			sed -i "${find_num} i\ ${add_begin_flag}" ${inifile}
		else
			echo -e "${add_begin_flag}" >> "${inifile}"
		fi
		echo_line_num_add_oa_ini_info "${inifile}"
		rm -f ${g_etc_base_path}/.findtmp
	fi

	if [ -n "${g_appname}" ]; then
		sed -i "s/;oneapm.appname=.*/oneapm.appname=${g_appname}/" "${inifile}"
	fi
}

back_ini_file() {
	[ $# -lt 2 ] && { echo "back_ini_file() params is incorrect"; exit 1; }
	local ini_list=${1}
	local bef_aft_flag=${2}
	ioIFS="$IFS"
	IFS=${PATH_SEPARATOR}
	for t in ${ini_list}; do
		if [ -f "${t}" ]; then
			local ren=`echo ${t} |sed 's/\//_/g'`
			local uninstall_before_bak=${prefix}/tmp/.${ren}.${bef_aft_flag}
			cp -f "${t}" "${uninstall_before_bak}"
		fi
	done
	IFS="${ioIFS}"
}

warn_backup_ini_file() {
	[ $# -lt 1 ] && { echo "warn_backup_ini_file() params is incorrect"; exit 1; }
	echo "please backup your ini file: ${1} to avoid write incorrect"
	sleep 10
}

add_oneapm_php_info() {
	[ $# -lt 2 ] && { echo "add_oneapm_php_info() params is incorrect"; exit 1; }
	local ini_file="${1}"
	local yes_or_no="${2}"
	if [ -f "${ini_file}" ]; then
		back_ini_file "${ini_file}" "oneapm.nomod"
		del_php_ini_oneapm_info ${ini_file}
		if [ "${yes_or_no}" = "yes" ]; then
			g_changed_ini_file=${ini_file} 
			modify_user_phpini_file "${ini_file}"
		fi
		back_ini_file "${ini_file}" "oneapm.mod"
	fi
}

change_ini_file(){
	[ $# -lt 2 ] && { echo "change_ini_file() params is incorrect"; exit 1; }
	local inifile_tmp=$(echo "${1}" |grep "php.ini")
	# install_flag is "yes" or "no" 
	local install_flag=${2}
	ioIFS="$IFS"
	IFS=${PATH_SEPARATOR}
	if [ -n "${inifile_tmp}" ]; then
		#warn_backup_ini_file "${inifile_tmp}"
		for php_ini in ${inifile_tmp}; do
			add_oneapm_php_info "${php_ini}" "${install_flag}"
		done
	fi
	IFS="${ioIFS}"
}

install_agent_here() {
	local istat=
	[ "${php_support_zts}" = "yes" ] && zts="-zts"
	local srcf="${g_one_apm_install_base_dir}/agent/${g_arch}/oneapm-php${g_php_ver:0:3}${zts}.so"
	[ -d ${g_pi_extdir} ] || mkdir -p ${g_pi_extdir}
	local destf="${g_pi_extdir}/oneapm.so"
	while [ -z "${g_install_license}" ]; do
		echo ""
		echo -n "   Enter OneAPM license key :"
		read g_install_license
	done
	
	# copy agent
	logcmd cp -f "${srcf}" "${destf}" || {
		istat="failed"
		fatal " copy '${srcf}' -> '${destf}' FAILED!"
	}
	
	[ "${istat}"X = "failed"X ] && { error "maybe copy failed"; exit 1; }
	[ "${action}" = "install" ] && { change_ini_file "${g_php_ini_list}" "yes"; }
	
	
	[ -z "${istat}" ] && istat="OK"
	echo "     agent Status : ${istat}"
	log " agent status: ${istat}"
}

check_selinux() {
	command -v selinuxenabled > /dev/null 2>&1 
	if [ $? = 0 ];then
			selinuxenabled
			if [ $? = 0 ]; then 
					enforce_status=`getenforce`
					[ $enforce_status = "Permissive" ] && { echo "Warning : Your SELinux is not fully closed, the system can't use oneapm after restart machine."; 
						logcmd "Warning : Your SELinux is not fully closed, the system can't use oneapm after restart machine."; sleep 2;
					}
							 
					[ $enforce_status = "Enforcing" ] && { fatal "You need to set SELINUX to permissive or disable"; }
			fi   
	fi   
}

create_log_etc_ext_dae_dir() {
	[ ! -d ${g_log_base_path} ] && { logcmd mkdir -p ${g_log_base_path}; logcmd chmod 0777 ${g_log_base_path}; log "created ${g_log_base_path}"; }
	[ ! -d ${g_etc_base_path} ] && { logcmd mkdir -p ${g_etc_base_path}; logcmd chmod 0755 ${g_etc_base_path}; log "created ${g_etc_base_path}"; }
	[ ! -d ${g_daemon_path} ] && { logcmd mkdir -p ${g_daemon_path}; logcmd chmod 0755 ${g_etc_base_path}; log "created ${g_etc_base_path}"; }
	[ ! -d ${g_pi_extdir} ] && { logcmd mkdir -p ${g_pi_extdir}; logcmd chmod 0755 ${g_pi_extdir}; log "created ${g_pi_extdir}"; }

}


run_daemon() {
	${g_daemonloc}
	if [ $? -eq 0 ]; then
		print_install_success_info
	else
		fatal "run daemon failed, please run daemon by hand";
	fi
}

init_php_install_file(){
        echo > $one_apm_php_log; echo > $one_apm_php_ini_log;
}

create_tmp_path_file() {
	[ ! -d "${prefix}/tmp" ] && { mkdir ${prefix}/tmp; chmod 777 /tmp; }
	[ ! -f ${g_one_apm_install_log} ] && { touch ${g_one_apm_install_log}; }
	[ ! -f ${g_one_apm_sys_info} ] && { touch ${g_one_apm_sys_info}; }
	[ ! -f ${g_one_apm_log_tar} ] && { touch ${g_one_apm_log_tar}; }
}
do_install() {
	banner

	logcmd rm -f "${one_apm_php_log}"
	# filled it for check SELINUX, it need to disabled.
	check_selinux
	init_php_install_file
	gather_php_info_without_php
	if [ ${without_php_ok} = 1 ]; then 		#install without php
		install_agent_here
	else									#install with php
		if [ -z "${g_php_params_path}" ]; then
			# ${g_numphp} maybe not need
			count_php ${g_guess_php_list}
			[ ${g_numphp} -gt 1 ] && print_select_info
			
			# you can got ${g_user_chosen_php}
			[ -z "${g_php_params_path}" ] && display_get_php_list_and_chosen
			local php_debug_mode=`${g_user_chosen_php}/php -i | grep 'Debug' | grep 'yes'`
			[ -n "${php_debug_mode}" ] && { error "The '${g_user_chosen_php}'/php is in Debug mode. Please change the mode and try install again."; exit 1; }

			gather_php_info "${g_user_chosen_php}" 
			install_agent_here 
		else
			gather_php_info "${g_php_params_path}"
			install_agent_here 
		fi
	fi
	ini_info "${g_php_ini_list}"
	set_daemon_location_and_install
	set_os_init_file_and_install
	run_daemon
}

remove_so_from_here() {
	[ "${g_pi_extdir}" = "." -o "${g_pi_extdir}" = "./" ] && { g_pi_extdir=${g_etc_base_path}; }
	
	destf="${g_pi_extdir}/oneapm.so"
	[ -f "${destf}" ] && { logcmd rm -f "${destf}"; }

}

clear_daemon() {
	cd ${g_log_base_path} && cd .. && tar czf agent_daemon.tar.gz  oneapm/* && mv agent_daemon.tar.gz ${prefix}/tmp
	logcmd rm -f ${g_etc_base_path}/oneapm.cfg.template
	logcmd rm -f ${g_log_base_path}/oneapm-*
	logcmd rm -f ${g_log_base_path}/php_agent_*
	
	# Remove the daemon
	[ -z "${OA_INSTALL_LOCATION}" ] && { logcmd rm -f "${g_daemonloc}"; }
	# remove /etc/oneapm directory
	[ -d ${g_etc_base_path} ] && { logcmd rm -rf ${g_etc_base_path}; }
	# remove the default log directory
	[ -d ${g_log_base_path} ] && { logcmd rm -rf ${g_log_base_path}; }
	# Remove init script
	set_os_init_file
	[ -f ${g_os_init_file} ] && { logcmd rm -f ${g_os_init_file}; }
	[ $? -eq 0 ] && print_oa_uninstall_success_info
}

del_null_line() {
    [ $# -lt 1 ] && { echo "del_null_line() params is incorrect"; exit 1; } 
    local filename=${1}
    sed -ie '/^$/d' $filename
}

do_uninstall() {
	banner
	# bake up log files to /tmp
	#if [ -f "${one_apm_php_log}" ]; then
	#	del_null_line ${one_apm_php_log}
	#	local got_one_php_path=$(cat "${one_apm_php_log}" | grep ":")
	#	[ -n ${got_one_php_path} ] && got_one_php_path=${got_one_php_path%:*}
	#fi
	#
	#if [ -f "${one_apm_php_ini_log}" ]; then 
   #     	del_null_line ${one_apm_php_ini_log}
   #     	g_user_modify_ini=$(cat "${one_apm_php_ini_log}")
   # fi
	#
	#[ -z ${got_one_php_path} ] && { 
	#	display_get_php_list_and_chosen; 
	#	if [ -n "${g_user_chosen_php}" ]; then
	#		gather_php_info "${g_user_chosen_php}"
   #     fi
	#}
	#
	## for get g_pi_extdir
	#if [ -n "${got_one_php_path}" ]; then
	#	gather_php_info "${got_one_php_path}"
	#fi
	#
	#back_ini_file "${g_php_ini_list}" "before"
	#if [ -n "${g_user_modify_ini}" ]; then
	#	change_ini_file "${g_user_modify_ini}" "no"
	#else
	#	change_ini_file "${g_php_ini_list}" "no"
	#fi
	del_null_line ${one_apm_php_log}
	g_pi_extdir=`grep "g_pi_extdir" ${one_apm_php_log}|cut -d : -f 2`
	g_php_ini_list=`grep "g_php_ini_list" ${one_apm_php_log}|cut -d : -f 2`
	g_daemonloc=`grep "g_daemonloc" ${one_apm_php_log}|cut -d : -f 2`
	back_ini_file "${g_php_ini_list}" "before"
	change_ini_file "${g_php_ini_list}" "no"
	back_ini_file "${g_php_ini_list}" "after"
	#using g_pi_extdir
	remove_so_from_here
	kill_running_daemon
	clear_daemon
}


g_daemon_pid=`ps aux |grep oneapm-daemon | grep -v grep | awk {'print $2'}`

kill_running_daemon

analysis_command_params "$@"

if [ -z "${action}" ]; then
	print_oa_main_menu_info
	choose_list "   Enter choice" 2
fi
log "Install action: ${action}"

as_root_run_check

if [ ${is_root} -eq 0 ]; then
	change_install_path
fi
if [ "${action}" = "install" ]; then
	create_tmp_path_file
	create_log_etc_ext_dae_dir
fi
nl='
'

# Create the log file
echo "OneAPM Agent Install Log dated: $now" > $g_one_apm_install_log

get_os_type

: ${PATH_SEPARATOR:=':'}
# Find where is this script
find_apm_install_base_dir
check_arch_type
check_install_dir_and_files

trap cleanup EXIT

echo "ONEAPMVERSION: ${oneapmversion}" >> $g_one_apm_install_log

# Gather system information and store it in the sysinfo file
write_oa_sys_info_file

if [ -z ${g_php_params_path} ];then
	if [ ${is_root} -eq 1 ]; then
		guess_php_bin_path
		if [ -n "${g_guess_php_list}" ]; then
			log "Final PHP list is: ${g_guess_php_list}"
		else 
			log "No PHP found in ${g_guess_php_list}"
		fi
	fi
fi




bold=`tput bold 2> /dev/null`
rmso=`tput sgr0 2> /dev/null`

# for unit test
[ "${g_unit_test}"X = "y"X ] && { echo "unit test"; return 0; }



[ "${action}" = "install" ] 	&& do_install
[ "${action}" = "uninstall" ] 	&& do_uninstall

exit 0
