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

START=99
SERVICE_WRITE_PID=1
SERVICE_DAEMONIZE=1

LOGFILE="/var/etc/frp/frpc.log"

echo_date(){
	local log=$1
	echo $(date +%Y/%m/%d\ %X): "$log" >> $LOGFILE
}

Reduce_Log(){
	local log=$1
	[ ! -f "$log" ] && return
	local sc=200
	[ -n "$2" ] && sc=$2
	local count=$(grep -c "" $log)
	if [ $count -gt $sc ];then
		let count=count-$sc
		sed -i "1,$count d" $log
	fi
}

conf_proxy_add() {

	local cfg="$1"
	local tmpconf="$2"
	local enable type domain_type custom_domains remote_port local_ip local_port enable_http_auth enable_host_header_rewrite host_header_rewrite
	local subdomain use_encryption use_compression http_user http_pwd remark locations
	local enable_plugin plugin plugin_http_user plugin_http_passwd plugin_unix_path stcp_role stcp_secretkey stcp_servername
	
	config_get_bool enable "$cfg" enable 1
	[ "$enable" -gt 0 ] || return 1
	
	config_get type "$cfg" type
	config_get custom_domains "$cfg" custom_domains
	config_get subdomain "$cfg" subdomain
	config_get remote_port "$cfg" remote_port
	config_get local_ip "$cfg" local_ip
	config_get local_port "$cfg" local_port
	config_get locations "$cfg" locations
	config_get host_header_rewrite "$cfg" host_header_rewrite
	config_get http_user "$cfg" http_user
	config_get http_pwd "$cfg" http_pwd
	config_get remark "$cfg" remark
	config_get plugin "$cfg" plugin
	config_get plugin_http_user "$cfg" plugin_http_user
	config_get plugin_http_passwd "$cfg" plugin_http_passwd
	config_get plugin_unix_path "$cfg" plugin_unix_path
	config_get stcp_role "$cfg" stcp_role
	config_get stcp_secretkey "$cfg" stcp_secretkey
	config_get stcp_servername "$cfg" stcp_servername


	[ -n "$remark" ] && [ -n "$type" ] || return 1
	
	echo "" >>$tmpconf
	echo "[$remark]" >>$tmpconf
	echo "type=$type" >>$tmpconf
	[ -n "$custom_domains" ] && echo "custom_domains=$custom_domains" >>$tmpconf
	[ -n "$subdomain" ] && echo "subdomain=$subdomain" >>$tmpconf
	[ -n "$remote_port" ] && echo "remote_port=$remote_port" >>$tmpconf
	[ -z "$stcp_role" ] && [ -n "$local_ip" ] && echo "local_ip=$local_ip" >>$tmpconf
	[ -z "$stcp_role" ] && [ -n "$local_port" ] && echo "local_port=$local_port" >>$tmpconf
	[ -n "$locations" ] && echo "locations=$locations" >>$tmpconf
	[ -n "$http_user" -a -n "$http_pwd" ] && {
		echo "http_user=$http_user" >>$tmpconf
		echo "http_pwd=$http_pwd" >>$tmpconf
	}
	[ -n "$host_header_rewrite" ] && echo "host_header_rewrite=$host_header_rewrite" >>$tmpconf
	[ -n "$plugin" ] && echo "plugin=$plugin" >>$tmpconf
	[ -n "$plugin_http_user" -a -n "$plugin_http_passwd" ] && {
		echo "plugin_http_user=$plugin_http_user" >>$tmpconf
		echo "plugin_http_passwd=$plugin_http_passwd" >>$tmpconf
	}
	[ -n "$plugin_unix_path" ] && echo "plugin_unix_path=$plugin_unix_path" >>$tmpconf
	
	[ -n "$stcp_role" ] && {
		if [ "$stcp_role" == "vistor" ]; then
			echo "role=$stcp_role" >>$tmpconf
			[ -n "$local_ip" ] && echo "bind_addr=$local_ip" >>$tmpconf
			[ -n "$local_port" ] && echo "bind_port=$local_port" >>$tmpconf
			[ -n "$stcp_servername" ] && echo "server_name=$stcp_servername" >>$tmpconf || return 1
		else
			[ -n "$local_ip" ] && echo "local_ip=$local_ip" >>$tmpconf
			[ -n "$local_port" ] && echo "local_port=$local_port" >>$tmpconf
		fi
		[ -n "$stcp_secretkey" ] && echo "sk=$stcp_secretkey" >>$tmpconf || return 1
	}
	
	

	frp_write_bool use_encryption $cfg 1
	frp_write_bool use_compression $cfg 1

}

frp_write_bool() {
	local opt="$1"
	local config="$2"
	local def="$3"
	local val

	config_get_bool val $config "$opt" "$def"
	if [ "$val" -eq 0 ]; then
		echo "${opt}=false" >> $tmpconf
	else
		echo "${opt}=true" >> $tmpconf
	fi
}

