#!/bin/bash
. /lib/functions.sh
. /usr/share/openclash/uci.sh

[ -e "/etc/config/ucitrack" ] && {
uci -q delete ucitrack.@openclash[-1]
uci -q add ucitrack openclash
uci -q set ucitrack.@openclash[-1].init=openclash
uci -q commit ucitrack
}
uci -q delete firewall.openclash
uci -q set firewall.openclash=include
uci -q set firewall.openclash.type=script
uci -q set firewall.openclash.path=/var/etc/openclash.include
[ -n "$(command -v fw4)" ] || uci -q set firewall.openclash.reload=1
uci -q commit firewall

mkdir -p /etc/openclash/config
mkdir -p /etc/openclash/proxy_provider
mkdir -p /etc/openclash/rule_provider
mkdir -p /etc/openclash/core
mkdir -p /etc/openclash/history
mkdir -p /usr/share/openclash/backup/overwrite

#move the dynamic sections written by older builds (separate storage directory) into the
#main configuration, and drop the section types that no longer exist
if [ -f /etc/openclash/uci/openclash ]; then
	cp -f /etc/config/openclash /tmp/openclash.config.before_merge 2>/dev/null
	awk -v keep=1 '/^config /{ keep = ($2 != "groups" && $2 != "proxy-provider" && $2 != "servers") } keep' /etc/config/openclash > /tmp/openclash.merged 2>/dev/null
	echo >> /tmp/openclash.merged
	cat /etc/openclash/uci/openclash >> /tmp/openclash.merged
	if /sbin/uci -q -f /tmp/openclash.merged import openclash && /sbin/uci -q commit openclash; then
		rm -rf /etc/openclash/uci
	fi
	rm -f /tmp/openclash.merged
fi

mkdir -p /lib/upgrade/keep.d
cat > "/lib/upgrade/keep.d/luci-app-openclash" <<-EOF
/etc/openclash/
EOF

#Set Chnroute Format
FW4=$(command -v fw4)
if [ -n "$FW4" ]; then
	#v4
	if [ -z "$(cat "/etc/openclash/china_ip_route.ipset" |grep "define china_ip_route")" ]; then
		echo "define china_ip_route = {" >/tmp/china_ip_route.list
		awk '!/^$/&&!/^#/{printf("    %s,'" "'\n",$0)}' /etc/openclash/china_ip_route.ipset >>/tmp/china_ip_route.list
		echo "}" >>/tmp/china_ip_route.list
		echo "add set inet fw4 china_ip_route { type ipv4_addr; flags interval; auto-merge; }" >>/tmp/china_ip_route.list
		echo 'add element inet fw4 china_ip_route $china_ip_route' >>/tmp/china_ip_route.list
	fi
	#v6
	if [ -z "$(cat "/etc/openclash/china_ip6_route.ipset" |grep "define china_ip6_route")" ]; then
		echo "define china_ip6_route = {" >/tmp/china_ip6_route.list
		awk '!/^$/&&!/^#/{printf("    %s,'" "'\n",$0)}' /etc/openclash/china_ip6_route.ipset >>/tmp/china_ip6_route.list
		echo "}" >>/tmp/china_ip6_route.list
		echo "add set inet fw4 china_ip6_route { type ipv6_addr; flags interval; auto-merge; }" >>/tmp/china_ip6_route.list
		echo 'add element inet fw4 china_ip6_route $china_ip6_route' >>/tmp/china_ip6_route.list
	fi
