#!/bin/sh /etc/rc.common
# Copyright (C) 2010 Jo-Philipp Wich

START=50

USE_PROCD=1

UHTTPD_BIN="/usr/sbin/uhttpd"
PX5G_BIN="/usr/sbin/px5g"
OPENSSL_BIN="/usr/bin/openssl"

# 定义keystore文件路径
KEYSTORE_DIR="/opt/tplink/EAPController/data/keystore"
EAP_KEYSTORE="$KEYSTORE_DIR/eap.keystore"
SMB_KEYSTORE="$KEYSTORE_DIR/smb.keystore"
USER_KEYSTORE="$KEYSTORE_DIR/user.jks"
USER_KEY="$KEYSTORE_DIR/user"

USER_KEY_PASSWORD="18F54B22D2B624AAE592394D354EF79F"
SMB_KEY_PASSWORD="tplink"

UHTTPD_KEY_LENGTH="2048"

all_in_one=`uci -c /etc/profile.d get profile.@global[0].all_in_one`

uhttpd_led_control()
{
	system-led-blink 500
	sleep 3
	system-led-off
}

wait_omadad_started()
{
	local progress_file="/tmp/omada_init_progress"
	#ER7212,uhttpd,port redirect,change port 80->8143,433->8188
	iptables -w -t nat -I PREROUTING -p tcp --dport 80 -m set --match-set VMe dst -m comment --comment "HTTP_REDIRECT" -j REDIRECT --to-port 8143
	iptables -w -t nat -I PREROUTING -p tcp --dport 443 -m set --match-set VMe dst -m comment --comment "HTTPS_REDIRECT" -j REDIRECT --to-port 8188

	if [ ! -f "$progress_file" ]; then
		echo "/etc/config/uhttpd,$progress_file does not exist,touch file" > /dev/console
		touch "$progress_file"
		echo "0" > "$progress_file"
	fi

	uhttpd_led_control
}

append_arg() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	if [ $var = "http_keepalive" ]; then
		local http_keepalive=$(uci -c /etc/profile.d get profile.@uhttpd[0].http_keepalive)
		if [ $http_keepalive ]; then
			val=$http_keepalive
		else
			config_get val "$cfg" "$var"
		fi
	else
		config_get val "$cfg" "$var"
	fi

	[ -n "$val" -o -n "$def" ] && procd_append_param command "$opt" "${val:-$def}"
}

append_bool() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get_bool val "$cfg" "$var" "$def"
	[ "$val" = 1 ] && procd_append_param command "$opt"
}

OPENSSL_CONFIG='
[req]
prompt             = no
distinguished_name = req_distinguished_name
req_extensions     = v3_req

[req_distinguished_name]
C    = CN
ST   = ShenZhen
L    = ShenZhen
CN   = TP-Link

[v3_req]
basicConstraints       = CA:FALSE
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid
subjectAltName         = %s
'

generate_keys() {
	[ -x "$OPENSSL_BIN" ] && {
		local alt_names=""
		local tp_domains=$(uci -c /etc/profile.d get profile.@tp_domain[0].domain)
		[ -z "$tp_domains" ] && tp_domains="omadaer.net"
		for domain in $tp_domains; do
			[ -n "$alt_names" ] && alt_names="$alt_names,"
			alt_names="${alt_names}DNS:*.${domain},DNS:${domain}"
		done

		local openssl_config=$(mktemp)
		printf "${OPENSSL_CONFIG}\n" "$alt_names" > "$openssl_config"
		openssl genrsa -out "$UHTTPD_KEY" $UHTTPD_KEY_LENGTH
		openssl req -x509 -new -key "$UHTTPD_KEY" -out "$UHTTPD_CERT" -outform DER -days 7200 \
			-config "$openssl_config" -extensions v3_req
		rm -f "$openssl_config"
	}
}

check_uhttpd_security_flag()
{
	local config_flag
	config_get config_flag "$cfg" uhttpd_security
	local profile_flag=$(uci -c /etc/profile.d get profile.@uhttpd[0].uhttpd_security)
	echo Get flag profile_flag $profile_flag config_flag $config_flag > /dev/console

	[ -n "$profile_flag" ] && [ -z "$config_flag" ] && {
		echo uhttpd configing.. > /dev/console
		rm $UHTTPD_CERT
		rm /tmp/userconfig/$UHTTPD_CERT

		local redirect_https
		local enable_https

		config_get enable_https "$cfg" listen_https
		config_get redirect_https "$cfg" redirect_https
		echo redirect_https $redirect_https > /dev/console
		[ -n "$enable_https" ] && [ "$redirect_https" != "on" ] && {
			uci set uhttpd.main.redirect_https="on"
		}

		uci set uhttpd.main.uhttpd_security="1"
		uci commit uhttpd
		
		local snmp_enable=`uci get snmpd.agent.snmp_enable`
		echo snmp_enable $snmp_enable > /dev/console
		[ "$snmp_enable" == "off" ] && {
			uci delete snmpd.public.community
			uci commit snmpd
		}
		/lib/cfg_save/config.sh save
	}
}


