#!/bin/sh
# SecuBox post-installation script
# Ensures appstore catalog and permissions are correct

[ -n "${IPKG_INSTROOT}" ] || {
	# Check if appstore catalog exists
	if [ ! -f /usr/share/secubox/appstore/apps.json ]; then
		echo "WARNING: SecuBox appstore catalog not found at /usr/share/secubox/appstore/apps.json"

		# Try to restore from package ROM overlay
		if [ -f /rom/usr/share/secubox/appstore/apps.json ]; then
			echo "  Restoring from package overlay..."
			mkdir -p /usr/share/secubox/appstore
			cp /rom/usr/share/secubox/appstore/apps.json /usr/share/secubox/appstore/apps.json
			echo "  ✓ Restored appstore catalog"
		else
			echo "  ERROR: Appstore catalog not found in package!"
			echo "  The app store will be empty until this is fixed."
			echo "  Try: opkg remove luci-app-secubox && opkg install luci-app-secubox"
		fi
	fi

	# Set proper permissions (safe even if files don't exist)
	chmod 755 /usr/share/secubox 2>/dev/null || true
	chmod 755 /usr/share/secubox/appstore 2>/dev/null || true
	chmod 644 /usr/share/secubox/appstore/apps.json 2>/dev/null || true
	chmod 755 /usr/share/secubox/profiles 2>/dev/null || true

	# Reload RPCD to pick up new methods
	/etc/init.d/rpcd reload 2>/dev/null || true

	echo "SecuBox: Installation complete"
	if [ -f /usr/share/secubox/appstore/apps.json ]; then
		echo "  ✓ Appstore catalog: /usr/share/secubox/appstore/apps.json"
	else
		echo "  ✗ Appstore catalog: MISSING"
	fi
	echo "  ✓ RPCD methods available via: ubus call luci.secubox"
}
exit 0