else
	#v4
	if [ -z "$(cat "/etc/openclash/china_ip_route.ipset" |grep "create china_ip_route")" ]; then
		echo "create china_ip_route hash:net family inet hashsize 1024 maxelem 1000000" >/tmp/china_ip_route.list
		awk '!/^$/&&!/^#/{printf("add china_ip_route %s'" "'\n",$0)}' /etc/openclash/china_ip_route.ipset >>/tmp/china_ip_route.list
	fi
	#v6
	if [ -z "$(cat "/etc/openclash/china_ip6_route.ipset" |grep "create china_ip6_route")" ]; then
		echo "create china_ip6_route hash:net family inet6 hashsize 1024 maxelem 1000000" >/tmp/china_ip6_route.list
		awk '!/^$/&&!/^#/{printf("add china_ip6_route %s'" "'\n",$0)}' /etc/openclash/china_ip6_route.ipset >>/tmp/china_ip6_route.list
	fi
fi
mv -f /tmp/china_ip_route.list /etc/openclash/china_ip_route.ipset >/dev/null 2>&1
mv -f /tmp/china_ip6_route.list /etc/openclash/china_ip6_route.ipset >/dev/null 2>&1

#Set Dashboard Secret
if [ -z "$(uci_get_config "dashboard_password")" ]; then
	uci -q set openclash.config.dashboard_password="$(tr -cd 'a-zA-Z0-9' </dev/urandom 2>/dev/null| head -c8 || date +%N| md5sum |head -c8)"
fi

#Set Authentication
if [ -z "$(uci -q get openclash.@authentication[0])" ]; then
	uci_name_tmp=$(uci -q add openclash authentication)
	uci_set="uci -q set openclash.$uci_name_tmp."
	${uci_set}enabled="1"
	${uci_set}username="Clash"
	${uci_set}password="$(tr -cd 'a-zA-Z0-9' </dev/urandom 2>/dev/null| head -c8 || date +%N| md5sum |head -c8)"
fi

#Set Core Model
source "/etc/openwrt_release"
case "${DISTRIB_ARCH}" in
	aarch64_*)
		CORE_ARCH="linux-arm64"
		;;
	armeb_*)
		CORE_ARCH="0"
		;;
	arm_cortex-a5|arm_cortex-a5[^0-9]*|arm_cortex-a7|arm_cortex-a7[^0-9]*|arm_cortex-a8*|arm_cortex-a9*|arm_cortex-a12*|arm_cortex-a15*|arm_cortex-a17*)
		CORE_ARCH="linux-armv7"
		;;
	arm_arm1176jzf-s*|arm_arm1136*|arm_mpcore*)
		CORE_ARCH="linux-armv6"
		;;
	arm*)
		CORE_ARCH="linux-armv5"
		;;
	i386_*)
		CORE_ARCH="linux-386"
		;;
	mips64el_*)
		CORE_ARCH="linux-mips64le"
		;;
	mips64_*)
		CORE_ARCH="linux-mips64"
		;;
	mips_*)
		CORE_ARCH="linux-mips-softfloat"
		;;
	mipsel_*)
		CORE_ARCH="linux-mipsle-softfloat"
		;;
	riscv64*)
		CORE_ARCH="linux-riscv64"
		;;
	loongarch64*|loongarch_*)
		CORE_ARCH="linux-loong64-abi2"
		;;
	x86_64)
		CORE_ARCH="linux-amd64-v1"
		;;
	*)
		CORE_ARCH="0"
		;;
esac
uci -q set openclash.config.core_version="${CORE_ARCH}"

#Backup Resolvfile
if [ -n "$(uci -q get dhcp.@dnsmasq[0].resolvfile)" ]; then
	uci -q set openclash.config.default_resolvfile=$(uci -q get dhcp.@dnsmasq[0].resolvfile)
fi

# Quic-go GSO Disable
current_kernel=$(uname -r | cut -d'-' -f1)
if [ "$(printf '%s\n' "$current_kernel" "6.6" | sort -V | head -n1)" != "$current_kernel" ]; then
	uci -q set openclash.config.disable_quic_go_gso=1
fi

uci -q commit openclash

