#!/bin/sh /etc/rc.common
#
# Copyright 2021-2022 Michael Zhang <probezy@gmail.com>
# Licensed to the public under the MIT License.
#

START=99
STOP=15

USE_PROCD=1

NAME=cpolar

CONFIG_FOLDER=/etc/$NAME
DEFAULT_CONFIG_FILE=$CONFIG_FOLDER/cpolar.yml

LOG_LEVEL=info

if [ -r /usr/share/libubox/jshn.sh ] ; then
	. /usr/share/libubox/jshn.sh
elif [ -r /lib/functions/jshn.sh ] ; then
	. /lib/functions/jshn.sh
else
	logger -p daemon.err -t "$NAME" "Package required: jshn."
	echo "[err] Package required: jshn." >&2
	exit 1
fi

_log() {
	local level="$1" ; shift
	local msg="$@"
	logger -p "daemon.$level" -t "$NAME" "$msg"

	echo "[$level] $msg" >&2
}

_info() {
	_log "info" $@
}


_debug() {
	if [ $LOG_LEVEL == "debug" ] ; then
		_log "debug" $@
	fi
}

_err() {
	_log "err" $@
}

cpolar_section_validate() {
	uci_validate_section "$NAME" "cpolar" "$1" \
		'enabled:bool:0' \
		'cpolar_file:string' \
		'mem_percentage:and(uinteger, max(100)):80' \
		'config_file:file' \
		'loglevel:or("debug", "info", "warning", "error", "none")' \
		'access_log:string' \
		'error_log:string' \
		'authtoken:string'

}

tunnel_section_validate() {
	uci_validate_section "$NAME" "tunnel" "$1" \
		'enabled:bool:0' \
		'addr:string' \
		'proto:or("http", "tcp", "ftp", "tls", "nas")' \
		'region:string' \
		'remote_addr:string' \
		'subdomain:string' \
		'hostname:string' \
		'client_cas:string' \
		'inspect:string' \
		'auth:string' \
		'host_header:string' \
		'bind_tls:string' \
		'disable_keep_alives:string' \
		'redirect_https:string' \
		'crt:file' \
		'key:string' \
		'domainType:string' \
		'portType:string'
}

get_commands_from_json() {
	local json="$1"

	test -n "$json" || return

	jshn -r "$json" 2>/dev/null | grep -v "json_init"
}

add_tunnel_section() {
	local section="$1"
  
	if ! tunnel_section_validate "$section" ; then
		_err "Invalid config."
		return 1
	fi

	if [ "x$enabled" != "x1" ] ; then
		_info "Tunnel disabled: $section"
		return 0
	fi
	
	_debug "tunnelName = $section"
	json_add_object $section

	test -n "$addr" && \
		json_add_string "addr" "$addr"

	test -n "$proto" && \
		json_add_string "proto" "$proto"

	test -n "$region" && \
		json_add_string "region" "$region"

case $proto in
	tcp)
			_debug "tcp..."
			case $portType in
				randPort)
							_debug "portType = randPort"
							;;
				fixedPort)
							_debug "portType = fixedPort"
							test -n "$remote_addr" && \
								json_add_string "remote_addr" "$remote_addr"
							;;
				*)
							_debug "portType = randPort"
							;;
			esac
			;;
	http)
				_debug "http..."

				case $domainType in
					randDomain)
										_debug "domainType = randDomain"
										;;
					subDomain)
									  _debug "domainType = subDomain"
										test -n "$subdomain" && \
											json_add_string "subdomain" "$subdomain"
										;;
					custDomain)
										_debug "domainType = custDomain"
										test -n "$hostname" && \
											json_add_string "hostname" "$hostname"

										test -n "$crt" && \
											json_add_string "crt" "$crt"

										test -n "$key" && \
											json_add_string "key" "$key"

										test -n "$client_cas" && \
											json_add_string "client_cas" "$client_cas"
										;;
					*)
										_debug "domainType = randDomain"
										;;
				esac

				test -n "$inspect" && \
					json_add_string "inspect" "$inspect"

				test -n "$auth" && \
					json_add_string "auth" "$auth"

				test -n "$host_header" && \
					json_add_string "host_header" "$host_header"

				test -n "$bind_tls" && \
					json_add_string "bind_tls" "$bind_tls"


				test -n "$disable_keep_alives" && \
					json_add_string "disable_keep_alives" "$disable_keep_alives"


				test -n "$redirect_https" && \
					json_add_string "redirect_https" "$redirect_https"
				;;

	*)
				_debug "unknown..."
				;;
	esac

  json_close_object

}


start_instance() {
	local section="$1"

	if ! cpolar_section_validate "$section" ; then
		_err "Invalid config."
		return 1
	fi

	if [ "x$enabled" != "x1" ] ; then
		_info "Service disabled: $section"
		return 0
	fi

	if [ -z "$cpolar_file" ] || [ ! -s "$cpolar_file" ] ; then
		_err "Invalid Cpolar file."
		return 1
	fi

	test -x "$cpolar_file" || chmod 755 "$cpolar_file"

	local temp_config

		_debug "setp 1"

	if [ -n "$config_file" ] ; then
    _debug "setp 2.a"
		if [ ! -s "$config_file" ] ; then
			_err "Config file not found: $config_file"
			return 1
		fi

		# if ! ( eval "$cpolar_file -test -config=\"$config_file\" >/dev/null 2>&1" ) ; then
		# 	_err "Validate config file failed: $config_file"
		# 	return 1
		# fi

		temp_config="$config_file"
		_debug "setp 2.a.1"
		_debug $temp_config
	else
    _debug "setp 2.b"

		test -d "$CONFIG_FOLDER" || mkdir -p "$CONFIG_FOLDER"

    _debug "setp 2.b.1"

		temp_config=$DEFAULT_CONFIG_FILE
    _debug "setp 2.b.2"


		if [ ! -s "$temp_config" ] ; then
			_err "Error when create config file: $temp_config"
			return 1
		fi
 	fi
  
	local nofile=$(cat /proc/sys/fs/nr_open)

	procd_open_instance
	procd_set_param stderr 1
	procd_set_param command "$cpolar_file" start-all  -daemon=on -dashboard=on -config=$temp_config -log=$access_log
	procd_set_param pidfile "/var/run/${NAME}.pid"
	procd_set_param respawn
	procd_set_param limits nofile="${nofile} ${nofile}"
	procd_set_param file /etc/config/cpolar
	procd_set_param term_timeout 60 # wait before sending SIGKILL
	procd_close_instance

}

start_service() {

	config_load "$NAME"

	config_foreach start_instance "general"

}

stop_service() {
	if [ "x$action" = "xrestart" ] ; then
		# skip when restarting, start_service will do this
		return 0
	fi


}


service_triggers() {
	procd_add_reload_trigger "$NAME"
}

service_stopped() {
	killall -9 -q $NAME
}