frp_add_cru(){
time=$1
if [ ! -f "/etc/crontabs/root" ] || [ -z "$(cat /etc/crontabs/root | grep frp)" ]; then
  sed -i '/frp/d' /etc/crontabs/root >/dev/null 2>&1
  echo "*/$time * * * * /etc/init.d/frp restart" >> /etc/crontabs/root 
fi
crontab /etc/crontabs/root
/etc/init.d/cron restart
}

frp_del_cru(){
if [ ! -f "/etc/crontabs/root" ] || [ -n "$(cat /etc/crontabs/root | grep frp)" ]; then
  sed -i '/frp/d' /etc/crontabs/root >/dev/null 2>&1
fi
/etc/init.d/cron restart
}

routercpu(){
	for a in $(opkg print-architecture | awk '{print $2}'); do
		case "$a" in
			all|noarch)
				;;
			aarch64_armv8-a|arm_arm1176jzf-s_vfp|arm_arm926ej-s|arm_cortex-a15_neon-vfpv4|arm_cortex-a5|arm_cortex-a53_neon-vfpv4|arm_cortex-a7_neon-vfpv4|arm_cortex-a8_vfpv3|arm_cortex-a9|arm_cortex-a9_neon|arm_cortex-a9_vfpv3|arm_fa526|arm_mpcore|arm_mpcore_vfp|arm_xscale|armeb_xscale)
				ARCH="arm"
				;;
			aarch64_cortex-a53)
				ARCH="arm64"
				;;
			i386_pentium|i386_pentium4)
				ARCH="386"
				;;
			ar71xx|mips_24kc|mips_mips32|mips64_octeon)
				ARCH="mips"
				;;
			mipsel_24kc|mipsel_24kec_dsp|mipsel_74kc|mipsel_mips32|mipsel_1004kc_dsp|ramips_1004kc|ramips_24kec)
				ARCH="mipsle"
				;;
			x86_64)
				ARCH="amd64"
				;;
			*)
				echo $(date "+%F %T"): Architectures $a not support >>$LOGFILE
				exit 0
				;;
		esac
	done

	echo $(date "+%F %T"): Target Arch: $ARCH >>$LOGFILE
}

downfile(){

    	for a in $(uci get frp.common.url); do
		case "$a" in
			1)
				download="download_binary"
				;;
			2)
				download="download_binary2"
				;;
			3)
				download="download_binary3"
				;;
			*)
				echo $(date "+%F %T"): error.
				exit 0
				;;
		esac
	echo $a
	done
}

download_binary(){
	stop
	routercpu
	echo_date "开始下载frpc二进制文件..."
	filever=$ver
	tarfile=frp_"$filever"_linux_"$ARCH".tar.gz
	tmpfile=/tmp/etc/tmp_frpc
	rm -rf $bin_path

	[ ! -s "/tmp/$tarfile" ] && [ ! -f "$bin_path" ] && wget --no-check-certificate --timeout=10 --tries=10 -o $LOGFILE https://download.lyin.org/frp/v$filever/$tarfile -O /tmp/$tarfile && echo_date "成功下载frpc二进制文件..."

	[ -f /tmp/$tarfile ] && tar zxvf /tmp/$tarfile -C /tmp && \
	mv /tmp/frp_"$filever"_linux_$ARCH/frpc  $bin_path
	[ -f "$bin_path" ] && ln -s $bin_path /usr/bin/frpc

	if [ -L /usr/bin/frpc ]; then
		chmod +x $bin_path && [ -x "$bin_path" ] && echo_date "frpc 下载完成"
	rm -rf /tmp/frp_"$filever"_linux_"$ARCH"*
	else
		echo_date "下载frpc二进制文件失败，请重试！"
	fi
}

download_binary2(){
	stop
	routercpu
	echo_date "开始下载frpc二进制文件..."
	filever=$ver
	tarfile=frp_"$filever"_linux_"$ARCH".tar.gz
	tmpfile=/tmp/etc/tmp_frpc
	rm -rf $bin_path

	[ ! -s "/tmp/$tarfile" ] && [ ! -f "$bin_path" ] && wget --no-check-certificate --timeout=10 --tries=10 -o $LOGFILE https://download.lyin.org/frp/v$filever/$tarfile -O /tmp/$tarfile && echo_date "成功下载frpc二进制文件..."

	[ -f /tmp/$tarfile ] && tar zxvf /tmp/$tarfile -C /tmp && \
	mv /tmp/frp_"$filever"_linux_$ARCH/frpc  $bin_path
	[ -f "$bin_path" ] && ln -s $bin_path /usr/bin/frpc

	if [ -L /usr/bin/frpc ]; then
		chmod +x $bin_path && [ -x "$bin_path" ] && echo_date "frpc 下载完成"
	rm -rf /tmp/frp_"$filever"_linux_"$ARCH"*
	else
		echo_date "下载frpc二进制文件失败，请重试！"
	fi
}