#Backup
cp -f "/etc/config/openclash" "/usr/share/openclash/backup/openclash" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_rules.list" "/usr/share/openclash/backup/openclash_custom_rules.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_rules_2.list" "/usr/share/openclash/backup/openclash_custom_rules_2.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_hosts.list" "/usr/share/openclash/backup/openclash_custom_hosts.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_fake_filter.list" "/usr/share/openclash/backup/openclash_custom_fake_filter.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_domain_dns.list" "/usr/share/openclash/backup/openclash_custom_domain_dns.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_domain_dns_policy.list" "/usr/share/openclash/backup/openclash_custom_domain_dns_policy.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_proxy_server_dns_policy.list" "/usr/share/openclash/backup/openclash_custom_proxy_server_dns_policy.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_fallback_filter.yaml" "/usr/share/openclash/backup/openclash_custom_fallback_filter.yaml" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_sniffer.yaml" "/usr/share/openclash/backup/openclash_custom_sniffer.yaml" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_localnetwork_ipv4.list" "/usr/share/openclash/backup/openclash_custom_localnetwork_ipv4.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_localnetwork_ipv6.list" "/usr/share/openclash/backup/openclash_custom_localnetwork_ipv6.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_chnroute_pass.list" "/usr/share/openclash/backup/openclash_custom_chnroute_pass.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_chnroute6_pass.list" "/usr/share/openclash/backup/openclash_custom_chnroute6_pass.list" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_firewall_rules.sh" "/usr/share/openclash/backup/openclash_custom_firewall_rules.sh" >/dev/null 2>&1
cp -f "/etc/openclash/custom/openclash_custom_overwrite.sh" "/usr/share/openclash/backup/openclash_custom_overwrite.sh" >/dev/null 2>&1
cp -f "/etc/openclash/china_ip_route.ipset" "/usr/share/openclash/backup/china_ip_route.ipset" >/dev/null 2>&1
cp -f "/etc/openclash/china_ip6_route.ipset" "/usr/share/openclash/backup/china_ip6_route.ipset" >/dev/null 2>&1
cp -f "/etc/openclash/overwrite/default" "/usr/share/openclash/backup/overwrite/default" >/dev/null 2>&1
cp -f "/etc/openclash/rule_provider/oc-cn-domain.mrs" "/usr/share/openclash/backup/oc-cn-domain.mrs" >/dev/null 2>&1

