#!/bin/sh
# ╔═══════════════════════════════════════════════════════════════════╗
# ║  RSS-Bridge Setup for CyberFeed                                   ║
# ║  Enables Facebook, Twitter, YouTube feeds via RSS-Bridge          ║
# ╚═══════════════════════════════════════════════════════════════════╝

RSSBRIDGE_DIR="/srv/rss-bridge"
RSSBRIDGE_PORT=$(uci -q get cyberfeed.rssbridge.port || echo 3000)

print_banner() {
	echo ""
	echo "╔═══════════════════════════════════════════════════════════╗"
	echo "║  🌉 RSS-BRIDGE SETUP FOR CYBERFEED 🌉                     ║"
	echo "╚═══════════════════════════════════════════════════════════╝"
	echo ""
}

check_deps() {
	echo "📦 Checking dependencies..."

	local missing=""

	command -v php >/dev/null 2>&1 || missing="$missing php8"
	command -v php-cgi >/dev/null 2>&1 || missing="$missing php8-cgi"

	if [ -n "$missing" ]; then
		echo "⚠️  Missing packages:$missing"
		echo ""
		echo "Install with:"
		echo "  opkg update"
		echo "  opkg install$missing php8-mod-curl php8-mod-json php8-mod-mbstring php8-mod-simplexml"
		return 1
	fi

	echo "✅ Dependencies OK"
	return 0
}

install_rssbridge() {
	print_banner

	if ! check_deps; then
		return 1
	fi

	echo ""
	echo "📥 Downloading RSS-Bridge..."

	mkdir -p "$RSSBRIDGE_DIR"

	# Download latest release
	wget -q -O /tmp/rss-bridge.zip \
		"https://github.com/RSS-Bridge/rss-bridge/releases/latest/download/rss-bridge.zip" || {
		echo "❌ Download failed"
		return 1
	}

	echo "📦 Extracting..."
	unzip -q -o /tmp/rss-bridge.zip -d "$RSSBRIDGE_DIR"
	rm -f /tmp/rss-bridge.zip

	# Configure whitelist (enable common bridges)
	cat > "${RSSBRIDGE_DIR}/whitelist.txt" << 'EOF'
Facebook
Twitter
Youtube
Mastodon
Reddit
Instagram
Telegram
Bandcamp
SoundCloud
*
EOF

	# Create init script
	cat > /etc/init.d/rss-bridge << 'INITEOF'
#!/bin/sh /etc/rc.common
START=96
STOP=10
USE_PROCD=1

RSSBRIDGE_DIR="/srv/rss-bridge"

start_service() {
	local enabled port
	config_load cyberfeed
	config_get enabled rssbridge enabled 0
	config_get port rssbridge port 3000

	[ "$enabled" = "1" ] || return 0

	procd_open_instance
	procd_set_param command php-cgi -b 127.0.0.1:9000 -d cgi.fix_pathinfo=1
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance

	# Also start simple HTTP server for RSS-Bridge
	procd_open_instance rss-bridge-http
	procd_set_param command php -S 0.0.0.0:${port} -t ${RSSBRIDGE_DIR}
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}
INITEOF
	chmod +x /etc/init.d/rss-bridge

	echo ""
	echo "╔═══════════════════════════════════════════════════════════╗"
	echo "║  ✅ RSS-BRIDGE INSTALLED                                  ║"
	echo "╠═══════════════════════════════════════════════════════════╣"
	echo "║  📁 Location: /srv/rss-bridge                             ║"
	printf "║  🌐 URL: http://your-router:%s                       ║\n" "$RSSBRIDGE_PORT"
	echo "║                                                           ║"
	echo "║  To enable:                                               ║"
	echo "║    uci set cyberfeed.rssbridge.enabled=1                  ║"
	echo "║    uci commit cyberfeed                                   ║"
	echo "║    /etc/init.d/rss-bridge start                           ║"
	echo "╚═══════════════════════════════════════════════════════════╝"
}

start_rssbridge() {
	local enabled=$(uci -q get cyberfeed.rssbridge.enabled || echo 0)

	if [ "$enabled" != "1" ]; then
		echo "⚠️  RSS-Bridge is disabled"
		echo "Enable with: uci set cyberfeed.rssbridge.enabled=1 && uci commit"
		return 1
	fi

	if [ ! -d "$RSSBRIDGE_DIR" ]; then
		echo "❌ RSS-Bridge not installed. Run: rss-bridge-setup install"
		return 1
	fi

	/etc/init.d/rss-bridge start
	echo "✅ RSS-Bridge started on port $RSSBRIDGE_PORT"
}

stop_rssbridge() {
	/etc/init.d/rss-bridge stop 2>/dev/null
	echo "⏹️  RSS-Bridge stopped"
}

status_rssbridge() {
	local enabled=$(uci -q get cyberfeed.rssbridge.enabled || echo 0)
	local running="false"

	if pgrep -f "rss-bridge" >/dev/null 2>&1 || pgrep -f "php.*$RSSBRIDGE_PORT" >/dev/null 2>&1; then
		running="true"
	fi

	cat << EOF
{
	"installed": $([ -d "$RSSBRIDGE_DIR" ] && echo "true" || echo "false"),
	"enabled": $enabled,
	"running": $running,
	"port": $RSSBRIDGE_PORT,
	"path": "$RSSBRIDGE_DIR"
}
EOF
}

case "$1" in
	install)
		install_rssbridge
		;;
	start)
		start_rssbridge
		;;
	stop)
		stop_rssbridge
		;;
	status)
		status_rssbridge
		;;
	*)
		echo "Usage: $0 {install|start|stop|status}"
		echo ""
		echo "RSS-Bridge converts social media pages to RSS feeds:"
		echo "  - Facebook pages/groups"
		echo "  - Twitter/X accounts"
		echo "  - YouTube channels"
		echo "  - Mastodon accounts"
		echo "  - And many more..."
		;;
esac
