#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] || {
	/etc/init.d/zapret2 enable

	# Copy default hostlist files only if they don't exist
	# This preserves user modifications during package updates
	IPSET_DIR="/opt/zapret2/ipset"
	for default_file in ${IPSET_DIR}/*.default; do
		[ -f "${default_file}" ] || continue
		target_file="${default_file%.default}"
		if [ ! -f "${target_file}" ]; then
			echo "Creating ${target_file} from default"
			cp "${default_file}" "${target_file}"
			chmod 644 "${target_file}"
		else
			echo "Keeping existing ${target_file}"
		fi
	done

	# Create empty user files if not exist
	[ -f "${IPSET_DIR}/zapret_hosts_user.txt" ] || touch "${IPSET_DIR}/zapret_hosts_user.txt"
	[ -f "${IPSET_DIR}/zapret_hosts_auto.txt" ] || touch "${IPSET_DIR}/zapret_hosts_auto.txt"

	# Sync blob files with UCI config
	# This prevents LuCI from showing "unsaved changes" after package update
	BLOBS_DIR="/opt/zapret2/files/fake"
	BLOBS_CHANGED=0
	for blob_file in ${BLOBS_DIR}/*.bin; do
		[ -f "${blob_file}" ] || continue
		blob_name=$(basename "${blob_file}" .bin)
		# Convert filename to valid UCI section name (replace non-alphanumeric with _)
		section_name="blob_$(echo "${blob_name}" | sed 's/[^a-zA-Z0-9]/_/g')"
		# Add section only if it doesn't exist
		if ! uci -q get zapret2.${section_name} >/dev/null 2>&1; then
			uci set zapret2.${section_name}=blob
			uci set zapret2.${section_name}.path="${blob_file}"
			uci set zapret2.${section_name}.enabled='0'
			BLOBS_CHANGED=1
		fi
	done
	# Commit changes if any blobs were added
	[ "${BLOBS_CHANGED}" = "1" ] && uci commit zapret2
}
exit 0
