#!/bin/sh /etc/rc.common

. /lib/functions.sh

START=65
STOP=65

USE_PROCD=1

#退出后清理
exit_clean()
{
	[ -f "$1" ] && rm $1
	[ -f "$2" ] && rm $2
	[ -f "$3" ] && rm $3
}

start_service()
{
	local enabled
	local config_file
	local log_path
	local app_id
	local app_key
	local server_addr
	local pid_file
	local device_info
	local cmd
	local log_dir_path

	config_load phtunnel
	config_get enabled base enabled '0'
	[ "$enabled" == "0" ] && {
		echo 'phtunnel is not enabled'
		exit 1
	}

	config_get config_file base config_file '/etc/phtunnel.json' #配置文件路径
	config_get app_id base app_id '' #appid
	config_get app_key base app_key '' #appkey
	config_get server_addr base server 'https://hsk-embed.oray.com' #服务器地址
	config_get pid_file base pid_file '/tmp/phtunnel.pid' #pid文件位置
	config_get log_path log path '/var/log/oraybox/phtunnel.log' #日志位置

	echo 'now start phtunnel'

	log_dir_path="${log_path%/*}"
	[ ! -d "$log_dir_path" ] && mkdir -p $log_dir_path

	cmd="phtunnel -R 100 -c $config_file  -l $log_path --rpc -p $pid_file"
	[ -n "$app_id" -a -n "$app_key" ] && cmd="$cmd --appid "$app_id" --appkey $app_key"
	[ -n "$server_addr" ] && cmd="$cmd  -s $server_addr"
	[ -n "$dev_info" ] && cmd="$cmd --deviceinfo 'mem:32; usb:on; cpu:mipsel'"
	#echo $cmd

	procd_open_instance
	procd_set_param command $cmd
	procd_set_param respawn
	procd_close_instance
}

stop_service()
{
	echo 'now stop phtunnel'

	local enabled
	local config_file
	local pid_file
	local log_path
	config_load phtunnel
	config_get enabled base enabled '0'
	config_get config_file base config_file '/etc/phtunnel.json' #配置文件路径
	config_get pid_file base pid_file '/tmp/phtunnel.pid'
	config_get log_path log path '/var/log/oraybox/phtunnel.log'

	#获取程序的pid
	local pid=$(cat "$pid_file" 2> /dev/null | grep 'pid=' | cut -d'=' -f2 2> /dev/null)
	[ -z "$pid" ] && {
		echo 'phtunnel pid is not found'
		exit_clean $pid_file $log_path
		return 0
	}

	#如果enabled为0(禁用)，则删除配置文件
	[ "$enabled" = "0" -a -f "$config_file" ] && rm $config_file

	#kill程序
	kill "$pid" 2> /dev/null
	for i in $(seq 1 4)
	do
		[ -d "/proc/$pid" ] || {
			echo 'phtunnel processor is stopped'
			exit_clean $pid_file $log_path
			return 0
		}
		echo "phtunnel processor is still alive(pid is $pid), wait 1 second"
		sleep 1
	done

	echo "phtunnel processor is still alive(pid is $pid), kill it"
	kill -9 $pid 2> /dev/null
	exit_clean $pid_file $log_path
}

reload_service() {
	restart
}

service_triggers() {
	procd_add_reload_trigger "phtunnel"
}