start_instance()
{
	UHTTPD_CERT=""
	UHTTPD_KEY=""

	local cfg="$1"
	local realm=`cat /proc/sys/kernel/hostname`
	[ ! -n $"realm" ] && {
		realm="OpenWrt"
	}

	local listen http https interpreter indexes path handler

	procd_open_instance
	#procd_set_param respawn
	procd_set_param command "$UHTTPD_BIN" -f

	append_arg "$cfg" home "-h"
	append_arg "$cfg" realm "-r" "${realm:-OpenWrt}"
	append_arg "$cfg" config "-c"
	append_arg "$cfg" cgi_prefix "-x"
	[ -f /usr/lib/uhttpd_lua.so ] && {
		config_get handler "$cfg" lua_handler
		[ -f "$handler" ] && append_arg "$cfg" lua_prefix "-l" && {
			procd_append_param command "-L" "$handler"
		}
	}
	[ -f /usr/lib/uhttpd_ubus.so ] && {
		append_arg "$cfg" ubus_prefix "-u"
		append_arg "$cfg" ubus_socket "-U"
	}
	
	#append_arg "$cfg" script_timeout "-t"
	append_arg "$cfg" network_timeout "-T"
	append_arg "$cfg" http_keepalive "-k"
	#append_arg "$cfg" tcp_keepalive "-A"
	append_arg "$cfg" error_page "-E"
	append_arg "$cfg" max_requests "-n" 3
	append_arg "$cfg" max_connections "-N"

	procd_append_param command "-t" "1800"
        procd_append_param command "-A" "1800"
	
	append_bool "$cfg" no_ubusauth "-a" 0
	append_bool "$cfg" no_symlinks "-S" 0
	append_bool "$cfg" no_dirlists "-D" 0
	append_bool "$cfg" rfc1918_filter "-R" 0

	
	config_get http "$cfg" listen_http
	for listen in $http; do
		 procd_append_param command -p "$listen"
	done

	config_get interpreter "$cfg" interpreter
	for path in $interpreter; do
		procd_append_param command -i "$path"
	done

	config_get indexes "$cfg" index_page
	for path in $indexes; do
		procd_append_param command -I "$path"
	done

	config_get https "$cfg" listen_https
	config_get UHTTPD_KEY  "$cfg" key  /etc/uhttpd.key
	config_get UHTTPD_CERT "$cfg" cert /etc/uhttpd.crt

	check_uhttpd_security_flag

	[ -f /lib/libustream-ssl.so ] && [ -n "$https" ] && {
		[ -f "$UHTTPD_CERT" -a -f "$UHTTPD_KEY" ] || {
			config_foreach generate_keys cert
		}
		key_len=$(openssl rsa -in $UHTTPD_KEY -check -noout -text | grep "RSA Private-Key" | awk -F'[()]' '{print $2}' | cut -d' ' -f1)

        if [ -z $key_len ] || [ $key_len -lt $UHTTPD_KEY_LENGTH ]; then
            config_foreach generate_keys cert
        fi

		#use controller eap crt and key file
		[ -f "$UHTTPD_CERT" -a -f "$UHTTPD_KEY" ] && {
			if [ "x$all_in_one" = "x1" ]; then
				echo "=====uhttpd.init,create smb.keystore=====" > /dev/console
				# eap.keystore not exist,create smb.keystore
				[ -f "$EAP_KEYSTORE" ] || {
					config_foreach generate_keys cert
					[ -f "/etc/smb.jks" ] && rm /etc/smb.jks
					[ -f "/etc/uhttpd.p12" ] && rm /etc/uhttpd.p12
					[ -f "$SMB_KEYSTORE" ] && rm $SMB_KEYSTORE
					openssl x509 -inform DER -in /etc/uhttpd.crt -out /etc/uhttpd.crt.pem
					openssl rsa -inform DER -in $UHTTPD_KEY -outform PEM -out /etc/uhttpd.key.pem
					openssl pkcs12 -export -in /etc/uhttpd.crt.pem -inkey /etc/uhttpd.key.pem -out /etc/uhttpd.p12 -name uhttpd -passout pass:$SMB_KEY_PASSWORD
					chmod 644 /etc/uhttpd.p12
					#delete option -alias eap	
					keytool -importkeystore -deststorepass $SMB_KEY_PASSWORD -destkeypass $SMB_KEY_PASSWORD -destkeystore /etc/smb.jks -srckeystore /etc/uhttpd.p12 -srcstoretype PKCS12 -srcstorepass $SMB_KEY_PASSWORD
					chmod 644 /etc/smb.jks
					cp /etc/smb.jks $SMB_KEYSTORE
					echo "=====$EAP_KEYSTORE not exist,create smb.keystore=====" > /dev/console
				}

				[ -f "$EAP_KEYSTORE" ] && {
					[ -f "$USER_KEYSTORE" ] || {
						cp $EAP_KEYSTORE $SMB_KEYSTORE
						[ -f "/etc/eap.p12" ] && rm /etc/eap.p12
						keytool -importkeystore -srckeystore $EAP_KEYSTORE -destkeystore /etc/eap.p12 -deststoretype PKCS12 -srcstorepass $SMB_KEY_PASSWORD -deststorepass $SMB_KEY_PASSWORD
						openssl pkcs12 -in /etc/eap.p12 -out /etc/uhttpd.crt -nokeys -passin pass:$SMB_KEY_PASSWORD
						openssl pkcs12 -in /etc/eap.p12 -out /etc/uhttpd.key -nocerts -nodes -passin pass:$SMB_KEY_PASSWORD
						chmod 644 /etc/uhttpd.crt
						chmod 644 /etc/uhttpd.key
						echo "=====create new uhttpd.key and uhttpd.crt, based on eap.keystore=====" > /dev/console
					}
				}

				#use controller user crt and key file
				[ -f "$USER_KEYSTORE" ] && {
					[ -f "/etc/eap.p12" ] && rm /etc/eap.p12
					user_key="$(cat $USER_KEY)"
					user_decrypt_pwd="$(echo $user_key | openssl enc -aes-128-ecb -a -K $USER_KEY_PASSWORD -d)"

					keytool -importkeystore -srckeystore $USER_KEYSTORE -destkeystore /etc/eap.p12 -deststoretype PKCS12 -srcstorepass $user_decrypt_pwd -deststorepass $user_decrypt_pwd
					openssl pkcs12 -in /etc/eap.p12 -out /etc/uhttpd.crt -nokeys -passin pass:$user_decrypt_pwd
					openssl pkcs12 -in /etc/eap.p12 -out /etc/uhttpd.key -nocerts -nodes -passin pass:$user_decrypt_pwd
					chmod 644 /etc/uhttpd.crt
					chmod 644 /etc/uhttpd.key
					echo "=====create new uhttpd.key and uhttpd.crt, based on user.jks=====" > /dev/console
				}
			fi
			
			append_arg "$cfg" cert "-C"
			append_arg "$cfg" key  "-K"

			for listen in $https; do
				procd_append_param command -s "$listen"
			done
		}
	}

	procd_close_instance

	# Check if daemon is running, if not then
	# re-execute in foreground to display error.
#	sleep 1 && service_check $UHTTPD_BIN || \
#		$UHTTPD_BIN -f $UHTTPD_ARGS
}