#Restore
if [ -f "/tmp/openclash.bak" ]; then
	#delete old geosite database first
	if [ "/etc/openclash/GeoSite.dat" -nt "/tmp/openclash/GeoSite.dat" ]; then
		rm -rf "/tmp/openclash/GeoSite.dat" >/dev/null 2>&1
	fi
	#delete error china_ip_route first
	if [ -n "$FW4" ]; then
		if [ -z "$(cat "/tmp/openclash/china_ip_route.ipset" |grep "define china_ip_route")" ]; then
			rm -f "/tmp/openclash/china_ip_route.ipset" >/dev/null 2>&1
			rm -f "/tmp/openclash/china_ip6_route.ipset" >/dev/null 2>&1
		fi
	else
		if [ -z "$(cat "/tmp/openclash/china_ip_route.ipset" |grep "create china_ip_route")" ]; then
			rm -f "/tmp/openclash/china_ip_route.ipset" >/dev/null 2>&1
			rm -f "/tmp/openclash/china_ip6_route.ipset" >/dev/null 2>&1
		fi
	fi
	mv -f "/tmp/openclash.bak" "/etc/config/openclash" >/dev/null 2>&1
	cp -rf "/tmp/openclash/." "/etc/openclash/" >/dev/null 2>&1
	#ui
	if [ -d "/tmp/openclash_ui/" ]; then
		if [ -d "/tmp/openclash_ui/metacubexd/" ] || [ -d "/tmp/openclash_ui/zashboard/" ] || [ -d "/tmp/openclash_ui/yacd/" ] || [ -d "/tmp/openclash_ui/dashboard/" ]; then
			rm -rf "/usr/share/openclash/ui/" >/dev/null 2>&1
			cp -rf "/tmp/openclash_ui/." "/usr/share/openclash/ui/" >/dev/null 2>&1
		fi
		rm -rf "/tmp/openclash_ui/" >/dev/null 2>&1
	fi
	#pac
	if [ -d "/tmp/pac/" ]; then
		rm -rf "/www/luci-static/resources/openclash/pac/" >/dev/null 2>&1
		cp -rf "/tmp/pac/." "/www/luci-static/resources/openclash/pac/" >/dev/null 2>&1
		rm -rf "/tmp/pac/" >/dev/null 2>&1
	fi
	#oc-domain
	if [ -f "/etc/openclash/rule_provider/oc-cn-domain.mrs" ]; then
		cp -f "/usr/share/openclash/backup/oc-cn-domain.mrs" "/etc/openclash/rule_provider/oc-cn-domain.mrs" >/dev/null 2>&1
	fi
	rm -rf "/etc/openclash/openclash" >/dev/null 2>&1
	rm -rf "/tmp/openclash" >/dev/null 2>&1
	rm -rf "/tmp/openclash.bak" >/dev/null 2>&1
	#old version files
	rm -rf "/etc/openclash/fake_filter.list" >/dev/null 2>&1
	rm -rf "/etc/openclash/openclash_servers_fake_filter.conf" >/dev/null 2>&1
	rm -rf "/etc/openclash/core/clash" >/dev/null 2>&1
	rm -rf "/etc/openclash/core/clash_tun" >/dev/null 2>&1
	rm -rf "/etc/openclash/accelerated-domains.china.conf" >/dev/null 2>&1
	rm -rf "/etc/openclash/custom/openclash_force_sniffing_domain.yaml" >/dev/null 2>&1
	rm -rf "/etc/openclash/custom/openclash_sniffing_ports_filter.yaml" >/dev/null 2>&1
	rm -rf "/etc/openclash/custom/openclash_sniffing_port_filter.yaml" >/dev/null 2>&1
	rm -rf "/etc/openclash/custom/openclash_sniffing_domain_filter.yaml" >/dev/null 2>&1
	rm -rf "/etc/openclash/backup" >/dev/null 2>&1
fi

#long-running requests (streaming log)
#uhttpd backend (older LuCI)
if [ -x /etc/init.d/uhttpd ]; then
	uci -q set uhttpd.@uhttpd[0].max_requests=50
	uci -q set uhttpd.@uhttpd[0].script_timeout=3600
	uci -q commit uhttpd
fi
#nginx backend (luci-nginx, newer LuCI)
#gzip_types: nginx only compresses text/html by default, so the openclash
#static assets (js/css/svg) and the JSON API answers are sent uncompressed
if [ -d /etc/nginx/conf.d ]; then
	UWSGI_TIMEOUT="uwsgi_read_timeout 3600;"
	GZIP_TYPES="gzip_types text/css application/javascript image/svg+xml application/json;"
	nginx -V 2>&1 | grep -q 'without-http_uwsgi_module' && UWSGI_TIMEOUT=""
	nginx -V 2>&1 | grep -q 'without-http_gzip_module' && GZIP_TYPES=""
	cat > /etc/nginx/conf.d/openclash.conf <<-EOF
	$UWSGI_TIMEOUT
	$GZIP_TYPES
	EOF
	#same-origin proxy for the dashboard API so https pages can use wss
	[ -x /usr/share/openclash/openclash_nginx.sh ] && /usr/share/openclash/openclash_nginx.sh -n
fi

[ -x /etc/init.d/uhttpd ] && /etc/init.d/uhttpd restart >/dev/null 2>&1
[ -x /etc/init.d/nginx ] && /etc/init.d/nginx reload >/dev/null 2>&1

rm -rf /tmp/luci-indexcache /tmp/luci-indexcache.* /var/luci-indexcache /var/luci-indexcache.* >/dev/null 2>&1
rm -rf /tmp/luci-modulecache /var/luci-modulecache >/dev/null 2>&1
exit 0