download_binary3(){
	stop
	routercpu
	echo_date "开始下载frpc二进制文件..."
	filever=$ver
	tarfile=frp_"$filever"_linux_"$ARCH".tar.gz
	tmpfile=/tmp/etc/tmp_frpc
	rm -rf $bin_path

	[ ! -s "/tmp/$tarfile" ] && [ ! -f "$bin_path" ] && wget --no-check-certificate --timeout=10 --tries=10 -o $LOGFILE https://download.lyin.org/frp/v$filever/$tarfile -O /tmp/$tarfile && echo_date "成功下载frpc二进制文件..."

	[ -f /tmp/$tarfile ] && tar zxvf /tmp/$tarfile -C /tmp && \
	mv /tmp/frp_"$filever"_linux_$ARCH/frpc  $bin_path
	[ -f "$bin_path" ] && ln -s $bin_path /usr/bin/frpc

	if [ -L /usr/bin/frpc ]; then
		chmod +x $bin_path && [ -x "$bin_path" ] && echo_date "frpc 下载完成"
	rm -rf /tmp/frp_"$filever"_linux_"$ARCH"*
	else
		echo_date "下载frpc二进制文件失败，请重试！"
	fi
}
boot() {
	sleep 10s
	start
}

boot() {
	sleep 10s
	start
}

start() {

	config_load "frp"
	local enabled server_addr server_port time privilege_token tcp_mux enable_cpool bin_path time ver url
	local pool_count log_level log_max_days login_fail_exit http_proxy protocol

	config_get_bool enabled common enabled 1

	[ "$enabled" -gt 0 ] || return 1

	config_get server_addr common server_addr
	config_get server_port common server_port
	config_get privilege_token common privilege_token
	config_get enable_cpool common enable_cpool
	config_get pool_count common pool_count
	config_get log_level common log_level
	config_get log_max_days common log_max_days
	config_get http_proxy common http_proxy
	config_get protocol common protocol
	config_get time common time
	config_get ver common ver
	config_get bin_path common bin_path

	mkdir -p /var/etc/frp
	downfile
	[ ! -f "$LOGFILE" ] && touch $LOGFILE

	[ -f "$bin_path" ] && chmod +x $bin_path  && echo_date "frpc 正常" && ln -s $bin_path /usr/bin/frpc

	[ ! -f "/usr/bin/frpc" ] && $download

	[ "$ver" != "$(/usr/bin/frpc -v)" ] && echo "重新下载frpc" && rm -rf /usr/bin/frpc && $download

	[ ! -f "/usr/bin/frpc" ] && logger -t Frp '下载frpc二进制文件失败，请重试' && exit 0

	local tmpconf="/var/etc/frp/frpc.conf"

	echo "[common]" >$tmpconf
	echo "server_addr=${server_addr}" >>$tmpconf
	echo "server_port=${server_port}" >>$tmpconf
	echo "privilege_token=${privilege_token}" >>$tmpconf
	echo "log_level=${log_level}" >>$tmpconf
	echo "log_max_days=${log_max_days}" >>$tmpconf
	echo "protocol=${protocol}" >>$tmpconf
	echo "log_file=$LOGFILE" >>$tmpconf
	[ -n "$http_proxy" ] && echo "http_proxy=$http_proxy" >>$tmpconf
	[ -n "$pool_count" ] && echo "pool_count=$pool_count" >>$tmpconf

	config_load "frp"
	frp_write_bool tcp_mux common 1
	frp_write_bool login_fail_exit common 1
	config_foreach conf_proxy_add proxy "$tmpconf"

	[ "$(cat "$tmpconf" | grep -c "type=")" -gt 0 ] || (echo_date "frp服务启动失败，请首先添加服务列表！" && exit 0)
	logger -t FRPC 'Starting frp service'
	SERVICE_DAEMONIZE=1 \
		service_start /usr/bin/frpc -c $tmpconf

	[ "$time" -gt 0 ] && frp_add_cru $time
	[ -z "$(pgrep /usr/bin/frpc)" ] && echo_date "frp服务启动失败，请检查服务端 “TCP多路复用(tcp_mux)”设置，确保与客户端完全一致！"

	return 0
}

stop() {
	frp_del_cru
	if [ -n "`pidof frpc`" ]; then
		logger -t FRPC 'Shutting down frp service'
		service_stop /usr/bin/frpc
		service_stop $bin_path
		Reduce_Log $LOGFILE
	fi
	return 0
}

restart() {
stop
start
}