service_triggers()
{
	procd_add_reload_trigger "uhttpd"
}

start_service() {
	local state=$(uci -c /etc/profile.d get profile.@global[0].uhttpd_state)
	if [ "$state" = "0" ]; then
		echo "uhttpd not enable" > /dev/console
		return
	fi

	echo "uhttpd.init,all_in_one:$all_in_one" > /dev/console
	if [ "x$all_in_one" = "x1" ]; then
		sed 's/login\.html/loading.html/g' /www/index.html > /www/index.html.tmp && mv /www/index.html.tmp /www/index.html
	fi

	config_load uhttpd
	config_foreach start_instance uhttpd

	if [ "x$all_in_one" = "x1" ]; then
		wait_omadad_started &
	fi
}

stop_service() {
	pid=$(ps | grep $UHTTPD_BIN | grep -v grep | grep -v '/bin/sh' | awk '{print $1}')
	if [ "x$all_in_one" = "x1" ]; then
		progress=$(/lib/uhttpd/uhttpd_omada_interface.sh get_omada_init_progress)
		if [ "$progress" = "100" ]; then
			echo "stop_service omada_init_progress=100" > /dev/console
			/lib/uhttpd/uhttpd_omada_interface.sh redirect_index_html
			/lib/uhttpd/uhttpd_omada_interface.sh delete_redirect_iptables
		fi
	fi
	if [ -n "$pid" ]; then
		kill -9 $pid
	fi
}
